GridBagLayout and JFrame Content Pane

143 views Asked by At

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.

3

There are 3 answers

0
camickr On BEST ANSWER
    frame.setContentPane(new ImagePanel(myImage));  
    frame.add(new MainClass());

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.

If i comment it,everything works good.

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.

0
Antoniossss On

Most straightfroward and cruel answer is - dont use Java Swings's layout managers that are hardly useable in most cases. Try some third party one

I strongly suggest MIG Layout from http://www.miglayout.com/ It is very powerfull, flexible, easy to use layour manager with a decent documentation and examples.

0
sjohnson On

JLabel background = new JLabel(new ImageIcon(ImageIO.read(...))); setContentPane(background)

...

add all other buttons