[英]basic radiobutton issue - java
package pkg411project;
import javax.swing.ButtonGroup;
public class CrudMain extends javax.swing.JInternalFrame {
public CrudMain() {
initComponents();
}
@SuppressWarnings("unchecked")
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
BankRecordFrame bdFrame = new BankRecordFrame();
bdFrame.setVisible(true);
this.jDesktopPane2.add(bdFrame);
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JDesktopPane jDesktopPane2;
private javax.swing.JLabel jLabel1;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JRadioButton jRadioButton3;
private javax.swing.JRadioButton jRadioButton4;
private javax.swing.JRadioButton jRadioButton5;
// End of variables declaration
//ButtonGroup group = new ButtonGroup();
//group.
}
我認為這是一個簡單的問題。 我有四個單選按鈕,並在單選按鈕下面有一個常規的提交按鈕。 當用戶單擊“提交”按鈕(此時已選擇單選按鈕之一)時,我正在嘗試取消Jframe。根據選擇的單選按鈕,將啟動Jframe。 您如何將其放入代碼中? 有任何想法嗎?
在按鈕的動作偵聽器中,檢查選中了哪個單選按鈕:
private void jButton1ActionPerformed(ActionEvent evt) {
if (jRadioButton1.isSelected()) {
// show frame 1
}
else if (jRadioButton2.isSelected()) {
// show frame 2
}
else if (jRadioButton3.isSelected()) {
// show frame 3
}
else if (jRadioButton4.isSelected()) {
// show frame 4
}
}
您將要使用ButtonGroup來控制選擇行為(因此一次只能選擇一個單選按鈕)。 將動作偵聽器添加到JButton,然后在偵聽器內部,從ButtonGroup中檢索選定的按鈕。
您可以通過多種方式執行此操作。 我將嘗試在其中發布其中之一。
這不一定是最佳選擇,但它可能對您有用。 (我沒有測試過)
public class CrudMain extends javax.swing.JInternalFrame {
public CrudMain() {
initRadioButtons();
initOtherStuff();
}
private JRadioButton[] radioButtons = new JRadioButton[4];
private JRadioButton btn1 = new JRadioButton();
private JRadioButton btn2 = new JRadioButton();
private JRadioButton btn3 = new JRadioButton();
private JRadioButton btn4 = new JRadioButton();
private JButton submitBtn = new JButton("Submit");
public void initRadioButtons() {
radioButtons[0] = btn1;
radioButtons[1] = btn2;
radioButtons[2] = btn3;
radioButtons[3] = btn4;
}
public void initOtherStuff() {
//add stuff to your frame
.......
submitBtn.addActionListener(this)
}
public void actionPerformed(ActionEvent e) {
for(int i =0; i < radioButtons.length; i++){
if(radioButtons[i].isSelected()){
//Open your frame here
break; //Place break if you only want one radiobutton to be checked.
} else {
//This button was not selected
}
}
}
因此,讓我們看一下這段代碼。 我將所有按鈕放入數組中,以便您可以輕松地循環瀏覽內容以檢查是否已選擇它們。 我將actionListener放在按鈕上,當有人單擊該按鈕時將觸發它。 當actionListener觸發時,它將遍歷數組。 在每次迭代中,都會檢查每個按鈕狀態。 如果選擇了一個,它將觸發一個動作。
就是這樣。 如果您需要有關此代碼的幫助,請告訴我!
祝好運!
編輯:
剛剛注意到,使用這種方法不能為每個單選按鈕指定操作。 這就是您必須添加的內容:)祝您好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.