如何从JFrame(Java)中删除JPanel

时间:2015-04-27 19:45:18

标签: java jframe jpanel jbutton

我需要在按下按钮时从JFrame中删除JPanel。这是我的代码。它还需要添加包含不同图像的面板。当我尝试执行p4.remove(p4)时,它什么也没做,当我添加(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));
}

}

1 个答案:

答案 0 :(得分:0)

尝试使用以下代码替换ActionListener中的代码(包括if和else语句):

 start.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {


            p4.setVisible(false);
            add(p5, BorderLayout.CENTER);

    }
});