2012-11-12 182 views
-1

我需要在Java中對以下情況下小碼:獲取複選框值

按鈕應該得到的選擇複選框,並在我的形式執行代碼 這些複選框。

+2

請執行嘗試自己。指針:[Swing教程](http://docs.oracle.com/javase/tutorial/uiswing/components/index.html),'JButton#setAction'或'JButton#addActionListener','JCheckbox#isSelected' – Robin

+0

這裏:http://stackoverflow.com/questions/1509682/how-to-check-the-status-of-checkbox-in-java-gui – WilliamShatner

回答

9

這是我爲你做一個例子:

enter image description here

enter image description here

import java.awt.BorderLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JCheckBox; 
import javax.swing.JFrame; 
import javax.swing.JOptionPane; 
import javax.swing.SwingUtilities; 

public class TestJCheckBox { 

    private JFrame frame; 
    private JCheckBox jcb; 
    private JButton button; 

    public TestJCheckBox() { 
     initComponents(); 
    } 

    private void initComponents() { 
     frame = new JFrame("Test"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setResizable(false); 

     jcb = new JCheckBox("JCheckBox1"); 

     button = new JButton("Is JCheckBox selected?"); 
     button.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent ae) { 
       if (jcb.isSelected()) { 
        JOptionPane.showMessageDialog(frame, "JCheckBox is selected"); 
       } else { 
        JOptionPane.showMessageDialog(frame, "JCheckBox is NOT selected"); 

       } 
      } 
     }); 

     frame.add(jcb, BorderLayout.CENTER); 
     frame.add(button, BorderLayout.SOUTH); 

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

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       new TestJCheckBox(); 
      } 
     }); 
    } 
} 
+1

ThanQ。我認爲這對我的問題是適當的。抱歉的人,我甚至沒有時間來編碼的東西。無論如何,我很高興與您的關注。 – Raj

+1

@Raj它的樂趣..作爲一個有用的提示不要急於或沒有SSCCE提問,因爲他們有可能相對較快地關閉 - 就像這一個。在轉向Q&A之前,請嘗試做自己的工作,對涉及的單獨主題的快速谷歌不會傷害:)。 –