简体   繁体   中英

Hide JButton after click on it

I want to have 2 things:

  1. Hide my "PLAY" button after I click on it.
  2. To leave other buttons at the same positions in which they were before I hid the PLAY button

     public class MusicPlayer { public static void main (String[] args) { JFrame frame = new JFrame("Main window"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension(600, 400)); frame.setResizable(false); frame.setVisible(true); frame.pack(); frame.setLayout(new BorderLayout()); JPanel panel = new JPanel(new GridBagLayout()); JButton b1 = new JButton("PLAY"); JButton b2 = new JButton("PAUSE"); JButton b3 = new JButton("STOP"); GridBagConstraints layout = new GridBagConstraints(); layout.insets = new Insets(0, 10, 5, 0); layout.anchor = GridBagConstraints.SOUTH; layout.weighty = 1; panel.add(b1, layout); panel.add(b2, layout); panel.add(b3, layout); frame.add(panel, BorderLayout.CENTER); panel.setBackground(Color.blue); b1.setBackground(Color.green); b2.setBackground(Color.yellow); b3.setBackground(Color.red); } } 

Add action listener to your PLAY button b1 .

b1.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
     b1.setVisible(false); 
  } 
}

It shall do the job of hiding for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM