简体   繁体   English

我如何获得一个jbutton来更新jlabel?

[英]How do I get a jbutton to update a jlabel?

I'm new to Java. 我是Java新手。 First project, learning through Google new. 第一个项目,通过Google学习。

I want to update the text of a jlabel when the jbutton is pressed. 我想在按下jbutton时更新jlabel的文本。 I want to do a lot more, but if I can't get it to do that, it's not going further. 我想做更多的事情,但是如果我做不到,那就不会再走了。

It's giving me an error on the name of the jlabel like it doesn't exist, but the exact same thing works lower down in the jlabel code. 这给了我jlabel名称错误的提示,因为它不存在,但是在jlabel代码中完全一样的东西在下面起作用。

"lblCode" of lblCode.setText(time); lblCode.setText(time)的“ lblCode”; under the ActionEvent of the button is where it errors, lblCode cannot be resolved. 在按钮的ActionEvent发生错误的地方,lblCode无法解析。

JButton btnRefresh = new JButton("Refresh");
    btnRefresh.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            lblCode.setText(time);
        }
    });
    contentPane.add(btnRefresh, BorderLayout.EAST);

    JLabel lblCode = new JLabel("");
    lblCode.setHorizontalAlignment(SwingConstants.CENTER);
    contentPane.add(lblCode, BorderLayout.CENTER);
    lblCode.setText(time);

How can it exist one place, and not the other? 它如何在一个地方而不是另一个地方存在? I'm stuck. 我被卡住了。

Sorry if this question is too basic. 抱歉,这个问题太基础了。 I feel stupid for having to ask. 我不得不问这个问题而感到愚蠢。

You access lblCode before it is defined - move the 您可以在定义之前访问lblCode移动

btnRefresh.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        lblCode.setText(time);
    }
});

part below the initialization of lblCode . lblCode的初始化下面的部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM