I am currently trying to allign properly some components inside my frame. I am using GridBagLayout for it but it looks like this line is making troubles :
frame.setContentPane(new ImagePanel(myImage));
I want to center the buttons in the middle but it doesnt work.If i comment it,everything works good. Also tried to create another panel with BorderLayout and CENTER it but it's the same result. I want a background image to my JFrame. What should i do ? Or am i doing something wrong ?
private Image image;
public MainClass(Image image){
this.image = image;
GridBagConstraints c = new GridBagConstraints();
this.setOpaque(false);
this.setLayout(new GridBagLayout());
c.gridx = 0;
c.gridy = 0;
this.add(new JButton("1"), c);
c.gridx = 0;
c.gridy = 1;
this.add(new JButton("2"), c);
c.gridx = 0;
c.gridy = 2;
this.add(new JButton("3", c);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
public static void main(String[] args) throws IOException {
BufferedImage myImage = ImageIO.read(new File("images/city.png"));
JFrame frame = new JFrame();
frame.setContentPane(new MainClass(myImage));
frame.setSize(600, 375);
frame.setUndecorated(true);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
//edit : I just realised i was trying to add to panels to my frame .. it works pretty good at first look.
First you set the ImagePanel as the content pane which is ok. Then you add the MainClass() to the frame which is probably ok. This means the MainClass will be added to the ImagePanel.
By default a JPanel uses a
FlowLayout
so the MainClass will be centered at the top of the panel.You need to set the layout of your ImagePanel to be a
BorderLayout
. Then it should work just like adding the MainClass directly to the frame.