gpt4 book ai didi

java - 相邻类中的 ActionListener 实现

转载 作者:行者123 更新时间:2023-12-02 00:12:29 24 4
gpt4 key购买 nike

我认为在同一个类中编写监听器不是 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());
}
}

并为 tStringtLabel 分别添加一个 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/

24 4 0
文章推荐: java - 如何在Java中获取网页上所有

标签的字符串值?

文章推荐: sql - 向密集秩函数添加条件子句(Where)
文章推荐: reactjs - 如何将现有的 InputProps 与子组件中的其他 InputProps 结合起来
文章推荐: java - SELECT * FROM BETWEEN AND