views:

598

answers:

2

Hi guys, I had problem using a very simple frame containing two JPanel. The problem is on the layout of the Center JPanel that contains four JButton. How can I set a better size for buttons or directly for JPanel that uses the GridLayout. On the picture the problem:

alt !

Here the code: ` JFrame window = new JFrame("Horrible! LOL");

    JTextField textField = new JTextField("");
    textField.setPreferredSize(new Dimension(200,20));
    JPanel textPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    textPanel.add(textField);
    window.add(textPanel, BorderLayout.NORTH);

    JButton plus = new JButton("+");
    //plus.setPreferredSize(new Dimension(50,50)); nothing would change
    JButton minus = new JButton("-");
    JButton per = new JButton("x");
    JButton divide = new JButton("/");
    JPanel prova = new JPanel(new GridLayout(2,2,10,10));
    Dimension d = new Dimension(20,20);
    prova.setMaximumSize(d); // nothing changed!

    prova.add(plus);
    prova.add(minus);
    prova.add(per);
    prova.add(divide);
    window.add(prova, BorderLayout.CENTER);

    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setSize(250,300);
    window.setResizable(false);
    window.setVisible(true);`

Which is a good solution?

Kind regards

+1  A: 

Unfortunately gridlayout doesent respect preferred sizes. But still if you want to stick to grid layout then you can try something like this:

    public static JComponent wrap(JComponent comp)
    {
        JPanel panel = new JPanel();
        panel.add(comp);
        return panel;
    }

And then instead of direclty adding in to prova add like this:

            prova.add(wrap(plus)); 
            prova.add(wrap(minus)); 
            prova.add(wrap(per)); 
            prova.add(wrap(divide));

Tested, Works perfect!! There are other better ways though

Suraj Chandran
Thank you very much, it works but every button is kind of stick on the top edge of the grid. Is it my problem? I'll post on an answer my result, so you can judge. Could you please show me or give me a links about better solutions. Which would be the right layout for this kind of things?kind regards
soneangel
A: 

That's what happen to me: It's definitely attached to the upper edge of the grid.

alt text

Even if in this case, in the wrap method I can set the preferredSize of buttons/comp, every buttons is on its own edge. What about others solutions. How would you position buttons for a calculator? Kind regards and thanx angain!

soneangel