简体   繁体   English

在Java中“链接” JComponent?

[英]“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. 我想向每个按钮添加一个ActionListener,以便在单击按钮时切换面板的可见性。 However, inside the ActionPerformed method, I cannot get the JPanel. 但是,在ActionPerformed方法内部,我无法获取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. 创建实现ActionListener的类可能更好。 You could then pass in a reference to the parent JPanel and then refer to that in the actionPerformed method. 然后,您可以传递对父JPanel的引用,然后在actionPerformed方法中进行引用。

But if you really wanted to, you could use this convoluted one-liner. 但是,如果您真的想要,可以使用这种复杂的单线。

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

An AbstractAction could work well: AbstractAction可以很好地工作:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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