我刚接触过Java,我正在为我的大学课程开展一个项目。 我正在进行一场Milionaire比赛但是我被卡住了。
我有一个JFrame类,其中有2个面板。第一个是按钮,第二个是我想按按钮改变的面板。按钮有自己的类和构造函数,对于面板也是如此,因为它们具有不同的布局。我需要在按钮类中创建一个方法来从框架中删除第二个面板并添加第三个面板(在另一个更多的JPanel类中描述)。所以我在技术上需要从按钮类方法到我的JFrame类构造函数。有办法吗?
我的第一个Panel类和我的Button类及其ClickListener方法。 现在我需要知道如何在Button方法中修改我的JFrame类,以便在单击时关闭第一个Panel,在另一个位置打开另一个。
按钮方法
.netcoreapp1.1
主JFrame类
.netstandard1.4
由于
答案 0 :(得分:0)
您只需设置与按钮的动作监听器中的按钮对应的面板。
.caret {
position: relative;
top: 50%;
transform: translateY(-50%);
}
如果所有按钮都是自定义的(public class NuovaPartitaViewer extends JFrame {
public NuovaPartitaViewer() {
JPanel p1 = new JPanel();
p1.add(new JLabel("Panel 1"));
JPanel p2 = new JPanel();
p2.add(new JLabel("Panel 2"));
JPanel p3 = new JPanel();
p3.add(new JLabel("Panel 3"));
JPanel p4 = new JPanel();
p4.add(new JLabel("Panel 4"));
JButton b1 = new JButton("Button 1");
b1.addActionListener(e -> setPanel(p1));
JButton b2 = new JButton("Button 2");
b2.addActionListener(e -> setPanel(p2));
JButton b3 = new JButton("Button 3");
b3.addActionListener(e -> setPanel(p3));
JButton b4 = new JButton("Button 4");
b4.addActionListener(e -> setPanel(p4));
JPanel buttonsPanel = new JPanel(new GridLayout(2, 2));
buttonsPanel.add(b1);
buttonsPanel.add(b2);
buttonsPanel.add(b3);
buttonsPanel.add(b4);
BorderLayout layout = new BorderLayout();
getContentPane().setLayout(layout);
getContentPane().setBackground(Color.BLACK);
add(buttonsPanel, BorderLayout.WEST);
add(p1, BorderLayout.CENTER);
setTitle("CHI VUOL ESSER MILIONARIO?");
pack();
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}
private void setPanel(JPanel p) {
add(p, BorderLayout.CENTER);
revalidate();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new NuovaPartitaViewer());
}
}
),那么您可以直接在该类中添加动作侦听器代码。在构造函数中传递相应的extends JButton
,以便在动作侦听器中使用它。
此外:
JPanel
。pack()
作为方法中的最后一件事。