我想从另一个类中的监听器访问扩展的 JPanel,以便在单击按钮时重新调整该面板的大小。
我尝试使用 Buttons.this.setPreferredSize
访问它......,但我收到此错误
No enclosing instance of the type Buttons is accessible in scope
我的按钮类看起来像这样
public class Buttons extends JPanel {
public Buttons() {
//code
}
}
另一个是我想更改面板大小的地方
public class InterfaceCalc extends JPanel {
// others codes
expandIcon = new ImageIcon("src\\img\\expand.png");
expand = new JButton("", expandIcon);
expand.setBorderPainted(false);
expand.setContentAreaFilled(false);
expand.setFocusPainted(false);
expand.setOpaque(false);
expand.setMargin(new Insets(0, 0, 0, 0));
expand.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!on) {
Buttons.sqrt.setVisible(true);
Buttons.log.setVisible(true);
Buttons.cos.setVisible(true);
Buttons.sin.setVisible(true);
// this is where is want to access the panel
Buttons.this.setPreferredSize(new Dimension());
on = true;
} else {
Buttons.sqrt.setVisible(false);
Buttons.log.setVisible(false);
Buttons.cos.setVisible(false);
Buttons.sin.setVisible(false);
on = false;
}
}
});
// others codes
}
如何实现这一目标?
最佳答案
我通过在监听器外部创建 Button 实例解决了该问题。之前,扩展面板是像这样在InterfaceCalc面板中的this.add(new Buttons())中直接添加的,现在在我创建实例后,我将它添加到面板中,并用它来更改大小。
关于java - 从另一个类中的监听器访问扩展 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30334039/