1

我正在为计算器制作一个简单的布局,实际上我是 Java 新手并学习基础知识。我的问题是,当我运行此代码时,仅打开一个 JFrame,并且未显示其按钮的其他面板。PLz帮助,我哪里出错了。

    import java.awt.*;
    import javax.swing.*;

    public class Layouts extends JFrame{
        public Layouts(){
            super("Calculator");
            setLookAndFeel();
            setSize(350,350);

            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            BorderLayout border = new BorderLayout();
            setLayout(border);

            GridLayout numbers = new GridLayout(2,2);
            row2.setLayout(numbers);
            row2.add(one);
            row2.add(two);
            row2.add(three);
            row2.add(four);

            GridLayout operators = new GridLayout(2,2);
            row3.setLayout(operators);
            row3.add(plus);
            row3.add(subtract);
            row3.add(multiply);
            row3.add(equals);
            setVisible(true);
        }

        private void setLookAndFeel()
        {
            try
            {
            IManager.setLookAndFeel("com.sun.java.lang.plaf.nimbus.NimbusLookAndFeel");
            }
            catch(Exception exc)
            {
            }
        }

        //row 1
        JPanel row1 = new JPanel();
        JTextField text = new JTextField(20);

        //row 2
        JPanel row2 = new JPanel();
        JButton one = new JButton("1");
        JButton two = new JButton("2");
        JButton three = new JButton("3");
        JButton four = new JButton("4");

        //row3
        JPanel row3 = new JPanel();
        JButton plus = new JButton("+");
        JButton subtract = new JButton("-");
        JButton multiply = new JButton("*");
        JButton equals = new JButton("=");

        public static void main(String[] args)
        {
        Layouts l1 = new Layouts();
        }

   }
4

3 回答 3

0
BorderLayout border = new BorderLayout();
setLayout(border);

但你没有添加任何东西border!添加numbersoperators

于 2012-12-05T19:28:21.227 回答
0

请记住添加所有组件(即 row2、row3 等)

例子:

add(row2,BorderLayout.CENTER)
add(row3,BorderLayout.SOUTH)
于 2012-12-05T19:28:28.353 回答
0

您需要将JPanels 和JButtons 添加到JFrame. 在JFrame这种情况下是你的Layouts班级。所以做类似的事情:

row1.add(text);
this.add(row1); 

row2.add(one);
row2.add(two);
row2.add(three);
row2.add(four);
this.add(row2); 

...

检查本教程是一个非常有用的JButton、JPanel 和 JFrame 示例

于 2012-12-05T19:31:46.463 回答