[英]Text in JLabel doesn't get updated on pressing a JButton
我正在一個項目上,但是該程序似乎有一個我找不到的錯誤。
這是重現問題的MCVE :
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class SO{
JLabel label;
JButton button;
JPanel panel;
JFrame frame;
public static void main(String[] args){
new SO().start();
}
public void start()
{
label = new JLabel("Button not pressed");
button = new JButton("Press me");
frame = new JFrame();
panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
panel.add(label);
panel.add(button);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("Button was pressed");
label = new JLabel("Button is pressed"); //Doesn't work
frame.repaint();
}
});
}
}
上面的程序有一個帶有一些文本的JLabel和一個JButton,它們都被添加到JPanel中,而JPanel又被添加到JFrame中。
當按下按鈕時,我希望更改JLabel中的文本。 但是,即使每次按下按鈕都執行println
,文本也不會改變。
這里有什么問題?
單擊該按鈕時,您正在創建JLabel
的新對象,但此后未將其添加到JPanel
或JFrame
。
盡管創建了新對象,即
label = new JLabel("Button is pressed")
做類似的事情,
label.setText("Button is pressed");
更改
label = new JLabel("Button is pressed");
至
label.setText("Button is pressed");
您無需每次都創建和分配新標簽。只需更改文本
您可以將該行更改為label.setText(“按下按鈕”); 使這項工作。
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class SO{
JLabel label;
JButton button;
JPanel panel;
JFrame frame;
public static void main(String[] args){
new SO().start();
}
public void start()
{
label = new JLabel("Button not pressed");
button = new JButton("Press me");
frame = new JFrame();
panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
panel.add(label);
panel.add(button);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("Button was pressed");
label.setText("Button is pressed"); //Doesn't work
frame.repaint();
}
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.