Re: Problems with ItemEvents
Quote:
Originally Posted by
bgroenks96
How do you use the ItemEvent to simply tell you what is now selected?
I researched this recently and it would seem that the solution is to loop over all buttons to see which is selected. My personal solution was to addan action command to each button. Then call getSelection on the ButtonGroup which returns a ButtonModel. Then call getActionCommand on the Button Model.
Quote:
Also, why is it that JRadioButtonMenuItem inherits the method isSelected from AbstractButton but my compiler says that it can't find the symbol isSelected in class javax.swing.JRadioButtonMenuItem when I try to use it?
Code and full and exact error message or it never happened.
Re: Problems with ItemEvents
Quote:
Originally Posted by
Junky
Code and full and exact error message or it never happened.
Code :
import javax.swing.*;
import java.awt.event.*;
class Test {
JMenu error;
JMenuBar menuBar;
ButtonGroup bg;
JRadioButtonMenuItem one,two;
public void setUp() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
menuBar = new JMenuBar();
error = new JMenu("Error");
bg = new ButtonGroup();
one = new JRadioButtonMenuItem("One");
two = new JRadioButtonMenuItem("Two");
bg.add(one);
bg.add(two);
one.addItemListener(new Listener());
two.addItemListener(new Listener());
error.add(one);
error.add(two);
menuBar.add(error);
frame.setJMenuBar(menuBar);
frame.add(panel);
frame.setSize(600,600);
frame.setVisible(true);
}
class Listener implements ItemListener {
public void itemStateChanged(ItemEvent event) {
if(one.isSelected) {
System.out.println("One");
} else if(two.isSelected) {
System.out.println("Two");
}
}
}
public static void main(String[] args) {
Test t = new Test();
t.setUp();
}
}
Quote:
javac Test.java
Test.java:30: cannot find symbol
symbol : variable isSelected
location: class javax.swing.JRadioButtonMenuItem
if(one.isSelected) {
^
Test.java:32: cannot find symbol
symbol : variable isSelected
location: class javax.swing.JRadioButtonMenuItem
} else if(two.isSelected) {
^
2 errors
Re: Problems with ItemEvents
Look closely at the code where the error points to - isSelected is a method, not a variable. Variables are accessed via myObject.myVariable Methods as myObject.myMethod()
Re: Problems with ItemEvents
Quote:
Originally Posted by
copeg
Look closely at the code where the error points to - isSelected is a method, not a variable. Variables are accessed via myObject.myVariable Methods as myObject.myMethod()
Yeah just realized that.... stupidity isn't a fun feeling. :(
I do that somewhat often. Type in a method and forget the () identifier.
Re: Problems with ItemEvents
Quote:
Originally Posted by
bgroenks96
Yeah just realized that.... stupidity isn't a fun feeling. :(
I do that somewhat often. Type in a method and forget the () identifier.
Not stupidity - its called learning. The thing is, I could readily find the error because I myself have done this countless times through the years.