我不知道在哪里添加ActionListeners / ItemListener并需要帮助:
这是所需的输出:
这是代码:
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);
}
}
答案 0 :(得分:3)
您应该将ActionListeners添加到用户与之交互的任何按钮,这里是您的JRadioButtons。所以你有这个:
JRadioButton aRadioButton = new JRadioButton("Fill Color");
panel.add(aRadioButton);
group.add(aRadioButton);
aRadioButton = new JRadioButton("Remove Fill");
panel.add(aRadioButton);
group.add(aRadioButton);
你可以这样:
ActionListener myActionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO: put in code I want to have happen on button selection
// One ActionListener can likely be used for all buttons in this
// small program.
// as noted below, it could be as simple as one line saying:
// repaint();
}
};
JRadioButton aRadioButton = new JRadioButton("Fill Color");
panel.add(aRadioButton);
group.add(aRadioButton);
aRadioButton.addActionListener(myActionListener);
aRadioButton = new JRadioButton("Remove Fill");
panel.add(aRadioButton);
group.add(aRadioButton);
aRadioButton.addActionListener(myActionListener); // add to each radiobutton object
另外,你的JCheckBox也不应该是JRadioButtons,在第二个ButtonGroup对象的帮助下,一次只允许一个选择吗?
此外:
repaint()
,并让paintComponent方法轮询JRadioButtons的状态,以及if块决定要绘制的内容。