I'm new to JFrame
, I was trying to populate dynamic checkboxes with a scroll pane. I tried with some code as seen below. My Focus is:
import java.awt.EventQueue;
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.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollBar;
import javax.swing.JTextField;
import javax.swing.border.BevelBorder;
import javax.swing.border.TitledBorder;
import net.miginfocom.swing.MigLayout;
public class JFrameMain extends JFrame {
private JPanel contentPane;
private JButton btnOkay;
private JTextField textField;
private JRadioButton yes;
private JRadioButton no;
// Launch the application.
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrameMain frame = new JFrameMain();
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
// Create the frame.
public JFrameMain() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 556, 383);
contentPane = new JPanel();
contentPane.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(null, "Enetr the class", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel.setBounds(44, 23, 443, 53);
contentPane.add(panel);
panel.setLayout(null);
yes = new JRadioButton("yes");
yes.setSelected(true);
yes.setBounds(144, 20, 64, 25);
panel.add(yes);
yes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(yes.isSelected())
{
no.setSelected(false);
textField.setEnabled(true);
}
}
});
no = new JRadioButton("No");
no.setBounds(212, 20, 64, 25);
panel.add(no);
no.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(no.isSelected())
{
yes.setSelected(false);
textField.setEnabled(false);
}
}
});
btnOkay = new JButton("Okay");
btnOkay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Text field
System.out.println(textField.getText());
}
});
btnOkay.setBounds(120, 281, 97, 25);
contentPane.add(btnOkay);
JPanel panelCheckBox = new JPanel();
panelCheckBox.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
panelCheckBox.setBounds(44, 89, 443, 90);
contentPane.add(panelCheckBox);
panelCheckBox.setLayout(new MigLayout("", "[]", "[]"));
int numberCheckBox = 10;
JCheckBox[] checkBoxList = new JCheckBox[numberCheckBox];
for(int i = 0; i < numberCheckBox; i++) {
checkBoxList[i] = new JCheckBox("CheckBox" + i);
panelCheckBox.add(checkBoxList[i]);
}
JScrollBar scrollBar = new JScrollBar();
scrollBar.setBounds(492, 89, 21, 90);
contentPane.add(scrollBar);
JPanel panel_1 = new JPanel();
panel_1.setBorder(new TitledBorder(null, "Enter Class", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel_1.setBounds(44, 192, 443, 66);
contentPane.add(panel_1);
panel_1.setLayout(null);
textField = new JTextField();
//textField.setEnabled(false);
textField.setBounds(55, 23, 336, 22);
panel_1.add(textField);
textField.setColumns(10);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(1);
}
});
btnCancel.setBounds(263, 281, 97, 25);
contentPane.add(btnCancel);
}
}
I was stuck with this for the past 3 days. Can't get the selected checkbox name in dynamic checkboxes. Can anyone help me with this?
Start by having a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener
One thing you want to focus on is the setActionCommand
for buttons and getActionCommand
for the ActionEvent
For example...
ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("You clicked " + e.getActionCommand());
}
};
for (int i = 0; i < numberCheckBox; i++) {
checkBoxList[i] = new JCheckBox("CheckBox" + i);
panelCheckBox.add(checkBoxList[i]);
checkBoxList[i].addActionListener(actionListener);
}
You're also going to want to take the time to read through How to Use Scroll Panes and Laying Out Components Within a Container
Now, because it annoys me, the following is basically your design using proper layout managers
Yours...
Compared to mine...
And now you also have resisability for free
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
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.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBorder(new EmptyBorder(16, 16, 16, 16));
setLayout(new GridBagLayout());
JTextField textField = new JTextField(40);
JRadioButton yes = new JRadioButton("yes");
yes.setSelected(true);
yes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (yes.isSelected()) {
textField.setEnabled(true);
}
}
});
JRadioButton no = new JRadioButton("No");
no.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (no.isSelected()) {
textField.setEnabled(false);
}
}
});
JPanel enterClassPane = new JPanel(new GridBagLayout());
enterClassPane.setBorder(new TitledBorder(null, "Enetr the class", TitledBorder.LEADING, TitledBorder.TOP, null, null));
enterClassPane.add(yes);
enterClassPane.add(no);
JPanel panelCheckBox = new JPanel(new WrapLayout(WrapLayout.LEADING));
int numberCheckBox = 10;
JCheckBox[] checkBoxList = new JCheckBox[numberCheckBox];
for (int i = 0; i < numberCheckBox; i++) {
checkBoxList[i] = new JCheckBox("CheckBox" + i);
panelCheckBox.add(checkBoxList[i]);
checkBoxList[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("You clicked " + e.getActionCommand());
}
});
}
JPanel classPane = new JPanel(new GridBagLayout());
classPane.setBorder(new TitledBorder(null, "Enter Class", TitledBorder.LEADING, TitledBorder.TOP, null, null));
classPane.add(textField);
JPanel actionsPane = new JPanel(new GridBagLayout());
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(1);
}
});
JButton btnOkay = new JButton("Okay");
btnOkay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Text field
System.out.println(textField.getText());
}
});
actionsPane.add(btnOkay);
actionsPane.add(btnCancel);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridwidth = gbc.REMAINDER;
gbc.fill = gbc.HORIZONTAL;
add(enterClassPane, gbc);
add(new JScrollPane(panelCheckBox), gbc);
add(classPane, gbc);
add(actionsPane, gbc);
}
}
public class WrapLayout extends FlowLayout {
private Dimension preferredLayoutSize;
/**
* Constructs a new <code>WrapLayout</code> with a left alignment and a
* default 5-unit horizontal and vertical gap.
*/
public WrapLayout() {
super();
}
/**
* Constructs a new <code>FlowLayout</code> with the specified alignment
* and a default 5-unit horizontal and vertical gap. The value of the
* alignment argument must be one of <code>WrapLayout</code>,
* <code>WrapLayout</code>, or <code>WrapLayout</code>.
*
* @param align the alignment value
*/
public WrapLayout(int align) {
super(align);
}
/**
* Creates a new flow layout manager with the indicated alignment and
* the indicated horizontal and vertical gaps.
* <p>
* The value of the alignment argument must be one of
* <code>WrapLayout</code>, <code>WrapLayout</code>, or
* <code>WrapLayout</code>.
*
* @param align the alignment value
* @param hgap the horizontal gap between components
* @param vgap the vertical gap between components
*/
public WrapLayout(int align, int hgap, int vgap) {
super(align, hgap, vgap);
}
/**
* Returns the preferred dimensions for this layout given the
* <i>visible</i> components in the specified target container.
*
* @param target the component which needs to be laid out
* @return the preferred dimensions to lay out the subcomponents of the
* specified container
*/
@Override
public Dimension preferredLayoutSize(Container target) {
return layoutSize(target, true);
}
/**
* Returns the minimum dimensions needed to layout the <i>visible</i>
* components contained in the specified target container.
*
* @param target the component which needs to be laid out
* @return the minimum dimensions to lay out the subcomponents of the
* specified container
*/
@Override
public Dimension minimumLayoutSize(Container target) {
Dimension minimum = layoutSize(target, false);
minimum.width -= (getHgap() + 1);
return minimum;
}
/**
* Returns the minimum or preferred dimension needed to layout the
* target container.
*
* @param target target to get layout size for
* @param preferred should preferred size be calculated
* @return the dimension to layout the target container
*/
private Dimension layoutSize(Container target, boolean preferred) {
synchronized (target.getTreeLock()) {
// Each row must fit with the width allocated to the containter.
// When the container width = 0, the preferred width of the container
// has not yet been calculated so lets ask for the maximum.
int targetWidth = target.getSize().width;
Container container = target;
while (container.getSize().width == 0 && container.getParent() != null) {
container = container.getParent();
}
targetWidth = container.getSize().width;
if (targetWidth == 0) {
targetWidth = Integer.MAX_VALUE;
}
int hgap = getHgap();
int vgap = getVgap();
Insets insets = target.getInsets();
int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2);
int maxWidth = targetWidth - horizontalInsetsAndGap;
// Fit components into the allowed width
Dimension dim = new Dimension(0, 0);
int rowWidth = 0;
int rowHeight = 0;
int nmembers = target.getComponentCount();
for (int i = 0; i < nmembers; i++) {
Component m = target.getComponent(i);
if (m.isVisible()) {
Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize();
// Can't add the component to current row. Start a new row.
if (rowWidth + d.width > maxWidth) {
addRow(dim, rowWidth, rowHeight);
rowWidth = 0;
rowHeight = 0;
}
// Add a horizontal gap for all components after the first
if (rowWidth != 0) {
rowWidth += hgap;
}
rowWidth += d.width;
rowHeight = Math.max(rowHeight, d.height);
}
}
addRow(dim, rowWidth, rowHeight);
dim.width += horizontalInsetsAndGap;
dim.height += insets.top + insets.bottom + vgap * 2;
// When using a scroll pane or the DecoratedLookAndFeel we need to
// make sure the preferred size is less than the size of the
// target containter so shrinking the container size works
// correctly. Removing the horizontal gap is an easy way to do this.
Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target);
if (scrollPane != null && target.isValid()) {
dim.width -= (hgap + 1);
}
return dim;
}
}
/*
* A new row has been completed. Use the dimensions of this row
* to update the preferred size for the container.
*
* @param dim update the width and height when appropriate
* @param rowWidth the width of the row to add
* @param rowHeight the height of the row to add
*/
private void addRow(Dimension dim, int rowWidth, int rowHeight) {
dim.width = Math.max(dim.width, rowWidth);
if (dim.height > 0) {
dim.height += getVgap();
}
dim.height += rowHeight;
}
}
}
Actually I want this selected checkbox while I click OKAY Button
You have a number of possible options. One might be to simply add or remove the "action command" of the checkbox from some kind of List
For example...
checkBoxList[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("You clicked " + e.getActionCommand());
if (e.getSource() instanceof JCheckBox) {
JCheckBox cb = (JCheckBox) e.getSource();
if (cb.isSelected()) {
selectedValues.add(cb.getActionCommand());
} else {
selectedValues.remove(cb.getActionCommand());
}
}
}
});
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Set;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Set<String> selectedValues = new HashSet<>(8);
public TestPane() {
setBorder(new EmptyBorder(16, 16, 16, 16));
setLayout(new GridBagLayout());
JTextField textField = new JTextField(40);
JRadioButton yes = new JRadioButton("yes");
yes.setSelected(true);
yes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (yes.isSelected()) {
textField.setEnabled(true);
}
}
});
JRadioButton no = new JRadioButton("No");
no.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (no.isSelected()) {
textField.setEnabled(false);
}
}
});
ButtonGroup bg = new ButtonGroup();
bg.add(yes);
bg.add(no);
JPanel enterClassPane = new JPanel(new GridBagLayout());
enterClassPane.setBorder(new TitledBorder(null, "Enetr the class", TitledBorder.LEADING, TitledBorder.TOP, null, null));
enterClassPane.add(yes);
enterClassPane.add(no);
JPanel panelCheckBox = new JPanel(new WrapLayout(WrapLayout.LEADING));
int numberCheckBox = 10;
JCheckBox[] checkBoxList = new JCheckBox[numberCheckBox];
for (int i = 0; i < numberCheckBox; i++) {
checkBoxList[i] = new JCheckBox("CheckBox" + i);
panelCheckBox.add(checkBoxList[i]);
checkBoxList[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("You clicked " + e.getActionCommand());
if (e.getSource() instanceof JCheckBox) {
JCheckBox cb = (JCheckBox) e.getSource();
if (cb.isSelected()) {
selectedValues.add(cb.getActionCommand());
} else {
selectedValues.remove(cb.getActionCommand());
}
}
}
});
}
JPanel classPane = new JPanel(new GridBagLayout());
classPane.setBorder(new TitledBorder(null, "Enter Class", TitledBorder.LEADING, TitledBorder.TOP, null, null));
classPane.add(textField);
JPanel actionsPane = new JPanel(new GridBagLayout());
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(1);
}
});
JButton btnOkay = new JButton("Okay");
btnOkay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Text field
System.out.println(textField.getText());
for (String command : selectedValues) {
System.out.println(command);
}
}
});
actionsPane.add(btnOkay);
actionsPane.add(btnCancel);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridwidth = gbc.REMAINDER;
gbc.fill = gbc.HORIZONTAL;
add(enterClassPane, gbc);
add(new JScrollPane(panelCheckBox), gbc);
add(classPane, gbc);
add(actionsPane, gbc);
}
}
public class WrapLayout extends FlowLayout {
private Dimension preferredLayoutSize;
/**
* Constructs a new <code>WrapLayout</code> with a left alignment and a
* default 5-unit horizontal and vertical gap.
*/
public WrapLayout() {
super();
}
/**
* Constructs a new <code>FlowLayout</code> with the specified alignment
* and a default 5-unit horizontal and vertical gap. The value of the
* alignment argument must be one of <code>WrapLayout</code>,
* <code>WrapLayout</code>, or <code>WrapLayout</code>.
*
* @param align the alignment value
*/
public WrapLayout(int align) {
super(align);
}
/**
* Creates a new flow layout manager with the indicated alignment and
* the indicated horizontal and vertical gaps.
* <p>
* The value of the alignment argument must be one of
* <code>WrapLayout</code>, <code>WrapLayout</code>, or
* <code>WrapLayout</code>.
*
* @param align the alignment value
* @param hgap the horizontal gap between components
* @param vgap the vertical gap between components
*/
public WrapLayout(int align, int hgap, int vgap) {
super(align, hgap, vgap);
}
/**
* Returns the preferred dimensions for this layout given the
* <i>visible</i> components in the specified target container.
*
* @param target the component which needs to be laid out
* @return the preferred dimensions to lay out the subcomponents of the
* specified container
*/
@Override
public Dimension preferredLayoutSize(Container target) {
return layoutSize(target, true);
}
/**
* Returns the minimum dimensions needed to layout the <i>visible</i>
* components contained in the specified target container.
*
* @param target the component which needs to be laid out
* @return the minimum dimensions to lay out the subcomponents of the
* specified container
*/
@Override
public Dimension minimumLayoutSize(Container target) {
Dimension minimum = layoutSize(target, false);
minimum.width -= (getHgap() + 1);
return minimum;
}
/**
* Returns the minimum or preferred dimension needed to layout the
* target container.
*
* @param target target to get layout size for
* @param preferred should preferred size be calculated
* @return the dimension to layout the target container
*/
private Dimension layoutSize(Container target, boolean preferred) {
synchronized (target.getTreeLock()) {
// Each row must fit with the width allocated to the containter.
// When the container width = 0, the preferred width of the container
// has not yet been calculated so lets ask for the maximum.
int targetWidth = target.getSize().width;
Container container = target;
while (container.getSize().width == 0 && container.getParent() != null) {
container = container.getParent();
}
targetWidth = container.getSize().width;
if (targetWidth == 0) {
targetWidth = Integer.MAX_VALUE;
}
int hgap = getHgap();
int vgap = getVgap();
Insets insets = target.getInsets();
int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2);
int maxWidth = targetWidth - horizontalInsetsAndGap;
// Fit components into the allowed width
Dimension dim = new Dimension(0, 0);
int rowWidth = 0;
int rowHeight = 0;
int nmembers = target.getComponentCount();
for (int i = 0; i < nmembers; i++) {
Component m = target.getComponent(i);
if (m.isVisible()) {
Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize();
// Can't add the component to current row. Start a new row.
if (rowWidth + d.width > maxWidth) {
addRow(dim, rowWidth, rowHeight);
rowWidth = 0;
rowHeight = 0;
}
// Add a horizontal gap for all components after the first
if (rowWidth != 0) {
rowWidth += hgap;
}
rowWidth += d.width;
rowHeight = Math.max(rowHeight, d.height);
}
}
addRow(dim, rowWidth, rowHeight);
dim.width += horizontalInsetsAndGap;
dim.height += insets.top + insets.bottom + vgap * 2;
// When using a scroll pane or the DecoratedLookAndFeel we need to
// make sure the preferred size is less than the size of the
// target containter so shrinking the container size works
// correctly. Removing the horizontal gap is an easy way to do this.
Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target);
if (scrollPane != null && target.isValid()) {
dim.width -= (hgap + 1);
}
return dim;
}
}
/*
* A new row has been completed. Use the dimensions of this row
* to update the preferred size for the container.
*
* @param dim update the width and height when appropriate
* @param rowWidth the width of the row to add
* @param rowHeight the height of the row to add
*/
private void addRow(Dimension dim, int rowWidth, int rowHeight) {
dim.width = Math.max(dim.width, rowWidth);
if (dim.height > 0) {
dim.height += getVgap();
}
dim.height += rowHeight;
}
}
}