我正在创建GUI,我不知道如何解决我的问题.我想做的是像在Main中一样从PanelClass创建几个面板.
我不知道如何:
>我的面板中的名称按钮,并给了他们一些功能(就像我尝试按钮b1)
>添加到panel3其他标签和按钮.
我的主要课程
public class Main {
JFrame f;
PanelClass panel1, panel2, panel3;
JButton b1, b2;
public Main() {
b1 = new JButton("asasa");
f = new JFrame();
f.setSize(300, 300);
f.setLayout(new GridBagLayout());
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel1 = new PanelClass(b1, b2, panel1);
panel2 = new PanelClass(b1, b2, panel2);
panel3 = new PanelClass(b1, b2, panel3);
f.add(panel1);
f.add(panel2);
f.add(panel3);
}
public static void main(String[] args) {
Main m = new Main();
}
}
我的Panel类
public class PanelClass extends JPanel {
public PanelClass(JButton btn, JButton btn1, JPanel p) {
super();
p = new JPanel(new GridBagLayout());
btn = new JButton();
btn1 = new JButton();
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
p.add(btn, c);
c.gridx = 0;
c.gridy = 1;
p.add(btn1, c);
add(p);
}
}
解决方法:
>组件一次只能存在于一个可见容器中(除非它被用作flyweight渲染器).因此将相同的按钮放入3个面板将不起作用.
>代码传递了PanelClass构造函数中的按钮,这些按钮被忽略.而是创建了2个新按钮实例.只需将传递的按钮指定给..当我注意到它们不是时,我会说’类级别属性’.完全删除
btn = new JButton();并且将出现在按钮构造函数中传递的文本.
>有关活动,请参阅How to Write an Action Listener.
标签:java,layout,swing,jpanel
来源: https://codeday.me/bug/20190901/1785009.html