我是Java的初学者。这是我需要做的示例代码。我想将JLabel中的文本更改为“Hooray!”来自另一个班级的另一种方法。它是成功编译的,但是在运行时我每次运行时都会得到不同的结果(甚至代码中的单个字母也没有变化)。我在GUI和CLI中随机获得了以下结果。我期待第一个结果......(我使用NetBeans生成GUI)
label method; run method; action performed 1 ; action performed 2;..."
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class NewJFrame extends javax.swing.JFrame {
public static String st;
static int counter;
private static javax.swing.JLabel jLabel1;
public NewJFrame() {
initComponents();
}
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("jLabel1");
/*I Generated this GUI Using NetBeans IDE... with a Single JLabel and a JFrame*/
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(89, 89, 89)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(170, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(89, 89, 89)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(120, Short.MAX_VALUE))
);
pack();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
counter++;
setLabel(st);
System.out.println("actionPerformed "+counter);
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
});
Test t = new Test();
t.run();
}
public static void setLabel(String x) {
jLabel1.setText(x);
}
}
class Test extends NewJFrame {
void run() {
label();
System.out.println("run method");
}
void label() {
st = "Hooray !";
System.out.println("label method");
}
}
我对这些不同的结果不明确我每次运行代码时都会随机获取...请帮助我......