Java - 使用 Jbutton 监听器获取 JRadioButton cmd

标签 java swing radio-button jbutton

我是 java 新手,正在创建一个简单的 gui 应用程序。在这个简单的应用程序中,我试图为公司写一封电子商务信函。所以,我计划了我的应用程序是这样的..

First i ask to user if he want to write an letter to British Firm or American. For this i use two radio buttons(one for american firm and second for british) and JButton. When user Trigger jbutton then i want to get radiobutton command(which type of letter user want to write).

问题是我不知道在触发 jButton 时获取 Radiobutton 命令。请给我一个简单的想法(如果可能的话,对于初学者来说并不复杂)来获取 RadioButtons 的值..

这是我的java代码:

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

class englet{

    static public JFrame f;
    static public JPanel p;
    static class getTypeOfLetter implements ActionListener{

        public void actionPerformed( ActionEvent e){
            String btnInput = e.getActionCommand();
            System.out.println(btnInput);

        }
    }
    public static void askletter(){
        JRadioButton btnRadio1;
        JRadioButton btnRadio2;
        ButtonGroup btngrp;
        JButton btnGo = new JButton("Write");
        btnRadio1 = new JRadioButton("Write Letter For American Firm");
        btnRadio1.setActionCommand("Amer");
        btnRadio2 = new JRadioButton("Write Letter For British Firm");
        btnRadio2.setActionCommand("Brit");
        btngrp    = new ButtonGroup();
        btnGo.setActionCommand("WriteTest");
        btnGo.addActionListener(new getTypeOfLetter());
        btngrp.add(btnRadio1);
        btngrp.add(btnRadio2);
        p.add(btnRadio1);
        p.add(btnRadio2);
        p.add(btnGo);
    }
    englet(){
        f  = new JFrame("English Letter");
        p  = new JPanel();
        askletter();
        f.add(p);
        f.setSize(400,200);
        f.setVisible(true);

    }
    public static void main (String[] argv ){
        englet i = new englet();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

我使用的是 Notepad++ 和 CMD。没有使用任何其他工具,例如 netbeans initllli ecplisse。 **重新编辑 ** 我想要一个可能的解决方案并且可以满足我..这个应用程序可以工作,但我无法使用 jubtton 获取单选按钮命令..

最佳答案

您遇到了几个问题:

  • 过度使用静态。代码的大多数字段和方法应该是非静态的
  • 您缺少传输所需信息所必需的关键字段。要获取选定的 JRadioButton,您需要创建 JRadioButton 字段并检查哪个 JRadioButton 被选中,或者(和我的偏好),您需要将 ButtonGroup 变量设为字段并根据 ButtonGroup 返回的 ButtonModel 检查已选择哪个 JRadioButton。

    您当前正在使用局部变量,这些变量在整个类中不可见,这就是为什么 JRadioButtons 或 ButtonModel 大多数是字段(在类中声明)。

  • 如果您使用上面的 ButtonModel,则必须为每个 JRadioButton 提供适当的 actionCommand 字符串。

例如:

import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class GetRadio extends JPanel {
    private static final String[] FIRMS = {"American Firm", "British Firm"};

    // You need this field to access it in your listener
    private ButtonGroup buttonGroup = new ButtonGroup();

    public GetRadio() {
        // create JButton and add ActionListener
        JButton button = new JButton("Select");
        button.addActionListener(new ButtonListener());

        // JPanel with a grid layout with one column and variable number of rows
        JPanel radioButtonPanel = new JPanel(new GridLayout(0, 1));
        radioButtonPanel.setBorder(BorderFactory.createTitledBorder("Select Firm")); // give it a title
        for (String firm : FIRMS) {
            // create radiobutton and set actionCommand
            JRadioButton radioButton = new JRadioButton(firm);
            radioButton.setActionCommand(firm);

            // add to button group and JPanel
            buttonGroup.add(radioButton);;
            radioButtonPanel.add(radioButton);
        }

        // add stuff to main JPanel
        add(radioButtonPanel);
        add(button);

    }

    private class ButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // get button model of selected radio button from ButtonGroup
            ButtonModel model = buttonGroup.getSelection();

            // if null, no country selected
            if (model == null) {
                Component component = GetRadio.this;
                String message = "You must first select a country!";
                String title = "Error: No Country Selected";
                int type = JOptionPane.ERROR_MESSAGE;
                JOptionPane.showMessageDialog(component, message, title, type);
            } else {
                // valid country selected
                String country = model.getActionCommand();
                System.out.println("Letter to " + country);
            }
        }
    }

    private static void createAndShowGui() {
        GetRadio mainPanel = new GetRadio();

        JFrame frame = new JFrame("Get Radio Btn");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

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

关于Java - 使用 Jbutton 监听器获取 JRadioButton cmd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35207924/

相关文章:

python - 如何使用 Flask 通过 HTML 表单携带带空格的字符串

java - Java 中的线程可以缓存 final 字段吗?

javascript - jQuery JavaScript : take action when radio button is selected

java - 在 Java 8 中使用 Lambda 从 Map of Maps 生成 Map

java - 使用对话框创建施工单(每次我尝试运行它都会终止)?

java - 绘制跨多个 View 或面板或水平滚动的 Java 2D 图表

java - java中使用arraylist填充JTable

html - IE 单选按钮隐藏不起作用

java - liquibase 迁移 2.x 到 3.0 的问题

java - Facebook Account-Kit + React.js + Spring boot