我的框架中有 2 个面板,1 个用于按钮(我想使用 radioButton,但现在使用按钮更容易),另一个用于卡片布局面板。我的计划是当我按下特定按钮时对乍得进行洗牌。就像移动按钮会向我显示移动面板卡。移动面板卡有 x0 标签和文本字段,线路面板卡有 x0 和 x1 标签和文本字段。
有 2 个类,1 个用于按钮面板 = 按钮 另一个用于卡片 = PanelMiddle 这是我的代码:
public class PanelMiddle{
JPanel controlPanel = new JPanel();
CardLayout cl = new CardLayout();
JPanel movePanel = new JPanel();
JPanel linePanel = new JPanel();
JLabel x0Label = new JLabel("x0");
JTextField x0TextField = new JTextField(3);
JLabel x1Label = new JLabel("x1");
JTextField x1TextField = new JTextField(3);
public PanelMiddle(){
controlPanel.setLayout(cl);
//move panel
movePanel.setLayout(new GridLayout (1,2));
movePanel.add(x0Label);
movePanel.add(x0TextField);
controlPanel.add(movePanel,"Move"); //add the keyword Move to show the move card
//line panel
linePanel.setLayout(new GridLayout (2,2));
//linePanel.add(x0Label);
linePanel.add(x1Label);
//linePanel.add(x0TextField);
linePanel.add(x1TextField);
controlPanel.add(linePanel,"Line"); // add the keyword Line to show the line card
}
}
In the other class I have:
public class Buttons extends PanelMiddle{
JPanel buttonPanel = new JPanel();
JButton moveB = new JButton ("Move");
JButton lineB = new JButton ("Line");
public Buttons(){
buttonPanel.setLayout(new GridLayout (2,1));
buttonPanel.add(moveB);
buttonPanel.add(lineB);
action();
}
public void action(){
moveB.addActionListener((e) -> {
cl.show(controlPanel,"Move");
});
lineB.addActionListener((e) -> { cl.show(controlPanel,"Line");});
}
}
我得到的结果很奇怪。它没有完全显示我的面板。但是当我尝试评论所有线路面板时,它起作用了。有人解决了吗?
注意:抱歉,我不知道如何编辑这里的文本,所以有点乱。
编辑1:正如guleryuz所说,我从行面板中注释掉了x0Label
和x0TextField
最佳答案
在 swing 组件层次结构中,一个组件只能添加到一个容器中,您将添加 x0Label 和 x0TextField 两个面板。因此,当您添加 x0Labe 两个第二面板(linePanel)时,它将从 movePanel 中删除(x0TextField 的情况相同),因此 movePanel 变为空。
更多详情here
关于java - 用于更改卡片布局中卡片的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37964385/