Question

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 http://img42.imageshack.us/img42/4601/horrible.jpg !

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

Was it helpful?

Solution

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

OTHER TIPS

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

alt text http://img96.imageshack.us/img96/9431/stillnot.jpg

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top