Java - 更改JLabel [英] Java - Change JLabel

查看:178
本文介绍了Java - 更改JLabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Keys.java的按钮类,它返回一个名为Control.java的按钮面板。我在Control.java中有一个JLabel,但是我想做的是当按下一个按钮时更改一个JLabel。你会怎么做呢?

I have a class of buttons called Keys.java which returns a panel of buttons to the class called Control.java. I have a JLabel in Control.java, but what I want to do is change a JLabel when a button is pressed. How would you go about doing this?

我已经尝试在Keys.java中设置一个字符串,根据按钮更改,然后设置JLabel的文本等于字符串,但它似乎不工作。

I have tried setting a string in Keys.java which changes based on the button and then setting the JLabel's text equal to the string but it doesn't seem to work.

有关如何实现这一点的任何想法?

Any thoughts on how to achieve this?

推荐答案

是您更新错误的字符串或不正确地设置相应的标签的文本。两者都是必需的。在下面的例子中(使用你的名字),这两个更新在按钮的 actionPerformed()中紧密耦合。 此处显示了一种更松散耦合的方法。

It may be that you are updating the wrong string or setting the corresponding label's text incorrectly. Both are required. In the example below (using your names), the two updates are tightly coupled in the button's actionPerformed(). A more loosely coupled approach is shown here.

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/** @see http://stackoverflow.com/questions/9053824 */
public class JavaGUI extends JPanel {

    private Control control = new Control();
    private Keys keys = new Keys("Original starting value.");

    public JavaGUI() {
        this.setLayout(new GridLayout(0, 1));
        this.add(keys);
        this.add(control);
    }

    private class Control extends JPanel {

        public Control() {
            this.add(new JButton(new AbstractAction("Update") {

                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Command: " + e.getActionCommand());
                    keys.string = String.valueOf(System.nanoTime());
                    keys.label.setText(keys.string);
                }
            }));
        }
    }

    private class Keys extends JPanel {

        private String string;
        private JLabel label = new JLabel();

        public Keys(String s) {
            this.string = s;
            label.setText(s);
            this.add(label);
        }
    }

    private void display() {
        JFrame f = new JFrame("JavaGUI");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new JavaGUI().display();
            }
        });
    }
}

这篇关于Java - 更改JLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆