I managed it to create a JPanel with a special picture as Background and put this JPanel in a JFrame. Everytime a resize the JFrame the JPanel and the picture in it with be also resized. The ComponentListener is registered to the JFrame which notifies modifications in its size.
Here's the code:
package examples;
import images.MyImage;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class example3 {
private static JPanel panel = new MyPanel();
private static JFrame frame = new JFrame();
private static class MyPanel extends JPanel {
private static final long serialVersionUID = 1L;
private int width = 0;
private int height = 0;
public static final int DEFAULT_WIDTH = 400;
public static final int DEFAULT_HEIGHT = 100;
public MyPanel(int width, int heigth) {
super.setLayout(new BorderLayout());
setWidth(width);
setHeigth(heigth);
}
public MyPanel() {
super.setLayout(new BorderLayout());
setWidth(DEFAULT_WIDTH);
setHeigth(DEFAULT_HEIGHT);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_SPEED);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawImage(MyImage.IMAGE_BLUE_BLACKGROUND, 0, 0,
getMyPanelWidth(), getMyPanelHeight(), null);
g2d.dispose();
}
@Override
public Dimension preferredSize() {
return new Dimension(getMyPanelWidth(), getMyPanelHeight());
}
private void setWidth(int width) {
this.width = width;
}
private void setHeigth(int height) {
this.height = height;
}
private int getMyPanelHeight() {
return height;
}
private int getMyPanelWidth() {
return width;
}
}
private static class ComponentHandler extends ComponentAdapter{
@Override
public void componentResized(ComponentEvent e) {
super.componentResized(e);
frame.remove(panel);
frame.getContentPane().add(
new MyPanel(frame.getSize().width, frame.getSize().height),
BorderLayout.CENTER);
frame.repaint();
frame.revalidate();
}
}
public static void main(String[] args) {
panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(panel);
frame.addComponentListener(new ComponentHandler());
frame.pack();
frame.setVisible(true);
}
}
The problem is that I'm getting scaling errors:
Is it because the Event Dispatch Thread can not handle all the resize-Events which is fired by the resize-method? Is there any satisfying solution?