SwingUtilities.getRoot() in a javax.swing.Action

R

RedGrittyBrick

After reading
http://www.exampledepot.com/egs/javax.swing/frame_FrameFind.html

I wrote a small test program in which I found that
SwingUtilities.getRoot() returns null. getRoot() works well for me in
other programs when I feed it a container (e.g. JPanel).

What am I doing wrong? Cannot SwingUtilities trace the JFrame to which
the JMenuItems are ultimately attached? Why not?

------------------------------------8<-------------------------------
import java.awt.Component;
import java.awt.event.ActionEvent;
import javax.swing.*;

public class EnumAction {

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new EnumAction();
}
});
}

EnumAction() {
JMenu m = new JMenu("Menu");
for (Command c : Command.values())
m.add(new JMenuItem(c.action));
JMenuBar mb = new JMenuBar();
mb.add(m);

JPanel p = new JPanel();
p.add(new JLabel("EnumAction"));

JFrame f = new JFrame("EnumAction");
f.setJMenuBar(mb);
f.add(p);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
}

enum Command {
CMD_THIS("This"), CMD_THAT("That");
Action action;

Command(final String label) {
action = new AbstractAction() {
{
putValue(Action.ACTION_COMMAND_KEY, name());
putValue(Action.NAME, label);
}
public void actionPerformed(ActionEvent event) {
System.out.println(event.getActionCommand());
Object o = event.getSource();
if (o instanceof JMenuItem) {
Component c = SwingUtilities.getRoot((JMenuItem)o);
System.out.println("Root: "+c);
}
}

};
}
}
------------------------------------8<-------------------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top