0

所以我正在学习线程,我似乎无法让程序使用线程。

基本代码是:

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.GridLayout;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.Dimension;

public class CLASS1 extends JFrame implements KeyListener
{
public CLASS2 class2Variable1 = new CLASS2();
public CLASS2 class2Variable2 = new CLASS2();
public Thread thread1 = new Thread(class2Variable1);
public Thread thread2 = new Thread(class2Variable2);

public CLASS1()
{
    //Not Important for example
}

public static void main(String[] args)
{
    CLASS1 class1 = new CLASS1();
    class1.createAndShowGUI();
}

public void createAndShowGUI()
{
    CLASS1 frame = new CLASS1();
    frame.setPreferredSize(new Dimension(400,200));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel contentPane = new JPanel(new GridLayout());
    frame.setContentPane(contentPane);
    frame.addKeyListener(frame);
    frame.add(class2Variable1);
    frame.add(class2Variable2);
    thread1.start();
    thread2.start();
    frame.pack();
    frame.setVisible(true);
}

public void keyPressed(KeyEvent e)
{
    class2Variable1.speed = class2Variable1.speed + 10;
    class2Variable1.changeText("CHANGED VALUE TO: " + class2Variable1.speed);
    //Also Tried class2Variable1.labelText.setText("CHANGED VALUE");
    class2Variable1.revalidate();
    class2Variable1.repaint();
}

public void keyTyped(KeyEvent e)
{
}

public void keyReleased(KeyEvent e)
{
}
}

class CLASS2 extends JPanel implements Runnable
{
public int speed = 0;
public JLabel labelText = new JLabel(); //Also tried Initializing it here

public void changeText(String text)
{
    labelText.setText(text);
    labelText.repaint();
}

public void run()
{
    addStuff();
}

public CLASS2()
{
    setLayout(new GridLayout());
}

public void addStuff()
{
    labelText.setText("INITIAL VALUE");
    add(labelText);
    }
}

所有的 KeyEvents 都有效,但是如果我使用 messageDialog 检查变量 var1,它会显示初始化时的值 (0),而不是线程的值 (100)。即使使用 setText,我也无法更改 JLabel 中的文本。

4

1 回答 1

0

更改变量var1不会更改标签的文本。您必须varLabel.setText使用更改后的值进行调用。

另请阅读这篇关于使用 swing 线程的文章:http: //docs.oracle.com/javase/7/docs/api/javax/swing/package-summary.html#threading

解决方案应如下所示:

public void run()
{
     var1 = 100;
     SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            varLabel.setText(String.valueOf(var1));
            // varLabel.repaint(); // might be necessary?
        }
    });
}
于 2013-10-02T12:49:43.210 回答