簡體   English   中英

按下JButton時JLabel中的文本不會更新

[英]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的新對象,但此后未將其添加到JPanelJFrame

盡管創建了新對象,

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.

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