简体   繁体   English

从多个JButton java swing的第一个单击的Jbutton返回结果

[英]Returning result from the first clicked Jbutton from multiple JButtons java swing

Basically I have n JButtons. 基本上我有n个JButton。 If any of them is clicked, they return a certain number. 如果单击其中任何一个,它们将返回一定的数字。 I have a menu with each of the buttons and when the user clicks one, my menu method returns the number returned by the Button handler. 我有一个包含每个按钮的菜单,当用户单击一个菜单时,我的菜单方法返回由Button处理程序返回的数字。 Is it possible? 可能吗?

Something like: 就像是:

frame.add(button1..)
frame.add(button2..)
frame.add(button3..)
if (button1.isClicked()) {
    return button1ActionHandler();
} else if (button2.isClicked()) {
       return button2ActionHandler();
} else if (button3.isClicked()) {
             return button3ActionHandler();
}

The problem is, the code is not waiting for me to click a button so it won't enter in any of those if's. 问题是,代码没有等待我单击按钮,因此不会在其中输入任何if。 What can I do for the program to wait for click and how can I check if a button is clicked? 我要如何做才能让程序等待点击,如何检查按钮是否被点击?

Start by having a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners . 首先看一下如何使用按钮,复选框和单选按钮以及如何编写动作侦听器

Remember, a GUI is an event driven environment, that is, something and then you respond to it. 记住,GUI是事件驱动的环境,即某些东西,然后您对其进行响应。

You need to register an ActionListener against each button, when the button is triggered, you need to take appropriate action. 您需要针对每个按钮注册一个ActionListener ,当按钮被触发时,您需要采取适当的措施。

There are a number of ways you could achieve this, you could set the actionCommand of the buttons with appropriate information that you can use to ascertain what should be done when the button is clicked. 您可以通过多种方法来实现此目的,可以使用适当的信息来设置按钮的actionCommand ,这些信息可以用来确定单击按钮时应执行的操作。 You could use the source property of the ActionEvent to determine the source of the event and take appropriate action, as exampels 您可以使用ActionEventsource属性来确定事件的来源并采取适当的措施,例如

It sounds like you want to present the user with several options, let him choose one of the options, and then have him press a "submit" button to submit that option to the program. 听起来您想向用户显示几个选项,让他选择一个选项,然后让他按下“提交”按钮以将该选项提交给程序。 If so, then I think that your best bet is to use JRadioButtons, all added to a ButtonGroup -- this allows only one of the radio buttons to be selected at any time, or use a JComboBox. 如果是这样,那么我认为最好的选择是使用全部添加到ButtonGroup的JRadioButtons-这允许随时仅选择一个单选按钮,或者使用JComboBox。 Either way, it would be easy to extract the information regarding which selection the user made. 无论哪种方式,都将很容易提取有关用户做出选择的信息。 If you use the first option, use of JRadioButtons, ButtonGroup and a "submit" button, you simply get the selected ButtonModel from the ButtonGroup by calling its getSelection() method, and then extract the actionCommand String from this model by calling getActionCommand() . 如果使用第一个选项,则使用JRadioButtons,ButtonGroup和“提交”按钮,只需调用ButtonGroup的getSelection()方法即可从ButtonGroup中获取所选的ButtonModel,然后通过调用getActionCommand()从此模型中提取actionCommand字符串。 。 If you decide on the second option, use of a JComboBox together with a "submit" button, then simply call getSelectedItem() on the JComboBox within your submit button's ActionListener. 如果决定第二个选项,请同时使用JComboBox和“提交”按钮,然后在提交按钮的ActionListener中的JComboBox上调用getSelectedItem()

Below I show you both options. 下面,我向您展示两个选项。 Note that my submit button doesn't use an ActionListener but rather an AbstractAction, which is kind of like an ActionListener on steroids. 请注意,我的提交按钮不使用ActionListener,而是使用AbstractAction,它类似于类固醇上的ActionListener。

import java.awt.event.ActionEvent;
import javax.swing.*;

public class SelectionEg extends JPanel {
    private static final String[] SELECTIONS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
    private ButtonGroup buttonGroup = new ButtonGroup(); 
    private JComboBox<String> selectionComboBox = new JComboBox<>(SELECTIONS);

    public SelectionEg() {
        for (String selection : SELECTIONS) {
            JRadioButton radioButton = new JRadioButton(selection);
            radioButton.setActionCommand(selection);
            add(radioButton);
            buttonGroup.add(radioButton);
        }
        add(selectionComboBox);
        add(new JButton(new SubmitAction("Submit")));        
    }

    private class SubmitAction extends AbstractAction {
        public SubmitAction(String name) {
            super(name);
            putValue(MNEMONIC_KEY, (int) name.charAt(0));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            ButtonModel model = buttonGroup.getSelection();
            if (model == null) {
                // nothing selected yet, ignore this
                return;
            }
            String message = "The selected radio button is: " + model.getActionCommand();
            System.out.println(message);

            message = "The selection from the combo box is: " + selectionComboBox.getSelectedItem();
            System.out.println(message);
        }
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("Selelection Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new SelectionEg());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

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

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