Java eigener hintergrund?
hallo, ich möchte in bluej wenn ich ein frame fenster erstellt habe, das ich ein eigenes Bild als Hintergrund habe machen. habe schon viel von Internet probiert hat aber entweder gar nicht funktioniert oder nicht richtig
danke im vorraus
2 Antworten
Erstelle zunächst eine eigene Subklasse von Container oder JComponent und überschreibe in dieser die paintComponent-Methode:
class BackgroundImagePane extends JComponent {
// ...
@Override
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
graphics.drawImage(this.backgroundImage, 0, 0, this);
}
}
Dann kannst du eine Instanz dieser Klasse als ContentPane für deinen JFrame setzen.
Eine weitere Alternative wäre es, von JPanel zu erben und eine Instanz dieser Klasse an das ContentPane des Frame zu hängen. Wie oben wird das Bild gesetzt, indem du besagte Methode überschreibst.
Beispiel:
ImagePanel panel = new ImagePanel("path/to/your/image");
yourFrame.getContentPane().add(panel);
Das Panel sollte dabei dieselbe Größe wie der Frame bekommen.
Ich nutze für einen grafischen Hintergrund der sich in x- und y-Richtung wiederholt folgende Klasse:
public class RepeatingImage extends JPanel {
private Image _image;
private String _direction = "xy";
private String _imagePosition = "bottom";
public RepeatingImage(Image image) {
this._image = image;
};
public RepeatingImage(Image image, String direction) {
this._image = image;
this._direction = direction;
};
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int iw = _image.getWidth(this);
int ih = _image.getHeight(this);
int imagepositiony = 0;
if (iw > 0 && ih > 0) {
for (int x = 0; x < getWidth(); x += iw) {
if( this._direction == "xy" ) {
// repeat picture also in y-axis
for (int y = 0; y < getHeight(); y += ih) {
g.drawImage(_image, x, y, iw, ih, this);
}
} else {
// calculate the image-dimension depending on Panel-width
int ratio = iw / ih;
if ( ratio < 1 ) {
iw = this.getHeight() * ratio;
} else {
ih = this.getWidth() / ratio;
}
if( this._imagePosition == "bottom" ) {
imagepositiony = this.getHeight() - ih;
}
// do not repeat image, just print it
g.drawImage(_image, x, imagepositiony, iw, ih, this);
}
}
}
}
}
Das ruf ich so auf (ich denke das ist das entscheidende für dich):
Image icon = ImageIO.read(GUI.class.getResourceAsStream(backgroundImage));
wrapperPanel = new RepeatingImage(icon);
[..]
wrapperPanel.setLayout(new BorderLayout());
windowMain.getContentPane().add(wrapperPanel);
wobei backgroundImage der Pfad zu einer Grafik-Datei im eigenen Projekt ist.
- woher weiss das programm welches bild ich von meinem ordner haben will 2. wofür sind die ersten 2 konstruktoren 3. wie kann ich das dann in einer anderen klasse aufrufen aber danke