我有一个jframe,它包含两个JRadioButton。
public class jradioButtontest extends javax.swing.JFrame {
public jradioButtontest() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jRadioButton1.setText("jRadioButton1");
jRadioButton2.setText("jRadioButton2");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(198, 198, 198)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jRadioButton2)
.addComponent(jRadioButton1))
.addContainerGap(203, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(80, 80, 80)
.addComponent(jRadioButton1)
.addGap(18, 18, 18)
.addComponent(jRadioButton2)
.addContainerGap(225, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new jradioButtontest().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
// End of variables declaration
}
我希望当我选择第一个JRadioButton时,应该取消选择其他JRadioButton。 我使用ready jframe,如何更改netbeans生成的代码? 这是怎么回事?
答案 0 :(得分:5)
默认情况下,在自己的ButtonGroup中创建一个新的JRadioButton,这意味着它们都可以独立选择。
如果您希望链接两个按钮,以便一次只能选择一个,则需要添加:
ButtonGroup group = new ButtonGroup();
group.add(jRadioButton1);
group.add(jRadioButton2);
构建完按钮后。
答案 1 :(得分:4)
将2 JRadioButtons
添加到单个javax.swing.ButtonGroup
实例。
答案 2 :(得分:0)
使用ButtonGroup:
ButtonGroup buttongroup = new ButtonGroup();
buttongroup.add(...);