英文:
Java Swing unable to remove a component
问题
我正在尝试构建一个问答游戏,在用户点击带有答案的按钮后重新呈现自身。
我已经为4个按钮添加了动作监听器。当按钮被点击时,它应该达到扩展了JFrame的外部类,然后删除扩展了JPanel的QuestionPanel。然后创建一个新的QuestionPanel,并将其添加回框架。
层次结构如下:
MainFrame(JFrame)-> QuestionPanel(JPanel)-> optionPanel(JPanel)-> button(JButton)
MainFrame(外部类)
-> QuestionPanel(内部类)
-> OptionPanel(内部类)
button.addActionListener(e->{
boolean result = false;
JButton target = (JButton) e.getSource();
result = MainFrame.this.questions[currentQuestion].checkAnswer(target.getText());
System.out.println(questions.length);
if(currentQuestion != (questions.length - 1)){
MainFrame.this.remove(qPanel);
//qPanel是QuestionPanel的实例
currentQuestion++;
qPanel = new QuestionPanel(questions[currentQuestion]);
MainFrame.this.add(qPanel);
}
});
英文:
I am trying to build a quiz game that rerender itself after user click on the button with answer.
I have added an action listener to 4 buttons. When the button is clicked, it is suppose to reach the outer class which extend JFrame and remove the QuestionPanel that extends the JPanel. And then create a new QuestionPanel and add it back to the frame.
The hierarchy in goes like this :
MainFrame (JFrame) -> QuestionPanel (JPanel) -> optionPanel (JPanel) -> button (JButton)
MainFrame(outer class)
-> QuestionPanel (inner class)
-> OptionPanel (inner class)
But it just freeze during execution
button.addActionListener(e->{
boolean result = false;
JButton target = (JButton) e.getSource();
result = MainFrame.this.questions[currentQuestion].checkAnswer(target.getText());
System.out.println(questions.length);
if(currentQuestion != (questions.length - 1)){
MainFrame.this.remove(qPanel);
//qPanel is the instance of QuestionPanel
currentQuestion++;
qPanel = new QuestionPanel(questions[currentQuestion]);
MainFrame.this.add(qPanel);
}
});
答案1
得分: 0
许多人指出,你最好修改组件内部的文本,比如一个标签(Label),而不是移除一个 JPanel 并替换它。其实没有必要这样做,尤其是只是为了向用户显示文本。
英文:
Like many pointed out, you would be better off changing the text inside a component like a Label rather than removing a Jpanel and replacing it. There is simply no need for that, especially just to display text to a user.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论