【问题标题】:Java GUI JButton to actionlistnerJava GUI JButton 到 actionlistener
【发布时间】:2012-02-07 19:06:39
【问题描述】:

我在 NetBeans 中制作了一个 GUI。这是一个聊天程序,我有 4 个突击队员,例如 /join、/leave、/whisper 和 /leave

private void CommandoActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        JOptionPane.showMessageDialog(rootPane, "The following commandos are:" + "\n" + "\n" + "/join Channel name" + "\n" + "/leave channel name" + "\n" + "/whisper nick message" + "\n" + "/quit - quit the program");
    }  

这没关系,但我想要 actionlister 而不是 showMessageDialog,所以我可以推动它们,它出现在我的 JTextField 中。我想我可以让他们在那里,但我不知道如何让 actionlistener 与此结合。

编辑: 我想要的是按下 Commando 按钮并打开一个窗口,其中有 4 个新按钮,每个按钮都有一个 commando(/join、/leave、/whisper 和 /exit),所以当我按下其中一个按钮时,我得到了 commando在我的文本字段中,所以我只需要写下其余部分。 所以如果我按下“/join”按钮,我只需要写下频道名称。

EDIT2:如果我在描述问题方面做得很糟糕,我可以展示我想要的以及到目前为止所做的:

 private void showCommandActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        Object[] options = { "/join", "/leave", "/whisper", "/quit", "Ingenting" };


        int choice= JOptionPane.showOptionDialog(rootPane, "What do u want to do? ", null, WIDTH, WIDTH, null, options, rootPane);

        switch (choice) {
                case 0:
                    skrivTekst.setText("/Join ");
                skrivTekst.requestFocus();
                    break;
                case 1:
                    skrivTekst.setText("/Leave");
                skrivTekst.requestFocus();
                    break;
                case 2:
                    skrivTekst.setText("/Whisper");
                skrivTekst.requestFocus();
                    break;
                case 3:
                skrivTekst.setText("/Join ");
                skrivTekst.requestFocus();

                case 4:

                    System.exit(1); //this is wrong. i just want to close this window, not the whole program 
                default:

                    JOptionPane.showMessageDialog(null, "donno what!?!?!?!?!?!?!" + choice);
            }


    }                 

我希望这表明我想要什么以及我做了什么。 Ty :) 所以我剩下的唯一问题是关闭一个 JOptionPane 窗口而不是程序

【问题讨论】:

标签: java swing actionlistener jtextfield joptionpane


【解决方案1】:

1) 您可以在ButtonGroup 中实现JRadioButtons,然后只有一个选项可供选择,您可以在其中实现ActionListenerActionListener setText() 内部JTextField

2) 请使用标准 Swing JComponents 而不是从 palette 准备的 Components,有时覆盖基本 Swing 方法太难了

基于教程中 JRadioButton 示例的简单示例

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

/*
 * RadioButtonDemo.java is a 1.4 application that requires these files:
 * images/Bird.gif images/Cat.gif images/Dog.gif images/Rabbit.gif
 * images/Pig.gif
 */
public class RadioButtonDemo extends JPanel implements ActionListener {

    private static String birdString = "Bird";
    private static String catString = "Cat";
    private static String dogString = "Dog";
    private static String rabbitString = "Rabbit";
    private static String pigString = "Pig";
    private static final long serialVersionUID = 1L;
    private JLabel picture;

    public RadioButtonDemo() {
        super(new BorderLayout());
        //Create the radio buttons.
        JRadioButton birdButton = new JRadioButton(birdString);
        birdButton.setMnemonic(KeyEvent.VK_B);
        birdButton.setActionCommand(birdString);
        birdButton.setSelected(true);
        JRadioButton catButton = new JRadioButton(catString);
        catButton.setMnemonic(KeyEvent.VK_C);
        catButton.setActionCommand(catString);
        JRadioButton dogButton = new JRadioButton(dogString);
        dogButton.setMnemonic(KeyEvent.VK_D);
        dogButton.setActionCommand(dogString);
        JRadioButton rabbitButton = new JRadioButton(rabbitString);
        rabbitButton.setMnemonic(KeyEvent.VK_R);
        rabbitButton.setActionCommand(rabbitString);
        JRadioButton pigButton = new JRadioButton(pigString);
        pigButton.setMnemonic(KeyEvent.VK_P);
        pigButton.setActionCommand(pigString);
        //Group the radio buttons.
        ButtonGroup group = new ButtonGroup();
        group.add(birdButton);
        group.add(catButton);
        group.add(dogButton);
        group.add(rabbitButton);
        group.add(pigButton);
        //Register a listener for the radio buttons.
        birdButton.addActionListener(this);
        catButton.addActionListener(this);
        dogButton.addActionListener(this);
        rabbitButton.addActionListener(this);
        pigButton.addActionListener(this);
        //Set up the picture label.
        picture = new JLabel("Narrative");
        //The preferred size is hard-coded to be the width of the
        //widest image and the height of the tallest image.
        //A real program would compute this.
        //picture.setPreferredSize(new Dimension(177, 122));
        //Put the radio buttons in a column in a panel.
        JPanel radioPanel = new JPanel(new GridLayout(0, 1));
        radioPanel.add(birdButton);
        radioPanel.add(catButton);
        radioPanel.add(dogButton);
        radioPanel.add(rabbitButton);
        radioPanel.add(pigButton);
        add(radioPanel, BorderLayout.LINE_START);
        pigButton.setVisible(false);
        rabbitButton.setVisible(false);
        add(picture, BorderLayout.CENTER);
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
    }

    /** Listens to the radio buttons.
     * @param e
     */
    public void actionPerformed(ActionEvent e) {
        String narr = e.getActionCommand();
        picture.setText(narr);
    }

    /** Returns an ImageIcon, or null if the path was invalid.
     * @param path
     * @return
     */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = RadioButtonDemo.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

    /**
     * Create the GUI and show it. For thread safety, this method should be
     * invoked from the event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);
        //Create and set up the window.
        JFrame frame = new JFrame("RadioButtonDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Create and set up the content pane.
        JComponent newContentPane = new RadioButtonDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                createAndShowGUI();
            }
        });
    }
}

【讨论】:

    【解决方案2】:

    你想要 4 个按钮,每个按钮在文本字段中设置一个命令文本,对吗?

    joinButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            theTextField.setText("/join");
        }
    });
    

    对其他 3 个按钮执行相同操作。

    这是非常基本的东西。阅读tutorial about event listeners

    【讨论】:

    • @down_voter 我希望你能在这里发送一些描述
    • 答案是什么,但问题本身有些不完整 +1 至少可以抵消反对票。
    • 我按照我的理解回答了这个问题。现在 OP 已经解释了他想要什么,看来我的理解是正确的。
    • 是的,绝对是正确的,而且我发现该教程也值得一提。
    • TY 老兄,theTextField.setText("/join");与我的 JOptionPane.showOptionDialog 完美配合
    【解决方案3】:

    这样的?

    public void actionPerformed(ActionEvent event) {
        Object source = event.getSource();
        if (source == join) {
            textField.setText("/join");
        } else if (source == leave) {
            textField.setText("/leave");
        } else if (source == whisper) {
            textField.setText("/join");
        } else {
            textField.setText("/exit");
        }
    }
    

    这是假设您的按钮被命名为加入、离开、耳语和退出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-17
      • 2023-02-02
      • 2018-10-22
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 2020-11-01
      • 2013-11-02
      相关资源
      最近更新 更多