GUI不动态更新

时间:2015-05-14 13:52:10

标签: java swing user-interface

我目前正在尝试创建一个程序,在按下它们时动态更改JTextArea和JButton上的文本,或显示JOptionPane。当我按下按钮时,没有任何事情发生,他们没有得到更新,也没有出现对话框。

帮助表示赞赏     私人百万富翁观点;     私人百万富翁模特;     私有字符串问题;     private int gameState;     private boolean isRunning;

public MillionaireController(MillionaireGui view, Millionaire model) {
    this.view = view;
    this.model = model;
    this.question = null;
    this.gameState = 0;
    this.isRunning = true;
}

public void setModel(Millionaire model) {
    this.model = model;
}

public void setView(MillionaireGui gui) {
    this.view = gui;
}

public void getQuestion() {
    question = model.getDeck().generateQuestion();
    view.setQuestion(question);
}
public void update(){
 while(isRunning){

 if(gameState == 0){

    getQuestion();

    ArrayList<String> ans = model.getDeck().getAnswers();
    view.setButtonA(ans.get(0));
    view.setButtonB(ans.get(1));
    view.setButtonC(ans.get(2));
    view.setButtonD(ans.get(3));
    gameState = 1;

}

if(gameState == 1){

    if(view.getAnswer() != 0){
        if(model.getDeck().isCorrect(view.getAnswer())){
            view.dispCorrectAnswer();
            view.setAnswer(0);
                gameState = 0;
        }
        else {
            gameState = 3;
        }
    }

  }
  if(gameState == 3){
      isRunning = false;
      view.displayErrorMsg();
    }
}
}
@Override
public void run() {
  update();
}

GUI:

public void setButtonB(String str){
    buttonB.setText(str);
}

public void setButtonC(String str){
    buttonC.setText(str);
}

public void setButtonD(String str){
    buttonD.setText(str);
}

public void setAnswer(int num){
    answer = num;
}

public String getQuestion(){
   return question;

}

public void setQuestion(String str){
   question = str;
   questionField.setText(str);
}

MAIN:

public class Millionaire_main {

public Millionaire_main(){

}

public static void main(String[] args) {
    MillionaireGui gui = new MillionaireGui();
    QuestionDeck deck = new QuestionDeck();
    Millionaire model = new Millionaire(deck);
    MillionaireController control = new MillionaireController(gui, model);   
    gui.setVisible(true);

    Thread thread = new Thread(control);
    thread.start();
  }
}

2 个答案:

答案 0 :(得分:1)

update()方法中的代码似乎是在运行一个线程。我认为正在发生的事情是你有2个线程,其中一个正在做一些导致更新的后台任务。后台线程不是EDT,因此任何UI更新都不可见。

尝试以下方法可以解决问题(最有可能)(

SwingUtilities.invokeLater(new Runnable() 
{
    @Override
    public void run() {
        view.setButtonA(ans.get(0));
        view.setButtonB(ans.get(1));
        view.setButtonC(ans.get(2));
        view.setButtonD(ans.get(3));
    }
});

以上内容应将您的按钮设置事件放在EDT上,这应触发更改。

答案 1 :(得分:1)

看起来你可能只需要revalidate容器。

设置完所有按钮文字字段后,请致电gui.revalidate()将所有内容标记为invalid&amp; validateHere's more on the differences between those 3 methods

另外(正如@npinti所述) - 我不确定你正在用额外的线程做什么,但要注意在AWT线程之外修改GUI组件是NOT a good idea