gpt4 book ai didi

java - 如何从内部类的 try block 中获取字符串

转载 作者:行者123 更新时间:2023-12-01 20:27:44 24 4
gpt4 key购买 nike

我试图在实现 ActionListener 的内部类中将标签设置为阅读器收到的字符串。 但我收到未知符号错误。我如何在内部类中引用该变量

import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class DailyAdviceClient {
JLabel label;
JButton button;
JFrame frame;
JPanel mainPanel;

public void gui() {
frame = new JFrame("Daily Advice Client");
button = new JButton("Get Advice");
label = new JLabel("Text");
mainPanel = new JPanel();
mainPanel.add(button);
mainPanel.add(label);

button.addActionListener(new AdviceListener());
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);

frame.setSize(300,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

}
public void go() {
try {
Socket s = new Socket("127.0.0.1", 4242);

InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);

String advice = reader.readLine();
System.out.println("Today you should: " + advice);
reader.close();
}
catch (IOException e) {
System.out.println("Hayt tumhari ki");
System.out.print("I didn't think we would get to this stage. Please ");
System.out.println("kill the developer. \n");
e.printStackTrace();
}
}

public static void main(String[] args) {
DailyAdviceClient client = new DailyAdviceClient();
client.go();
client.gui();
}

public class AdviceListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
label.setText(advice);
}
}
}

最佳答案

通过应用 MVC 模式可以轻松解决这个问题:

您只有一个 Controller 和一个 View ,但是您缺少一个共同的模型,它们都可以工作。

最简单的实现是将局部变量 advice 提升为一个对象成员变量,充当模型:

public class DailyAdviceClient {
private String advice;
// ...
advice = reader.readLine();
// ...

并将类 AdviceListener 转换为 匿名内部类 作为 lambda:

button.addActionListener(ae->label.setText(advice));

关于java - 如何从内部类的 try block 中获取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43654952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com