如何访问KeyListener中JTextField对象数组的对象?

发布于 2025-01-16 22:08:44 字数 1102 浏览 3 评论 0 原文

我有这段代码,它使用包含 25 个元素的 JTextField 对象数组,我希望在更改或添加文本后,KeyListener (keyPressed) 会以不同的方式处理该元素。

那么如何将已更改字段的索引获取到侦听器中呢?

对于存在,第 10 个元素在用户添加或更改文本后会将字段的背景更改为绿色。

    public JTextField field[];
public void TextFilling(){
    field = new JTextField[25]; Font font = new Font("Times new Roman", Font.BOLD ,30);
    textChangedListener listener = new textChangedListener();

    //There are the process of formating size, location and other settings of the elements:
    for (int i = 0, j=0, k=0; i< field.length; i++, k++) {field[i] = new JTextField();
        if (k==j) field[i].setText("1");
        if (i % 5 == 0 && i!=0) {j++; k = 0;}
        field[i].setBounds(5+(100*(k+1)), 5+(100*(j+1)), 95, 95);
        field[i].setHorizontalAlignment(JTextField.CENTER); field[i].setFont(font);

        frame.add(field[i]);
        field[i].addKeyListener(listener);
    }
}
class textChangedListener implements KeyListener
{
    public void keyPressed(KeyEvent e){
        
    }
    public void keyReleased(KeyEvent e){}

    public void keyTyped(KeyEvent e){}
}

I have this code, that use an array of the JTextField objects for 25 elements and I want that ever element will be handle by KeyListener (keyPressed) differently after changing or adding text there.

So how can I get an index of the changed field into the listener?

For exist, 10-th element will change the background of the field to the green after adding or changing there text by user.

    public JTextField field[];
public void TextFilling(){
    field = new JTextField[25]; Font font = new Font("Times new Roman", Font.BOLD ,30);
    textChangedListener listener = new textChangedListener();

    //There are the process of formating size, location and other settings of the elements:
    for (int i = 0, j=0, k=0; i< field.length; i++, k++) {field[i] = new JTextField();
        if (k==j) field[i].setText("1");
        if (i % 5 == 0 && i!=0) {j++; k = 0;}
        field[i].setBounds(5+(100*(k+1)), 5+(100*(j+1)), 95, 95);
        field[i].setHorizontalAlignment(JTextField.CENTER); field[i].setFont(font);

        frame.add(field[i]);
        field[i].addKeyListener(listener);
    }
}
class textChangedListener implements KeyListener
{
    public void keyPressed(KeyEvent e){
        
    }
    public void keyReleased(KeyEvent e){}

    public void keyTyped(KeyEvent e){}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不知在何时 2025-01-23 22:08:44

不要在文本组件上使用 KeyListener ,它没有帮助,而且您可能最终会处于状态突变的中间。

相反,使用 DocumentListener 来监视文本字段的更改,请参阅 如何编写文档监听器了解更多详细信息。

您还应该利用依赖注入,基本上将信息传递给需要与程序交互的类。

请参阅:

以获取更多信息。

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

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

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private List<JTextField> textFields;

        public TestPane() {
            setBorder(new EmptyBorder(64, 64, 64, 64));
            setLayout(new GridBagLayout());

            Font font = new Font("Times new Roman", Font.BOLD, 30);
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.ipadx = 75;
            gbc.ipady = 75;
            gbc.insets = new Insets(8, 8, 8, 8);
            for (int row = 0; row < 5; row++) {
                for (int col = 0; col < 5; col++) {
                    gbc.gridx = col;
                    gbc.gridy = row;
                    JTextField field = new JTextField(1);
                    field.setHorizontalAlignment(JTextField.CENTER);
                    field.setFont(font);
                    textFields.add(field);

                    if (row == col) {
                        field.setText("1");
                    }

                    int index = ((row * 5) + col) + 1;
                    if (index % 10 == 0) {
                        field.getDocument().addDocumentListener(new DocumentHighlighter(field));
                    }
                    add(field, gbc);
                }
            }
        }

        public class DocumentHighlighter implements DocumentListener {

            private JTextField field;
            private Color defaultColor;

            public DocumentHighlighter(JTextField field) {
                this.field = field;
                defaultColor = field.getBackground();
            }

            protected void highlightFieldIfRequired() {
                if (field.getText().isEmpty()) {
                    field.setBackground(defaultColor);
                } else {
                    field.setBackground(Color.GREEN);
                }
            }

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

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

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

我认为您即将面临的一件事是您如何共享和管理数据。

您想要花一些时间研究的一个概念是分离职责的方式。实现这一点的方法之一是通过“模型”。模型负责管理与数据关联的状态和规则。然后,视图负责呈现模型的当前状态并根据用户输入更新模型。

请参阅:

这个概念的关键要素之一是使用观察者模式。您已经在工作中看到了这一点,因为 Swing 侦听器是观察者。

哦,您真的非常想花时间学习和理解布局管理器 API。有关更多详细信息,请参阅在容器内布置组件

Don't use KeyListener on text components, it's not helpful and you might end up in the middle of mutation of the state.

Instead, use a DocumentListener to monitor the changes to the text field, see How to Write a Document Listener for more details.

You should also be making use of dependency injection, basically passing information to the classes which need to interact with your program.

See:

for more information.

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

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

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private List<JTextField> textFields;

        public TestPane() {
            setBorder(new EmptyBorder(64, 64, 64, 64));
            setLayout(new GridBagLayout());

            Font font = new Font("Times new Roman", Font.BOLD, 30);
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.ipadx = 75;
            gbc.ipady = 75;
            gbc.insets = new Insets(8, 8, 8, 8);
            for (int row = 0; row < 5; row++) {
                for (int col = 0; col < 5; col++) {
                    gbc.gridx = col;
                    gbc.gridy = row;
                    JTextField field = new JTextField(1);
                    field.setHorizontalAlignment(JTextField.CENTER);
                    field.setFont(font);
                    textFields.add(field);

                    if (row == col) {
                        field.setText("1");
                    }

                    int index = ((row * 5) + col) + 1;
                    if (index % 10 == 0) {
                        field.getDocument().addDocumentListener(new DocumentHighlighter(field));
                    }
                    add(field, gbc);
                }
            }
        }

        public class DocumentHighlighter implements DocumentListener {

            private JTextField field;
            private Color defaultColor;

            public DocumentHighlighter(JTextField field) {
                this.field = field;
                defaultColor = field.getBackground();
            }

            protected void highlightFieldIfRequired() {
                if (field.getText().isEmpty()) {
                    field.setBackground(defaultColor);
                } else {
                    field.setBackground(Color.GREEN);
                }
            }

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

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

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

One of the things I can see which is about to step up smack you then face, is how you share and manage data.

One concept you want to spend some time looking into, is the way you decouple your responsibilities. One of the ways this can be done is via a "model". A model is responsible for managing the state and rules associated with the data. The view then becomes responsible for presenting the current state of the model and updating the model based on the user input.

See:

One of the key elements to this concept is the use of the observer pattern. You've already seen this at work, as Swing listeners are observers.

Oh, and you really, really want to take the time and learn and understand the layout manager API. See Laying Out Components Within a Container for more details

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文