Reputation: 11
I want to have a JFrame that displays 5 different check boxes. Multiple checkboxes should be able to be selected. This code only reads the ExchangingCard1 line and ignores all other checkboxes. When you run it you will have only one checkbox with "A" as the character.
JCheckBox ExchangingCard1 = new JCheckBox("A");
JCheckBox ExchangingCard2 = new JCheckBox("B");
JCheckBox ExchangingCard3 = new JCheckBox("C");
JCheckBox ExchangingCard4 = new JCheckBox("D");
JCheckBox ExchangingCard5 = new JCheckBox("E");
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setTitle("Exchange.");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(ExchangingCard1);
frame.setVisible(true);
frame.add(ExchangingCard2);
frame.setVisible(true);
frame.add(ExchangingCard3);
frame.setVisible(true);
frame.add(ExchangingCard4);
frame.setVisible(true);
frame.add(ExchangingCard5);
frame.setVisible(true);
Upvotes: 0
Views: 13564
Reputation: 51565
Put the check boxes in a JPanel, then put the JPanel to the JFrame.
Here's a runnable example.
package com.ggl.testing;
import java.awt.BorderLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CheckBoxTest2 implements Runnable {
private JFrame frame;
@Override
public void run() {
frame = new JFrame("Check Box Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel checkBoxPanel = new JPanel();
JCheckBox exchangingCard1 = new JCheckBox("A");
checkBoxPanel.add(exchangingCard1);
JCheckBox exchangingCard2 = new JCheckBox("B");
checkBoxPanel.add(exchangingCard2);
JCheckBox exchangingCard3 = new JCheckBox("C");
checkBoxPanel.add(exchangingCard3);
JCheckBox exchangingCard4 = new JCheckBox("D");
checkBoxPanel.add(exchangingCard4);
JCheckBox exchangingCard5 = new JCheckBox("E");
checkBoxPanel.add(exchangingCard5);
mainPanel.add(checkBoxPanel);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new CheckBoxTest2());
}
}
Upvotes: 2
Reputation: 46871
JFrame
by default use BorderLayoout
that adds items in the center by default. use proper layout.
Read more How to Use Various Layout Managers Try FlowLayout
Upvotes: 1