当我单击确定按钮时,它应该打印所有选中的项目。这是我尝试过的。
我尝试了以下代码,但它不起作用。
public class FilePermission extends JPanel implements ItemListener {
static String[] videoAvailable = new String[25];
static int j = 0;
JCheckBox[] file_boxes = new JCheckBox[25];
JButton button;
StringBuffer choices;
JLabel pictureLabel;
//static int j = 0;
public FilePermission() {
super(new BorderLayout());
JPanel checkPanel = new JPanel(new GridLayout(0, 1));
//Create the check boxes.
for (int i = 0; i < videoAvailable.length; i++) {
if (videoAvailable[i] != null) {
file_boxes[i] = new JCheckBox(videoAvailable[i]);
file_boxes[i].addItemListener(this);
checkPanel.add(file_boxes[i]);
}
}
button = new JButton("ok");
//Register a listener for the check boxes.
button.addItemListener(this);
//Indicates what's on the geek.
//Set up the picture label
pictureLabel = new JLabel();
pictureLabel.setFont(pictureLabel.getFont().deriveFont(Font.ITALIC));
//Put the check boxes in a column in a panel
checkPanel.add(button);
add(checkPanel, BorderLayout.LINE_START);
add(pictureLabel, BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
/** Listens to the check boxes. */
public void itemStateChanged(ItemEvent e) {
for (int i = 0; i < videoAvailable.length; i++) {
if (videoAvailable[i] != null) {
if (file_boxes[i].isSelected()) {
System.out.println(file_boxes[i]);
}
}
}
if (button.isSelected()) {
System.out.println(button);
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("CheckBoxDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new FilePermission();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) throws IOException {
File directory = new File("D:\\ims\\");
parseDir(directory);
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
这些方法是从 java 类的 main 方法调用的。如果你不明白,我想回答。