简体   繁体   English

如何使用动作侦听器在文本字段中显示多个 Jbutton?

[英]How can I show multiple Jbuttons in textfield using action listener?

I have four buttons named A,B,C,D and have action listener for each, in result when I press A it works but when i press other buttons it removes the first, it displays only one button in textfield, what should I do to print multiple buttons in my text field.我有四个名为 A、B、C、D 的按钮,每个按钮都有动作侦听器,结果当我按下 A 时它可以工作,但是当我按下其他按钮时它会删除第一个,它只在文本字段中显示一个按钮,我该怎么办在我的文本字段中打印多个按钮。

截屏

'package actionlistenerdemo;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ActionListenerDemo {

    public static void main(String[] args) {
    JFrame win = new JFrame("Action Listener");
    JPanel P1, P2;
    P1 = new JPanel();
    JTextField tf = new JTextField();
    tf.setColumns(10);
    tf.setEditable(false);
    P1.add(tf);
    win.add(P1,BorderLayout.PAGE_START);
    P2 = new JPanel();
    P2.setLayout (new GridLayout(2,2));
    JButton b1, b2, b3, b4; 
    b1 = new JButton(" A ");
    P2.add(b1);
    b2 = new JButton(" B ");
    P2.add(b2);
    b3 = new JButton(" C ");
    P2.add(b3);
    b4 = new JButton(" D ");
    P2.add(b4);
    b1.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
            tf.setText("A");
        }
    });

    b2.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
            tf.setText("B");
        }
    });

    b3.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
           tf.setText("C");
        }
    });

    b4.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
           tf.setText("D");
        }
    });

    win.add(P2);
    win.setSize(200,200);
    win.setVisible(true);

}

}'    

tf.setText("X"); overwrites the current text from the Textfield.覆盖文本字段中的当前文本。

If you want to display AB wehn you press Button A followed by Button B, then you need to get the the current Text from the Textfield add the next Character and set the the text:如果要在按下按钮 A 后按按钮 B 时显示AB ,则需要从文本字段中获取当前文本,添加下一个字符并设置文本:

tf.setText(tf.getText() + "X");

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

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