I do not know where to add ActionListeners/ItemListener and need help:
This is the desired output:
- If you selected a shape in checkboxes, it will draw a type of shape you selected
- and if you selected radiobutton, it will fill color(maybe a blue color)
here’s the code:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.Border;
public class ARadioCombo {
public static void main(String args[]) {
JFrame frame = new JFrame("Radio/Combo Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(0, 1));
Border border = BorderFactory.createTitledBorder("Fill/Unfill");
panel.setBorder(border);
ButtonGroup group = new ButtonGroup();
JRadioButton aRadioButton = new JRadioButton("Fill Color");
panel.add(aRadioButton);
group.add(aRadioButton);
aRadioButton = new JRadioButton("Remove Fill");
panel.add(aRadioButton);
group.add(aRadioButton);
Container contentPane = frame.getContentPane();
contentPane.add(panel, BorderLayout.WEST);
panel = new JPanel(new GridLayout(0, 1));
border = BorderFactory.createTitledBorder("Select Shape");
panel.setBorder(border);
JCheckBox aCheckBox = new JCheckBox("Oval");
panel.add(aCheckBox);
aCheckBox = new JCheckBox("Square", true);
panel.add(aCheckBox);
aCheckBox = new JCheckBox("Rectangle");
panel.add(aCheckBox);
aCheckBox = new JCheckBox("Circle");
panel.add(aCheckBox);
contentPane.add(panel, BorderLayout.EAST);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
You should add your ActionListeners to any buttons that the user interacts with, here your JRadioButtons. So where you have this:
You could have something like this:
Also, shouldn’t your JCheckBoxes also be JRadioButtons that with the help of a second ButtonGroup object only allow one selection at a time?
Also:
repaint()on the drawing JPanel in the ActionListener actionPerformed, and have the paintComponent method poll the JRadioButtons for their states and in if blocks decide what to draw.