上机一: 编写程序,创建如下图所示的图形界面: “ RadioCheckBox De... t 苹果 橘子 香蕉 口 文学 艺术 口 体育 确定 你最喜欢的水果是:香蕉你的爱好包括:文学 体育Java语言
时间: 2024-02-06 10:02:53 浏览: 62
好的,根据您的要求,我可以为您提供Java代码来创建这个图形界面。请注意,我将使用Swing库来实现这个界面。
```java
import javax.swing.*;
import java.awt.*;
public class FruitAndHobbyFrame extends JFrame {
private JRadioButton appleRadioButton, orangeRadioButton, bananaRadioButton;
private JCheckBox literatureCheckBox, artCheckBox, sportsCheckBox;
public FruitAndHobbyFrame() {
setTitle("RadioCheckBox Demo");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// 创建水果选择区域
JPanel fruitPanel = new JPanel();
fruitPanel.setBorder(BorderFactory.createTitledBorder("请选择您最喜欢的水果"));
ButtonGroup fruitButtonGroup = new ButtonGroup();
appleRadioButton = new JRadioButton("苹果");
orangeRadioButton = new JRadioButton("橘子");
bananaRadioButton = new JRadioButton("香蕉");
bananaRadioButton.setSelected(true); // 默认选中香蕉
fruitButtonGroup.add(appleRadioButton);
fruitButtonGroup.add(orangeRadioButton);
fruitButtonGroup.add(bananaRadioButton);
fruitPanel.add(appleRadioButton);
fruitPanel.add(orangeRadioButton);
fruitPanel.add(bananaRadioButton);
// 创建爱好选择区域
JPanel hobbyPanel = new JPanel();
hobbyPanel.setBorder(BorderFactory.createTitledBorder("请选择您的爱好"));
literatureCheckBox = new JCheckBox("文学");
artCheckBox = new JCheckBox("艺术");
sportsCheckBox = new JCheckBox("体育");
hobbyPanel.add(literatureCheckBox);
hobbyPanel.add(artCheckBox);
hobbyPanel.add(sportsCheckBox);
// 创建确定按钮
JButton confirmButton = new JButton("确定");
confirmButton.addActionListener(e -> {
// 输出选择结果
String fruit = "";
if (appleRadioButton.isSelected()) {
fruit = "苹果";
} else if (orangeRadioButton.isSelected()) {
fruit = "橘子";
} else if (bananaRadioButton.isSelected()) {
fruit = "香蕉";
}
String hobby = "";
if (literatureCheckBox.isSelected()) {
hobby += "文学 ";
}
if (artCheckBox.isSelected()) {
hobby += "艺术 ";
}
if (sportsCheckBox.isSelected()) {
hobby += "体育";
}
JOptionPane.showMessageDialog(null, "您最喜欢的水果是:" + fruit + "\n您的爱好包括:" + hobby);
});
// 将组件添加到窗口中
setLayout(new GridLayout(3, 1));
add(fruitPanel);
add(hobbyPanel);
add(confirmButton);
}
public static void main(String[] args) {
FruitAndHobbyFrame frame = new FruitAndHobbyFrame();
frame.setVisible(true);
}
}
```
请将此代码保存为`FruitAndHobbyFrame.java`文件,并在命令行中编译和运行它。您应该会看到一个类似于您所描述的图形界面。
阅读全文