Hide a button from Layout in Java Swing

前端 未结 4 1891
小蘑菇
小蘑菇 2020-12-18 15:04

I am trying something very basic: I have a list of 5 buttons. They are in a FlowLayout and the general idea should be that once I click one it should disappear and the other

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-18 15:27

    Works fine for me.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class FlowLayoutInvisible extends JFrame
        implements ActionListener
    {
        JPanel north;
        int i;
    
        public FlowLayoutInvisible()
        {
    
            north = new JPanel();
    
            for (int i = 0; i < 5; i++)
            {
                JButton button = new JButton("North - " + i);
                button.addActionListener(this);
                north.add(button);
            }
    
            getContentPane().add(north, BorderLayout.NORTH);
            }
    
        public void actionPerformed(ActionEvent e)
        {
            Component c = (Component)e.getSource();
            c.setVisible(false);
        ((JPanel)c.getParent()).revalidate();
        }
    
        public static void main(String[] args)
        {
            FlowLayoutInvisible frame = new FlowLayoutInvisible();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
        }
    }
    

    If you need more help post your SSCCE.

    Update: I don't know if the revalidate() is required. I seemed to have a problem once but now I can't duplicate the problem.

提交回复
热议问题