首页 文章

如何设置使用gridLayout的JPanel最大值或首选大小?

提问于
浏览
1

我使用包含两个JPanel的非常简单的框架时遇到了问题 . 问题在于包含四个JButton的Center JPanel的布局 . 如何为按钮设置更好的大小或直接为使用GridLayout的JPanel设置更大的大小 . 关于图片问题:

alt http://img42.imageshack.us/img42/4601/horrible.jpg

这里的代码是:`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);`

哪个是好的解决方案?

亲切的问候

2 回答

  • 2

    不幸的是,gridlayout doesent尊重首选尺寸 . 但是如果你想坚持网格布局,那么你可以尝试这样的事情:

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

    然后代替direclty添加到prova添加像这样:

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

    经测试,完美!还有其他更好的方法

  • 0

    这就是发生在我身上的事情:它绝对附着在网格的上边缘 .

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

    即使在这种情况下,在wrap方法中我可以设置buttons / comp的preferredSize,每个按钮都在它自己的边缘 . 其他解决方案呢?你如何定位计算器的按钮?亲切的问候和thanx angain!

相关问题