我尝试将此组件添加到框架中,但它遇到了同样的问题。所以我创建了一个类和一个面板,我正在尝试这种方式。但现在我有同样的问题。我的按钮都没有出现在框架内。我也得到了一个非法的例子。 (此代码现在有效)我改变了如下所示。
import java.awt.*;
import javax.swing.*;
public class Pan extends JFrame {
public Pan(){
setLayout(new GridLayout(1,1));
JPanel panel1 = new JPanel(new GridLayout(4,3));
JButton zero = new JButton(""+0);
JButton one = new JButton(""+1);
JButton two = new JButton(""+2);
JButton three = new JButton(""+3);
JButton four = new JButton(""+4);
JButton five = new JButton(""+5);
JButton six = new JButton(""+6);
JButton seven = new JButton(""+7);
JButton eight = new JButton(""+8);
JButton nine = new JButton(""+9);
panel1.add(zero);
panel1.add(one);
panel1.add(two);
panel1.add(three);
panel1.add(four);
panel1.add(five);
panel1.add(six);
panel1.add(seven);
panel1.add(eight);
panel1.add(nine);
add(panel1);
}
public static void main(String[] args){
Pan frame = new Pan();
frame.setSize(800, 800);
frame.setLocationRelativeTo(null);
frame.setTitle("Number Pad");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setVisible(true);
}}
答案 0 :(得分:1)
以下行的例外情况 - 将容器的父级添加到自身
panel.add(panel);
另外一项更改总是从EventQueue.invokeLater()
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
Pan frame = new Pan();
...
frame.setVisible(true);
}
});
}
答案 1 :(得分:0)
正如ZouZou指出的那样,void Pan()不是构造函数,因此不会被调用。您还可以将面板添加到框架的rootPane。
试试这段代码:
import java.awt.*;
import javax.swing.*;
public class Pan extends JFrame {
public Pan(){
JPanel panel = new JPanel(new GridLayout(4,3));
JButton zero = new JButton(""+0);
JButton one = new JButton(""+1);
JButton two = new JButton(""+2);
JButton three = new JButton(""+3);
JButton four = new JButton(""+4);
JButton five = new JButton(""+5);
JButton six = new JButton(""+6);
JButton seven = new JButton(""+7);
JButton eight = new JButton(""+8);
JButton nine = new JButton(""+9);
panel.add(zero);
panel.add(one);
panel.add(two);
panel.add(three);
panel.add(four);
panel.add(five);
panel.add(six);
panel.add(seven);
panel.add(eight);
panel.add(nine);
add(panel);
}
public static void main(String[] args){
Pan frame = new Pan();
frame.setSize(800, 800);
frame.setLocationRelativeTo(null);
frame.setTitle("Number Pad");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setVisible(true);
}}