这是我的问题的完全可验证的最小例子,我相信并希望。 如果使用从initialize()方法直接添加的DefaultMutableTreeNode创建的JTree正确添加了我(行注释代码)。但是,如果我尝试使用ActionPerformed方法来操作按钮,则不会出现JTree。
public class Window {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Window() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.getContentPane().add(menuBar, BorderLayout.NORTH);
JMenu mnAbrir = new JMenu("Open");
menuBar.add(mnAbrir);
JMenuItem mntmAbrirXml = new JMenuItem("Open JTree");
mntmAbrirXml.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DefaultMutableTreeNode mutable = new DefaultMutableTreeNode();
JTree tree = new JTree(mutable);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(tree);
frame.getContentPane().add(panel, BorderLayout.CENTER);
//System.out.println("Is into ActionPerformed");
}
});
mnAbrir.add(mntmAbrirXml);
//JTree treeOut = new JTree(new DefaultMutableTreeNode());
//frame.getContentPane().add(treeOut, BorderLayout.CENTER);
}
}
再次感谢Topo。
答案 0 :(得分:0)
不知道为什么,但必须在主框架ActionPerformed中显示。这是缺少的代码行(在actionPerformed中):
frame.setVisible(true);