Currently, I use this code:
public class Test extends JFrame {
static Test t = null;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
t = new Test();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static void addComponentsToPane(Container pane) {
JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
ImageIcon icon;
icon = new ImageIcon(System.getProperty("user.dir") + "/res/background.png");
Image img = icon.getImage() ;
Image newimg = getScaledImage(img, frame.getWidth(), frame.getHeight()) ;
icon = new ImageIcon( newimg );
JLabel background=new JLabel(icon);
//frame.getContentPane().add(background);
background.setLayout(new FlowLayout());
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = frame.getHeight() * 10;
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
pane.add(background, c);
}
private static Image getScaledImage(Image srcImg, int w, int h){
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg, 0, 0, w, h, null);
g2.dispose();
return resizedImg;
}
private void createAndShowGUI() {
frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
static JFrame frame = null;
public Test() {
createAndShowGUI();
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
}
}
This works fine for buttons, but for some reason is not working for a JLabel with an image. How can I make this JLabel/Image fit to the size I would like?
The image is being really tiny at the moment,
When really, the area that the same code with a JButton takes up is more like this:
Also, it is possible for me to get the ImageIcon to be bigger than button 4 as well, which I also would like to avoid.
So how can I stretch/contract the image to fit the area I would like it to have?