更改Java Thread中变量的值

时间:2013-10-02 12:38:23

标签: java multithreading

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

基本代码是:

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);
    }
}

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

1 个答案:

答案 0 :(得分: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?
        }
    });
}