java jframe jradiobuttonMeunitem
时间: 2024-02-11 19:05:08 浏览: 63
java JRadioButton的使用
5星 · 资源好评率100%
要在Java JFrame中添加JRadioButtonMenuItem,可以使用JMenu和JRadioButtonMenuItem来实现。下面是一个简单的例子:
```java
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
public class RadioButtonMenuItemExample extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JRadioButtonMenuItem redRadio, greenRadio, blueRadio;
public RadioButtonMenuItemExample() {
setTitle("Radio Button Menu Item Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu colorMenu = new JMenu("Color");
menuBar.add(colorMenu);
redRadio = new JRadioButtonMenuItem("Red");
redRadio.addActionListener(this);
colorMenu.add(redRadio);
greenRadio = new JRadioButtonMenuItem("Green");
greenRadio.addActionListener(this);
colorMenu.add(greenRadio);
blueRadio = new JRadioButtonMenuItem("Blue");
blueRadio.addActionListener(this);
colorMenu.add(blueRadio);
// Group the radio buttons
JMenu groupMenu = new JMenu("Group");
menuBar.add(groupMenu);
ButtonGroup group = new ButtonGroup();
group.add(redRadio);
group.add(greenRadio);
group.add(blueRadio);
// Default selection
redRadio.setSelected(true);
// Add a label to display the selected color
JLabel label = new JLabel("Selected color: Red");
add(label, BorderLayout.CENTER);
}
@Override
public void actionPerformed(ActionEvent e) {
// Update the label when a radio button is selected
if (e.getSource() == redRadio) {
label.setText("Selected color: Red");
} else if (e.getSource() == greenRadio) {
label.setText("Selected color: Green");
} else if (e.getSource() == blueRadio) {
label.setText("Selected color: Blue");
}
}
public static void main(String[] args) {
RadioButtonMenuItemExample example = new RadioButtonMenuItemExample();
example.setVisible(true);
}
}
```
在上面的例子中,我们创建了一个JFrame,并使用JMenuBar添加了一个JMenu。在JMenu中,我们使用JRadioButtonMenuItem添加了三个选项并将它们添加到同一个ButtonGroup中,以确保只有一个选项可以被选中。当用户选择其中一个选项时,我们更新了一个JLabel来显示所选颜色。
阅读全文