【发布时间】:2021-05-03 14:56:08
【问题描述】:
我试图通过单击 JButton 使第一个 JPanel 消失而使第二个 JPanel 可见。 到目前为止,我只显示了第一个 JPanel,单击 JButton 后,框架为空。 我也尝试用作文来做,所以我不必扩展课程。所以我对如何 作曲作品可能是问题所在。我研究了很多,但找不到适合我的问题的解决方案。
第一个 JPanel 类:
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Panel1 {
JPanel firstscreenpanel = new JPanel();
JButton jButton1 = new JButton();
Panel1() {
jButton1.setBounds(300,300,400,200);
jButton1.setBackground(Color.BLACK);
jButton1.setVisible(true);
jButton1.addActionListener(new ActionListener() {
Panel2 test = new Panel2();
public void actionPerformed(ActionEvent e) {
firstscreenpanel.setVisible(false);
test.secondscreenpanel.setVisible(true);
}
});
}
public Component panelone() {
firstscreenpanel.setSize(1280, 1024);
firstscreenpanel.setLayout(null);
firstscreenpanel.setBackground(Color.BLUE);
firstscreenpanel.add(jButton1);
firstscreenpanel.setVisible(true);
return firstscreenpanel;
}
}
第二个 JPanel 类:
import java.awt.Color;
import java.awt.Component;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Panel2 {
public JPanel secondscreenpanel = new JPanel();
public JButton jButton2 = new JButton();
Panel2() {
jButton2.setBounds(100,100,400,200);
jButton2.setBackground(Color.BLACK);
jButton2.setVisible(true);
}
public Component paneltwo() {
secondscreenpanel.setSize(1280, 1024);
secondscreenpanel.setLayout(null);
secondscreenpanel.add(jButton2);
secondscreenpanel.setBackground(Color.RED);
secondscreenpanel.setVisible(false);
return secondscreenpanel;
}
}
JFrame 类:
import javax.swing.JFrame;
public class Frame1 {
public JFrame frame1 = new JFrame();
Panel1 panel1 = new Panel1();
Panel2 panel2 = new Panel2();
Frame1() {
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setState(JFrame.MAXIMIZED_BOTH);
frame1.setSize(1280, 1024);
frame1.setLayout(null);
frame1.add(panel1.panelone());
frame1.add(panel2.paneltwo());
frame1.setVisible(true);
}
}
主类:
public class MainClass {
private void showGUI() {
Frame1 jframe = new Frame1();
}
public static void main(String[] args) {
final MainClass main = new MainClass();
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run() {
main.showGUI();
}
});
}
}
【问题讨论】:
-
我认为问题在于您正在创建一个新的 Panel2 对象并且您没有使用原始 JFrame 中的对象。您可能应该将 JFrame 的引用传递给您的 panel1,以便您可以使用引用的 Jframe 中的 jpanel2
-
我真的不明白如何传递我的 JFrame hm 的引用。
-
您的 JPanel 中应该有一个 JFrame,然后您可以在创建 JPanel 时将 JFrame 传递给您的 JPanel 的构造函数。
-
使用
CardLayout,如this answer所示。
标签: java swing jpanel jbutton actionlistener