【发布时间】:2014-09-19 22:09:46
【问题描述】:
我对 Java 还很陌生,我正在尝试制作一个 GUI。这是我的GUI.java 文件中的代码。它包含一个按钮和一个标签。当我单击按钮时,标签应该显示“正在加载...”并在名为 searcher 的 Main 类(在 Main.java 中)中输入一个静态 void 方法并执行操作。搜索完成后,标签变为""。
问题:当我按下按钮时,标签根本没有改变。似乎actionListener 中的setText 和searcher() 都不起作用。但是,我希望它在searcher() 中执行的其他“东西”仍然可以正常工作。我没有看到任何错误。
注意:如果我尝试从 main 调用 searcher(),它可以正常工作。
GUI.java:
public class GUI extends JFrame implements ActionListener{
public JButton button = new JButton("Refresh!");
public JLabel label = new JLabel("");
public GUI(){
Container pane = getContentPane();
button.addActionListener(this);
button.setActionCommand("refresh");
pane.add(button);
pane.add(label);
}
}
public void actionPerformed(ActionEvent e) {
if ("refresh".equals(e.getActionCommand())) {
label.setText("Loading...");
Main.searcher(this, "", "");
label.setText("");
}
}
Main.java:
public class Main{
public static void searcher(GUI gu, String popup, String url) {
gu.label.setText("Loading...");
//do stuff
gu.label.setText("");
}
public static void main(String[] args) {
GUI gu = new GUI ();
}
}
编辑:我已按照建议更改为使用 SwingWorker 和 propertylistener 的代码,但我现在遇到了麻烦。首先,'this' 不再是指 GUI。我应该在 searcher 方法中传递什么来传递类 GUI 的当前实例?
我也遇到了这个错误,我不确定如何解决它:
.\GUI.java:77: 错误:不是抽象的,并且不会覆盖 PropertyChangeListener 中的抽象方法 propertyChange(PropertyChangeEvent) PropertyChangeListener propChangeListn = new PropertyChangeListener() {^
public void actionPerformed(ActionEvent e) {
if ("refresh".equals(e.getActionCommand())) {
label.setText("Loading...");
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
public Void doInBackground() throws Exception {
Main.searcher(this, "", "http://maple.fm/api/2/search?server=0");
return null;
}
};
//worker.addPropertyChangeListener(new propertyChangeListener listener) {
PropertyChangeListener propChangeListn = new PropertyChangeListener() {
public void propertyChanged(PropertyChangeEvent pcEvt) {
if (pcEvt.getNewValue() == SwingWorker.StateValue.DONE) {
label.setText("");
}
}
};
worker.addPropertyChangeListener(propChangeListn);
worker.execute();
}
【问题讨论】:
-
这是一个很常见的挥杆问题,看起来应该是某个问题的重复,但我的 search-fu 找不到它。
标签: java swing user-interface swingworker