如何在 Java 个 GUI 中进行多项选择

How to Make a Multiple Choice in Java GUI's

这个程序应该是为那些想要预订宴会厅的人准备的,并要求用户回答一些关于活动的简单问题。对于膳食计划、房间类型和 10 天的问题,我只想让用户选择两个选项,然后用户单击其中一个选项。就像多项选择一样。我尝试查找资料,但我找到的所有教程都是针对多项选择测验的控制台版本。我知道执行此操作的一种方法是使用 JButtons,但我想知道是否有更用户友好的方法来执行此操作。

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
abstract class Main implements ActionListener{
  public static void main(String[] args) {
    
        JFrame frame = new JFrame("Catering Company");
        frame.setSize(770,490);
        frame.setVisible(true);

        JPanel panel = new JPanel();
        panel.setLayout(null);

        JLabel DayLabel = new JLabel("What day of the week is it?:");
        DayLabel.setBounds(150, 80, 200, 20);
        JTextField DayLabelTXT = new JTextField(5);
        DayLabelTXT.setBounds(360, 80, 70, 25);

        JLabel AdultCount = new JLabel("How many adults are there?:");
        AdultCount.setBounds(145, 120, 220, 20);
        JTextField AdultCountTXT = new JTextField(5);
        AdultCountTXT.setBounds(360, 120, 70, 25);

        JLabel ChildCount = new JLabel("How many children are there?:");
        ChildCount.setBounds(134, 160, 225, 20);
        JTextField ChildCountTXT = new JTextField(5);
        ChildCountTXT.setBounds(360, 160, 70, 25);

        JLabel MealPlan = new JLabel("Choose a meal plan:");
        MealPlan.setBounds(208, 200, 200, 20);


        JLabel room = new JLabel("Which room would you like to choose?:");
        room.setBounds(78, 240, 280, 20);

        JLabel TenDays = new JLabel("Will you pay within the next 10 days?:");
        TenDays.setBounds(85, 280, 275, 20);

        JLabel initialDep = new JLabel("What is your initial deposit:");
        initialDep.setBounds(155, 320, 200, 20);
        JTextField initialDepTXT = new JTextField(5);
        initialDepTXT.setBounds(360, 320, 70, 25);



        panel.add(DayLabel);
        panel.add(DayLabelTXT);

        panel.add(AdultCount);
        panel.add(AdultCountTXT);

        panel.add(ChildCount);
        panel.add(ChildCountTXT);

        panel.add(MealPlan);

        panel.add(room);

        panel.add(TenDays);

        panel.add(initialDep);
        panel.add(initialDepTXT);

        frame.add(panel);
  }
}

我认为你有多项选择,你可以使用 JRadioButtonJComboBoxJCheckBox,因为你有多项选择我认为 JCheckBox 是好的一个给你,看看这个来自 https://docs.oracle.com/ :

的例子
//In initialization code:
chinButton = new JCheckBox("Chin");
chinButton.setMnemonic(KeyEvent.VK_C); 
chinButton.setSelected(true);

glassesButton = new JCheckBox("Glasses");
glassesButton.setMnemonic(KeyEvent.VK_G); 
glassesButton.setSelected(true);

hairButton = new JCheckBox("Hair");
hairButton.setMnemonic(KeyEvent.VK_H); 
hairButton.setSelected(true);

teethButton = new JCheckBox("Teeth");
teethButton.setMnemonic(KeyEvent.VK_T); 
teethButton.setSelected(true);

结果: