在JLabel中设置键入的文本

时间:2015-11-08 19:11:08

标签: java swing

我是Swing的新手。当用户键入文本时,我希望它出现在JLabel中。我无法访问label变量,因为它在构造函数中。

另外,我应该在main方法中添加什么内容?

public class One extends JPanel implements KeyListener {
    private JTextField textField;

    /**
     * Create the panel.
     */
    public One() {
        setLayout(null);

        textField = new JTextField();
        textField.setBounds(88, 81, 258, 53);
        add(textField);
        textField.setColumns(10);

        JLabel label = new JLabel("New label");
        label.setBounds(182, 198, 61, 16);
        add(label);
    }

    public void keyPressed(KeyEvent e){
        int keyCode = e.getKeyCode();
        label.setText(KeyEvent.getKeyText(keyCode));
    }

    public void keyReleased(KeyEvent e){

    }

    public static void main(String[] args){
        // ??
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }
}

3 个答案:

答案 0 :(得分:3)

您的方法存在许多问题。

首先,您应该避免一般使用KeyListener,但特别是对于文本组件,它只是监视文本字段更改的不恰当方法。相反,您应该使用DocumentListener,有关详细信息,请参阅Listening for Changes on a Document

其次,避免使用null布局,像素完美布局是现代ui设计中的错觉。影响组件个体大小的因素太多,您无法控制。 Swing旨在与布局管理器一起工作,放弃这些将导致问题和问题的终结,您将花费越来越多的时间来纠正

有关详细信息,请参阅Laying Out Components Within a Container

"核心"你遇到的问题是范围问题,基本上label只有构造函数的局部范围。基本解决方案是使label成为类的实例字段。这是基本的Java 101,与Swing无关。有关详细信息,请查看Understanding Class Memebers

Hello world

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class TestInput {

    public static void main(String[] args) {
        new TestInput();
    }

    public TestInput() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new InputPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class InputPane extends JPanel {

        private JTextField textField;
        private JLabel label;

        public InputPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(4, 4, 4, 4);
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            textField = new JTextField(20);
            label = new JLabel(" ");

            add(textField, gbc);
            add(label, gbc);

            textField.getDocument().addDocumentListener(new DocumentListener() {

                @Override
                public void insertUpdate(DocumentEvent e) {
                    updateLabel();
                }

                @Override
                public void removeUpdate(DocumentEvent e) {
                    updateLabel();
                }

                @Override
                public void changedUpdate(DocumentEvent e) {
                    updateLabel();
                }

                protected void updateLabel() {
                    label.setText(textField.getText());
                }
            });
        }

    }

}

答案 1 :(得分:0)

在您的类中创建label成员变量,并在构造函数中创建initialize

label = new JLabel("New label");

答案 2 :(得分:0)

public class One extends JPanel implements KeyListener {
    private JTextField textField;

    private JLabel jLabel;

    /**
     * Create the panel.
     */
    public One() {
        setLayout(null);

        textField = new JTextField();
        textField.setBounds(88, 81, 258, 53);
        add(textField);
        textField.setColumns(10);

        jLabel = new JLabel("New label");
        jLabel.setBounds(182, 198, 61, 16);
        add(label);
    }

    public void keyPressed(KeyEvent e){
        int keyCode = e.getKeyCode();
        label.setText(KeyEvent.getKeyText(keyCode));
    }

    public void keyReleased(KeyEvent e){

    }

    public static void main(String[] args){
        SwingUtilities.invokeLater(() -> {            
            One one = new One();
            JFrame jFrame = new JFrame();
            jFrame.add(one);
            jFrame.pack();
            jFrame.setVisible(true);
        });
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }
}