[英]How should I use ActionItemListener on JRadiobutton?
I am trying to code very simple Java program - if the shape is fill and click on particular button is made than the message will popup. 我正在尝试编写非常简单的Java程序-如果填充形状并单击特定按钮,则消息将弹出。 On the other hand, if the fill is not selected it will show different messages. 另一方面,如果未选择填充,它将显示不同的消息。
fill.addItemListener(new ItemListener());
rect.addActionListener(new ButtonListener());
And the action event I have written is: 我写的动作事件是:
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==fill) {
if(e.getSource()==rect) {
JOptionPane.showMessageDialog(null,"Shojibur");
}
else {
JOptionPane.showMessageDialog(null,"Checking");
}
}
}
}
In your case you don't need the ItemListener
for the JRadioButton
. 在您的情况下,您不需要JRadioButton
的ItemListener
。 On button click you can check if the radio button is selected or not using 在按钮上单击,您可以检查是否选择了单选按钮
radioButton.isSelected() radioButton.isSelected()
and then show appropriate messages. 然后显示适当的消息。
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
@SuppressWarnings("serial")
public class RadioButtonTest extends JFrame implements ActionListener
{
private JRadioButton radio;
private JButton button;
public RadioButtonTest()
{
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new BorderLayout());
radio = new JRadioButton("Select Me!!");
button = new JButton("Click Me!!");
button.addActionListener(this);
add(radio, BorderLayout.CENTER);
add(button, BorderLayout.PAGE_END);
pack();
setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
new RadioButtonTest();
}
});
}
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == button)
{
if (radio.isSelected())
JOptionPane.showMessageDialog(this, "Selected.");
else
JOptionPane.showMessageDialog(this, "NOT selected!!");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.