我在使用 JTextField 类的 setText() 方法时遇到问题。简而言之,它在下面的 CounterPanel 类中不起作用。它在 run() 方法中调用,它不会更新文本字段。其余代码运行(可以使用我留下的 println() 语句将其打印到控制台。
这些面板被添加到我也在下面包含的 MainWindow 类中。MainWindow 中有 4 个 CounterPanel,每个都有自己的线程。正如我所说,run() 方法中的其余代码工作正常,所以谁能告诉我哪里出错了?
非常感谢。
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
public class CounterPanel extends JPanel implements Runnable {
/**
*
*/
private static final long serialVersionUID = 1L;
private JLabel labelOne = new JLabel("Counter 1");
private JTextField textFieldOne = new JTextField(3);
private JLabel labelTwo = new JLabel("Counter 2");
private JTextField textFieldTwo = new JTextField(3);
private int counter;
private String counterAsString = Integer.toString(counter);
public CounterPanel() {
this.setLayout(new MigLayout());
this.setBorder(BorderFactory.createLineBorder(Color.black, 1));
this.add(labelOne);
this.add(textFieldOne);
this.add(labelTwo);
this.add(textFieldTwo);
}
@Override
public void run() {
while(counter < 100) {
textFieldOne.setText(counterAsString);
textFieldTwo.setText(counterAsString);
System.out.println("Counter 1 = " + counterAsString + ", Counter 2 = " + counterAsString);
counter++;
}
System.out.println("FINISHED");
}
}
import java.awt.Color;
import javax.swing.*;
import net.miginfocom.swing.MigLayout;
public class MainWindow extends JFrame {
private CounterPanel panel1 = new CounterPanel();
private CounterPanel panel2 = new CounterPanel();
private CounterPanel panel3 = new CounterPanel();
private CounterPanel panel4 = new CounterPanel();
private JLabel labelOne = new JLabel("A");
private JLabel labelTwo = new JLabel("B");
private JLabel labelThree = new JLabel("C");
private JLabel labelFour = new JLabel("D");
public MainWindow() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new MigLayout());
this.add(labelOne, "gapright 20px");
this.getContentPane().add(panel1, "wrap");
this.add(labelTwo);
this.getContentPane().add(panel2, "wrap");
this.add(labelThree);
this.getContentPane().add(panel3, "wrap");
this.add(labelFour);
this.getContentPane().add(panel4);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
MainWindow window = new MainWindow();
window.setLocationRelativeTo(null);
window.runThreads();
}
public void runThreads() {
Thread panelThread1 = new Thread(panel1);
Thread panelThread2 = new Thread(panel2);
Thread panelThread3 = new Thread(panel3);
Thread panelThread4 = new Thread(panel4);
panelThread1.start();
panelThread2.start();
panelThread3.start();
panelThread4.start();
}
}