[英]How to remove a JPanel from a JFrame (Java)
I need to remove a JPanel from a JFrame upon the press of a button. 按下按钮后,我需要从JFrame中删除一个JPanel。 Here is my code. 这是我的代码。 It also needs to add a panel that contains a different image. 它还需要添加一个包含其他图像的面板。 When I try to do p4.remove(p4), it does nothing and when I do add(p5, BorderLayout.CENTER); 当我尝试执行p4.remove(p4)时,它什么都不做,当我执行add(p5,BorderLayout.CENTER);时,它什么也不做。
public class Main extends JFrame {
public Main() {
//Creates Title Image
JLabel title = new JLabel(" ");
ImageIcon tl = new ImageIcon("title.gif");
title.setIcon(tl);
//Creates Start Image
final JButton start = new JButton("");
ImageIcon st = new ImageIcon("start.gif");
start.setIcon(st);
//Creates Options Image
JButton options = new JButton("");
ImageIcon opt = new ImageIcon("options.gif");
options.setIcon(opt);
options.setBackground(Color.BLACK);
//Creates level 0
JLabel level0 = new JLabel(" ");
ImageIcon lvl0 = new ImageIcon("level0.gif");
level0.setIcon(lvl0);
//Create first frame for "Start" button
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1, 1));
p1.add(start, BorderLayout.CENTER);
//Create second panel for title label
JPanel p2 = new JPanel(new BorderLayout());
p2.setLayout(new GridLayout(1, 3));
p2.add(title, BorderLayout.WEST);
//Create third panel for "Options" button
JPanel p3 = new JPanel(new BorderLayout());
p3.setLayout(new GridLayout(1, 1));
p3.add(options, BorderLayout.SOUTH);
//Creates fourth panel to organize all other primary
final JPanel p4 = new JPanel(new BorderLayout());
p4.setLayout(new GridLayout(1, 3));
p4.add(p1, BorderLayout.WEST);
p4.add(p2, BorderLayout.CENTER);
p4.add(p3, BorderLayout.EAST);
//Creates fifth panel for level 0
final JPanel p5 = new JPanel(new BorderLayout());
p5.setLayout(new GridLayout(1, 1));
p5.add(level0, BorderLayout.CENTER);
start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(start.isSelected()) {
p4.remove(p4);
add(p5, BorderLayout.CENTER);
}
else {
return;
}
}
});
//Adds fourth panel to frame
add(p4, BorderLayout.CENTER);
}
public static void main(String args[]) {
Main frame = new Main();
//Finds screen size of monitor
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
//Creates the frame
frame.setTitle("Cockadoodle Duty: Awakening");
frame.setSize(screenSize);
frame.setLocale(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
String background = "#000000";
frame.setBackground(Color.decode(background));
}
} }
Try to replace the code you have in you ActionListener (including the if and else statement) with this: 尝试用以下代码替换ActionListener中包含的代码(包括if和else语句):
start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
p4.setVisible(false);
add(p5, BorderLayout.CENTER);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.