2017-04-26 20 views
0

我試圖處理兩個事件,即openfilenewfilecheckbox,因爲一次只檢查一個設置爲1 checkbox只設置1個在java中選中的複選框

最少的代碼:

新文件

private void newfileActionPerformed(java.awt.event.ActionEvent evt) {           
    textArea.setText(""); 
    newfile.setSelected(true); 
    setTitle(filename); 
} 

中openFile

private void openfileActionPerformed(java.awt.event.ActionEvent evt) {           

    openfile.setSelected(true); 

    FileDialog filedialog = new FileDialog(textEditorGui.this, "Open File", FileDialog.LOAD); 
    filedialog.setVisible(true); 

    if(filedialog.getFile() != null) 
    { 
     filename = filedialog.getDirectory() + filedialog.getFile(); 
     setTitle(filename); 
    } 
} 

我試過設置,如果別人控制,計數器,以檢查是否複選框被選中,但它是不工作。這是部分工作,在這種情況下複選框正在檢查,但openfile不起作用。

我已經嘗試設置,如果其他控制在兩個塊檢查複選框未選中,然後設置該特定複選框true

+1

看一看(https://docs.oracle.com/javase/7/docs/api/java/awt/CheckboxGroup.html)他們正是爲了使用[CheckBoxGroup'']這個目的。你不需要任何額外的代碼。 –

+1

在「CheckBoxGroup」中添加所有複選框,一次只能選擇一個複選框。 –

+0

查看[如何使用按鈕,複選框和單選按鈕](https://docs.oracle.com/javase/tutorial/uiswing/components/button.html) - 搜索「組」 – MadProgrammer

回答

0

請注意,您可以使用JRadioButtonButtonGroup一次僅選擇一個按鈕。工作代碼:

package com.stackoverflow.json; 

import java.awt.*; 
import javax.swing.*; 

public class UI extends JFrame { 
    public static void main(String[] args) { 
     JFrame frame = new JFrame(); 
     frame.setSize(500, 600); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setLayout(new GridLayout(0,2)); 

     JRadioButton rb1 = new JRadioButton("squirrel"); 
     rb1.addActionListener(e -> { 
      System.out.println("man: " + ((JRadioButton) e.getSource()).isSelected()); 
     }); 
     JRadioButton rb2 = new JRadioButton("rabbit"); 
     rb2.addActionListener(e -> { 
      System.out.println("weman: " + ((JRadioButton) e.getSource()).isSelected()); 
     }); 

     ButtonGroup group = new ButtonGroup(); 
     group.add(rb1); 
     group.add(rb2); 

     frame.getContentPane().add(rb1, BorderLayout.CENTER); 
     frame.getContentPane().add(rb2, BorderLayout.CENTER); 

     frame.pack(); 
     frame.setVisible(true); 
    } 
}