Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
&引用;“链接”;Java中的JComponents?_Java_Swing - Fatal编程技术网

&引用;“链接”;Java中的JComponents?

&引用;“链接”;Java中的JComponents?,java,swing,Java,Swing,我有几个按钮和几个面板。每个按钮对应一个面板。我想为每个按钮添加一个ActionListener,以便在单击按钮时切换面板的可见性。但是,在ActionPerformed方法中,我无法获得JPanel。以下是我的基本情况: JFrame frame1=new JFrame(); JPanel panel=new JPanel(); frame1.add(panel); JFrame frame2=new JFrame(); JButton btn=new JButton(panel.getNa

我有几个按钮和几个面板。每个按钮对应一个面板。我想为每个按钮添加一个ActionListener,以便在单击按钮时切换面板的可见性。但是,在
ActionPerformed
方法中,我无法获得JPanel。以下是我的基本情况:

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);
这应该起作用:

e.getSource().getParent().setVisible(false);
这应该起作用:

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

最好创建一个实现ActionListener的类。然后可以传入对父JPanel的引用,然后在actionPerformed方法中引用该引用

但如果你真的想,你可以用这个复杂的一行

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

最好创建一个实现ActionListener的类。然后可以传入对父JPanel的引用,然后在actionPerformed方法中引用该引用

但如果你真的想,你可以用这个复杂的一行

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

抽象操作可以很好地工作:

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);
  }
}
其他地方:

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

抽象操作可以很好地工作:

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);
  }
}
其他地方:

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

这不是一个很好的解决方案,但您可以按照以下方式链接swing组件

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

这不是一个很好的解决方案,但您可以按照以下方式链接swing组件

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

为什么不使用panel引用变量呢?您到底在哪里使用此代码?为什么您无法访问面板?并创建将按钮连接到面板的机制,例如
映射
@peeskillet什么是面板引用变量?@Linksku
JPanel panel=new JPanel()
panel
是ref变量。为什么不使用panel reference变量。您到底在哪里使用此代码?为什么您无法访问面板?并创建将按钮连接到面板的机制,例如
映射
@peeskillet什么是面板引用变量?@Linksku
JPanel panel=new JPanel()
面板
是参考变量。