Replacing JPanel with JPanel in a JFrame

后端 未结 3 1956
[愿得一人]
[愿得一人] 2020-11-29 13:20

I have a class that extends JFrame, and it has a BorderLayout. It has two private instance variables of type JPanel. They represent panels of buttons and are called flipButt

相关标签:
3条回答
  • 2020-11-29 13:33

    revalidate() + repaint() should be trick, example here

    EDIT:

    feel that you have got problem with that, examples for that here and here and again example by trashgod, feel free to built your question based on code again

    another way is look at excelent example added by Andrew Thompson :-) +1

    0 讨论(0)
  • 2020-11-29 13:41

    try using getContentPane() to call remove() ,add() methods ect..:

    getContentPane().remove(flipButton); 
    getContentPane().add(confidenceButtons,BorderLayout.SOUTH);   
    getContentPane().revalidate();
    getContentPane().repaint();
    

    Edit: this code bellow work for me:

    import java.awt.BorderLayout;
    import java.awt.HeadlessException;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    
    public class Frame extends JFrame {
    JPanel flipButton =new JPanel();
    JPanel confidenceButtons =new JPanel();
    
    
    
        public Frame() throws HeadlessException {
        super();
        this.setLayout(new BorderLayout());
        JButton b1=new JButton("flip");
        b1.addActionListener(new FlipListener());
        flipButton.add(b1);
    
        JButton b2=new JButton("color");
        b2.addActionListener(new ColorListener());
        confidenceButtons.add(b2);
        this.getContentPane().add(flipButton,BorderLayout.SOUTH);
        this.setSize(250,250);
        this.pack();
        this.setVisible(true);
    
    }
        private class FlipListener implements ActionListener{
            public void actionPerformed(ActionEvent e){
              remove(flipButton); 
              add(confidenceButtons,BorderLayout.SOUTH);
              validate();
              repaint();
    
            }
          } 
          private class ColorListener implements ActionListener{
    
            public void actionPerformed(ActionEvent e){
    
              remove(confidenceButtons); 
              add(flipButton,BorderLayout.SOUTH);
              validate();
              repaint();
            }
          }
        /**
         * @param args
         */
        public static void main(String[] args) {
            new Frame();
    
        }
    
    }
    
    0 讨论(0)
  • 2020-11-29 13:56

    Use a CardLayout, as shown here.

    Game view High Scores view

    0 讨论(0)
提交回复
热议问题