- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我认为在同一个类中编写监听器不是 OOP 方式。所以,我尝试在另一个文件中编写监听器。
有效的代码是:
class MyPanel extends JPanel{
private String tString = "Test String";
private JLabel tLabel;
public MyPanel(){
tLabel = new JLabel("Label");
JButton tButton = new JButton("Click me");
tButton.addActionListener(new ActionListener(){
public void ActionPerformed(ActionEvent e){
tLabel.setText(tString);
}
});
}
但是当我在单独的文件中编写监听器时:
public class MyListener implements ActionListener{
copy code here
}
并改变
tButton.addActionListener(new ActionListener(){
至
tButton.addActionListener(new MyListener());
这不起作用。当然我尝试过不同的组合。
例如,将“this”发送到监听器的构造函数并从接收到的调用方法 监听器类中的对象。
错误:
MyListener: cannot find symbol "tLabel"
最佳答案
感谢您编辑您的答案:)
您似乎正在尝试从新监听器访问 tLabel
变量,但它无法访问,因为它可能被声明为 private
。同样的事情也可能发生在 tString
上。试试这个:
public class MyListener implements ActionListener{
private MyPanel myPanel;
public MyListener(MyPanel myPanel) {
this.myPanel = myPanel;
}
public void ActionPerformed(ActionEvent e) {
myPanel.getTLabel().setText(myPanel.getTString());
}
}
并为 tString
和 tLabel
分别添加一个 getter 到 MyPanel
:
public class MyPanel extends JPanel {
// ...
public String getTString() {
return tString;
}
public JLabel getTLabel() {
return tLabel;
}
}
当您无法访问私有(private)字段时,通常会添加一个 public
“getter”,它返回该字段,而不是更改该字段本身的访问权限。约定是,例如,如果字段是 String
且名为 myField
,则 getter 名为 getMyField
。像这样,您还可以添加 setter 来设置该变量。请参阅this question有关 getter 和 setter 的更多信息。
关于java - 相邻类中的 ActionListener 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12461915/
我是一名优秀的程序员,十分优秀!