简体   繁体   中英

“Linking” JComponents in Java?

I have a few buttons and a few panels. Each button corresponds to a panel. I want to add an ActionListener to each button so that when the buttons are clicked, the visibility of the panels are toggled. However, inside the ActionPerformed method, I cannot get the JPanel. Here's basically what I have:

JFrame frame1=new JFrame();
JPanel panel=new JPanel();
frame1.add(panel);

JFrame frame2=new JFrame();
JButton btn=new JButton(panel.getName());
btn.addActionListener(new ActionListener(){
    public void ActionPerformed(ActionEvent e){
        (somehow get panel).setVisible(false);      
    }
});
frame2.add(btn);

It might be better to create a class that implements ActionListener. You could then pass in a reference to the parent JPanel and then refer to that in the actionPerformed method.

But if you really wanted to, you could use this convoluted one-liner.

((JComponent)e.getSource()).getParent().setVisible(false);

An AbstractAction could work well:

class ButtonAction extends AbstractAction {
  private JPanel panel;

  public ButtonAction(JPanel panel) {
    super(panel.getName());
    this.panel = panel;
  }

  public void actionPerformed(ActionEvent e) {
    panel.setVisible(false);
  }
}

elsewhere:

someContainer.add(new JButton(new ButtonAction(panel)));

这应该工作:

e.getSource().getParent().setVisible(false);

It is not very good solution, but you can link swing components in following way

button.putClientProperty("panel", panel1);
//and somewhere in code
((JPanel)button.getClientProperty("panel")).setVisible(false);

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