JAVA图形用户界面 写程序:当用户点击单选按钮时,在下面的标签上显示出当前所选定的数据库服务器类型。
时间: 2024-02-09 22:09:10 浏览: 29
可以通过使用Java Swing库中的JRadioButton和JLabel组件来实现此功能。以下是一个示例代码:
```java
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
public class DatabaseTypeSelector extends JFrame implements ActionListener {
// 定义单选按钮和标签
private JRadioButton mysqlButton, oracleButton, sqlServerButton;
private JLabel selectedLabel;
public DatabaseTypeSelector() {
super("Database Type Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);
setLayout(new FlowLayout());
// 初始化单选按钮和标签
mysqlButton = new JRadioButton("MySQL");
oracleButton = new JRadioButton("Oracle");
sqlServerButton = new JRadioButton("SQL Server");
selectedLabel = new JLabel("Selected database type: ");
// 将单选按钮添加到ButtonGroup中,确保只有一个按钮被选中
ButtonGroup group = new ButtonGroup();
group.add(mysqlButton);
group.add(oracleButton);
group.add(sqlServerButton);
// 添加事件监听器
mysqlButton.addActionListener(this);
oracleButton.addActionListener(this);
sqlServerButton.addActionListener(this);
// 将组件添加到窗口中
add(mysqlButton);
add(oracleButton);
add(sqlServerButton);
add(selectedLabel);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// 获取选中的单选按钮的文本,并将其显示在标签上
String selected = e.getActionCommand();
selectedLabel.setText("Selected database type: " + selected);
}
public static void main(String[] args) {
new DatabaseTypeSelector();
}
}
```
运行代码后,会显示一个窗口,其中包含三个单选按钮和一个标签。当用户点击单选按钮时,标签上会显示当前选中的数据库服务器类型。