簡體   English   中英

更改Java線程中變量的值

[英]Changing the value of a variable in a Java Thread

所以我正在學習線程,但似乎無法獲得使用線程的程序。

基本代碼是:

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中的文本。

更改變量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?
        }
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM