【问题标题】:Need to add buttons to a frame. What is wrong with this java code?需要在框架中添加按钮。这个java代码有什么问题?
【发布时间】:2014-01-02 18:27:01
【问题描述】:

我需要用 Java 编写一个计算器,而我却被困在向布局中添加按钮。这段代码有什么问题?我正在尝试使用 for 循环将 10 个按钮添加到 GridBagLayout。我正在使用 Eclipse,它只是说明存在错误,尽管它根本没有识别错误。 谢谢!

some import stuff

@SuppressWarnings("serial")
public class Calculator extends JFrame implements ActionListener {
    private GridBagConstraints grid;
    private JPanel mainPanel = new JPanel();
    private JButton[] button=new JButton[10];


    public Calculator(){                
        mainPanel.setLayout(new GridBagLayout());
        mainPanel.setBorder(BorderFactory.createTitledBorder("Size"));
        grid=new GridBagConstraints();  
        this.setSize(300,250);
        this.getContentPane().add(mainPanel);         
        for (int i = 0; i < button.length; i++) {  
            button[i] = new JButton(""+i);  
            button[i].add(button[i],grid);          
            button[i].addActionListener(this);  
         }  

    }

    public static void main(String[] args){
        Calculator calcFrame=new Calculator();
        calcFrame.setVisible(true);                     

    }
    @Override
    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub

    }   
};

【问题讨论】:

  • 这不仅仅是说“有错误”。打开“问题”视图,并阅读/发布此视图中显示的完整错误消息。如果它是运行时问题而不是编译问题,那么您将获得堆栈跟踪。阅读并发布。
  • 你的问题是一个诚实的问题,但你的问题可以改进。下一次复飞,请发布您的完整错误消息,请制作一个更好的问题标题,一个总结问题本身的标题。

标签: java swing calculator


【解决方案1】:

组件在 Swing 中不能是它们自己的容器。将按钮添加到 mainPanel 而不是组件本身

mainPanel.add(button[i], grid); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多