我不知道如何从单独的ActionListener类实现操作侦听器。我已经将应用程序分成了几个类。主类调用Frame类来创建包含所有按钮的GUI。现在,当按钮被按下时,我需要向ActionListener方法发送一些数据,以便它完成这项工作。如果我在Frame类中添加ActionListener而不能发送所需的数据,如果我在main()方法中添加ActionListener,在调用Frame类之后感觉很笨拙。代码如下: public class Main {
public static Client klijent;
public static void main(String[] args) {
FrameBuilder frame= new FrameBuilder();
frame.frameBuild();
frame.send.addActionListener(new SendBttnListener(ClientBuilder(klijent,frame.txt.getText())));
try {
frame.statLabel.setText(InetAddress.getLocalHost().getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
Udp udp;
// klijent = null;
while(true){
klijent=new Client();
udp=new Udp();
klijent=udp.packageIN();
if(klijent!=null){
frame.statLabel.setText("");
String str=new String(klijent.getBajt(),0,klijent.bajt.length);
str=str.trim();
frame.statLabel.setText(str+"@...@"+klijent.clientAddress.toString()+":"+klijent.clientPort+"-->Duljina:"+klijent.bajt.length);
}
}
}
public static Client ClientBuilder(Client klijent2, String str){
klijent.setBajt(str.getBytes());
return klijent2;
}正如你所看到的,客户端对象可以改变很多(UDP服务器),并将在等待下一个包时被清除。后来,我认为实现一些客户端列表并在Frame类中添加Action listener似乎很愚蠢。我是不是在创建用于构建GUI的separet类时出错了?有什么建议吗?
提前感谢....
发布于 2012-10-04 08:31:58
你发送的方法应该包装在它自己的实现中。这可以是一个单调实现,也可以作为引用传递给包装操作侦听器。
按钮操作侦听器应该只从按钮的上下文中管理,它不应该从按钮上下文的外部访问(例如,我不相信你应该能够做到这一点frame.send.addActionListener(...)),因为调用者不应该关心发送请求是如何实现的,只是它是...
我有一个可以传递给框架的类或接口,它为框架提供了“发送”消息的方法。
public interface Sender {
public void sendMessage(String message); // Or what ever parameter you want...
}我会将实现的引用传递给你的框架...
Sender sender = new ImplementationOfSender();
frame.setSender(sender); // It could also be passed to the constructor在框架中,我会将我的操作侦听器附加到按钮上,当触发时,我将访问发送者并发送消息...
send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Sender sender = getSender();
if (sender != null) {
sender.sendMessage(...);
}
}
});现在已经说过,所有的that...your程序都会很快在你面前爆炸……
这将停止你的程序在它的轨道上,使UI看起来它是挂起的。
while(true){
klijent=new Client();
udp=new Udp();
klijent=udp.packageIN();
if(klijent!=null){
frame.statLabel.setText("");
String str=new String(klijent.getBajt(),0,klijent.bajt.length);
str=str.trim();
frame.statLabel.setText(str+"@...@"+klijent.clientAddress.toString()+":"+klijent.clientPort+"-->Duljina:"+klijent.bajt.length);
}
}所有与UI的交互都必须在Event Dispatching Thread (AKA EDT)的上下文中完成。任何阻塞操作,比如您的循环,都不应该在EDT上下文中执行
我会读到Concurrency in Swing的。
你的程序可能已经爆炸的唯一原因是,当你启动它时,你还没有将你的UI的创建同步到EDT。
你可能想读一读Swing Single Threading Rule
https://stackoverflow.com/questions/12718711
复制相似问题