繁体   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