更新 JTextField.addActionListener 而不按“回车"; [英] Update JTextField.addActionListener without pressing "enter"

查看:58
本文介绍了更新 JTextField.addActionListener 而不按“回车";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到每次我希望 actionListener 执行它的方法执行时我都必须点击输入".我希望操作在用户在 JTextField 中输入任何类型的文本时发生.

I noticed I have to hit "enter" every time I want the actionListener to perform it's method execution. I would like the actions to happen the second the user enters any kind of text in the JTextField.

这是代码...

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;

public class TestGui extends JFrame {
    //**************************************************************************************
    // Variables
    private int enterTxtInTextFieldFontSize = 16;
    private int enterTxtInTextFieldWidth = 100;
    private int enterTxtInTextFieldHeight = 40;
    private JTextField enterTxtInTextField = createWhiteBoldFgDarkGreyBgFixedSizeAlignTextField("", enterTxtInTextFieldFontSize, enterTxtInTextFieldWidth, enterTxtInTextFieldHeight, SwingConstants.LEFT);;
    private JLabel inputStringText = new JLabel("");
    private JLabel inputIntText = new JLabel("");
    private JPanel topFrame = createTopFrame();
    private JScrollPane topFrameScroll = createTopScrollPane();
    private JPanel centerFrame = createCenterFrame();

    //**************************************************************************************
    // Constructor

    TestGui(){
        add(topFrameScroll, BorderLayout.NORTH);
        add(centerFrame, BorderLayout.CENTER);

        setSize(1280,720);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    //**************************************************************************************
    // Support Methods
    protected static boolean isInteger(String s) {
        try {
            Integer.parseInt(s);
        } catch(NumberFormatException e) {
            return false;
        } catch(NullPointerException e) {
            return false;
        }
        // String can be changed into an integer
        return true;
    }

    private static GridBagConstraints setGbc(int gridx, int gridy, int gridWidth, int gridHeight, int ipadx, int ipady, String anchorLocation, double weightx, double weighty, Insets insets){
        GridBagConstraints gbc = new GridBagConstraints();

        if (anchorLocation.toUpperCase().equals("NORTHWEST")){
            gbc.anchor = GridBagConstraints.NORTHWEST;
        } else if (anchorLocation.toUpperCase().equals("NORTH")){
            gbc.anchor = GridBagConstraints.NORTH;
        } else if (anchorLocation.toUpperCase().equals("NORTHEAST")){
            gbc.anchor = GridBagConstraints.NORTHEAST;
        } else if (anchorLocation.toUpperCase().equals("WEST")){
            gbc.anchor = GridBagConstraints.WEST;
        } else if (anchorLocation.toUpperCase().equals("EAST")){
            gbc.anchor = GridBagConstraints.EAST;
        } else if (anchorLocation.toUpperCase().equals("SOUTHWEST")){
            gbc.anchor = GridBagConstraints.SOUTHWEST;
        } else if (anchorLocation.toUpperCase().equals("SOUTH")){
            gbc.anchor = GridBagConstraints.SOUTH;
        } else if (anchorLocation.toUpperCase().equals("SOUTHEAST")){
            gbc.anchor = GridBagConstraints.SOUTHEAST;
        } else {
            gbc.anchor = GridBagConstraints.CENTER;
        }

        gbc.gridx = gridx; // column
        gbc.gridy = gridy; // row
        gbc.gridwidth = gridWidth; // number of columns
        gbc.gridheight = gridHeight; // number of rows
        gbc.ipadx = ipadx; // width of object
        gbc.ipady = ipady; // height of object
        gbc.weightx = weightx; // shifts rows to side of set anchor
        gbc.weighty = weighty; // shifts columns to side of set anchor
        gbc.insets = insets; // placement inside cell
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.fill = GridBagConstraints.VERTICAL;

        return gbc;
    }

    private Insets setInsets(int top, int left, int bottom, int right){
        Insets insets = new Insets(top,left,bottom,right);
        return insets;
    }

    //**************************************************************************************
    // Interactive Object Methods
    private JTextField createWhiteBoldFgDarkGreyBgFixedSizeAlignTextField(String text, int textSize, int width, int height, int hAlign){
        JTextField txtField = new JTextField(text);

        txtField.setForeground(Color.WHITE);
        txtField.setBackground(new Color(50,50,50));
        txtField.setCaretColor(Color.CYAN);
        txtField.setFont(new Font(text, Font.BOLD, textSize));
        txtField.setPreferredSize(new Dimension(width, height));
        txtField.setHorizontalAlignment(hAlign);
        return txtField;
    }
    //**************************************************************************************
    // Object Action Methods
    private void setEnterTxtInTextFieldAction(){
        enterTxtInTextField.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        String textInTextField = enterTxtInTextField.getText();
                        if (isInteger(textInTextField)){
                            inputStringText.setText("");
                            inputIntText.setText(textInTextField);
                        } else {
                            inputIntText.setText("");
                            inputStringText.setText(textInTextField);
                        }
                    }
                }
        );
    }

    //**************************************************************************************
    // Panel Methods

    private JPanel createTopFrame(){
        // pnl.add(object, setGbc(column,row, columnFill,rowFill, columnExtraWidth,columnExtraWidth, cellAlignment, weightColumn, weightRow, setInsets(top, left, bottom, right)));

        JPanel pnl = new JPanel();

        pnl.setLayout(new GridBagLayout());

        Border gridBorder = BorderFactory.createMatteBorder(4,4,4,4,Color.BLUE);

        JLabel enterText = new JLabel("Enter Text");
        JLabel textIsString = new JLabel("Text Is String");
        JLabel textIsInt = new JLabel("Text Is Int");
        enterText.setBorder(gridBorder);
        enterTxtInTextField.setBorder(gridBorder);
        textIsString.setBorder(gridBorder);
        inputStringText.setBorder(gridBorder);
        textIsInt.setBorder(gridBorder);
        inputIntText.setBorder(gridBorder);
        setEnterTxtInTextFieldAction();
        pnl.add(enterText, setGbc(0,0, 1,1, 0,0, "CENTER", 0, 0, setInsets(10, 10, 10, 10)));
        pnl.add(enterTxtInTextField, setGbc(0,1, 1,1, 0,0, "CENTER", 0, 0, setInsets(10, 10, 10, 10)));
        pnl.add(textIsString, setGbc(1,0, 1,1, 0,0, "CENTER", 0, 0, setInsets(10, 10, 10, 10)));
        pnl.add(inputStringText, setGbc(1,1, 1,1, 0,0, "CENTER", 0, 0, setInsets(10, 10, 10, 10)));
        pnl.add(textIsInt, setGbc(2,0, 1,1, 0,0, "CENTER", 0, 0, setInsets(10, 10, 10, 10)));
        pnl.add(inputIntText, setGbc(2,1, 1,1, 0,0, "CENTER", 0, 0, setInsets(10, 10, 10, 10)));

        pnl.setOpaque(false);
        return pnl;
    }

    private JScrollPane createTopScrollPane(){
        JScrollPane scrollPane = new JScrollPane();
        Border raisedBevel = BorderFactory.createRaisedBevelBorder();
        Border lineBorder = BorderFactory.createMatteBorder(2, 2, 2, 2, new Color(224,224,224));
        Border loweredBevel = BorderFactory.createLoweredBevelBorder();
        Border compoundSetup = BorderFactory.createCompoundBorder(raisedBevel, lineBorder);
        Border compoundFinal = BorderFactory.createCompoundBorder(compoundSetup, loweredBevel);

        scrollPane.setBorder(compoundFinal);
        scrollPane.getViewport().setView(topFrame);
        return scrollPane;
    }

    private JPanel createCenterFrame() {
        JPanel pnl = new JPanel();
        Border raisedBevel = BorderFactory.createRaisedBevelBorder();
        Color lineColor = new Color(224, 224, 224);
        Border lineBorder = BorderFactory.createMatteBorder(5, 5, 5, 5, lineColor);
        Border loweredBevel = BorderFactory.createLoweredBevelBorder();
        Border compoundSetup = BorderFactory.createCompoundBorder(raisedBevel, lineBorder);
        Border compoundFinal = BorderFactory.createCompoundBorder(compoundSetup, loweredBevel);
        TitledBorder topFrameTitle = BorderFactory.createTitledBorder(compoundFinal, "Stuff");
        topFrameTitle.setTitleJustification(TitledBorder.CENTER);

        pnl.setBorder(topFrameTitle);
        pnl.setLayout(new GridBagLayout());

        pnl.setOpaque(false);
        return pnl;
    }

    //**************************************************************************************

    public static void main(String[] args) {

        new TestGui();
    }
}

JTextField 在第 15 行实例化

JTextField is instantiated on line# 15

addActionListener 从第 106 行开始

addActionListener starts on line# 106

如果有人知道如何在不必先按输入"的情况下更新其他 JLabels,我将不胜感激.谢谢:)

If anyone has any idea how to make the other JLabels update without having to first press "enter", I would much appreciate the help. Thanks :)

推荐答案

您需要改用 DocumentListener,然后相应地处理更改.将方法 setEnterTxtInTextFieldAction 更改为:

You need to use DocumentListener instead, then handle the changes accordingly. Change the method setEnterTxtInTextFieldAction to:

private void setEnterTxtInTextFieldAction(){
    enterTxtInTextField.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent documentEvent) {
            performAction();
        }

        @Override
        public void removeUpdate(DocumentEvent documentEvent) {
            performAction();
        }

        @Override
        public void changedUpdate(DocumentEvent documentEvent) {
        }
    });

    enterTxtInTextField.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    performAction();
                }
            }
    );
}

private void performAction() {
    String textInTextField = enterTxtInTextField.getText();
    if (isInteger(textInTextField)){
        inputStringText.setText("");
        inputIntText.setText(textInTextField);
    } else {
        inputIntText.setText("");
        inputStringText.setText(textInTextField);
    }
}

这篇关于更新 JTextField.addActionListener 而不按“回车";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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