hal*_*ike 10 java swing jframe actionlistener gridbaglayout
我有一个JMenuItem用ActionListener,在此ActionListener我要一个添加GridBagLayout到我的frame(这可能会或可能不会有被添加到内容窗格-用于测试目的,并不),然后添加components到frame.frame works它本身的设计,但我希望trigger它来自ActionListener一个JMenuItem,这里是我遇到问题的地方.它不会从内部显示ActionListener.我已尝试从AL中的类中的不同方法运行相同的代码,但这也不起作用.
当我ActionListener完全注释掉时,JLabel我想测试添加到GBL正确的位置,系统prints我的debug线路在这里和here2.没有语法错误compiler.这产生了期望的结果,并且打印了标签.(请参阅下面的图片,了解当我完全注释掉AL时会发生什么.)有问题的代码片段(在哪个帧中是我的JFrame)如下:

// (frame created, menus added, etc.) ...
JMenuItem vPoke1Item = new JMenuItem("Pokemon 1");
vPoke1Item.setActionCommand("poke1");
viewMenu.add(vPoke1Item);
//Setup GBL to view stats for Pokemon 1
vPoke1Item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// debug output
System.out.println("here");
// Set up the content pane
frame.getContentPane().removeAll();
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
Container pane = frame.getContentPane();
pane.setLayout(gbl);
// Make a StatCalcObject (all my labels/fields are already initialized)
StatCalc1 sc1 = new StatCalc1();
// Add it to pane
gbc.gridx = 0;gbc.gridy = 0;gbl.setConstraints(sc1.speciesL, gbc);
pane.add(sc1.speciesL);
frame.revalidate();
frame.repaint();
// debug output
System.out.println("here2");
}
});
// (etc.)
Run Code Online (Sandbox Code Playgroud)
现在,当我运行此代码时,我仍然可以打印调试行"here"和"here2",因此它告诉我ActionListener运行正常.但标签没有出现.仍然没有编译器拾取语法错误.所以我在这里摸不着头脑.我究竟做错了什么?我希望这个代码片段足以理解这个问题,但是如果你想要完整的代码,我可以提供它.
看看调用方法 pane.add(sc1.speciesL); 时发生了什么
接下来调用 Container.add(sc1.speciesL, null, -1)
然后 Container.addImpl( 组件 comp, 对象约束, int index )
然后通过 gbl.setConstraints(sc1.speciesL, gbc); 之前放置的约束 被 null 取代。
if (layoutMgr instanceof LayoutManager2) {
((LayoutManager2)layoutMgr).addLayoutComponent(comp, constraints);
}
Run Code Online (Sandbox Code Playgroud)
然后面板没有显示您新添加的组件,因为 GridBagConstraints 现在为空
而且你实际上不需要强迫
frame.revalidate();
frame.repaint();
frame.pack();
Run Code Online (Sandbox Code Playgroud)
您需要使用正确的方法将新组件正确添加到容器中:
pane.add(sc1.speciesL, gbc);
Run Code Online (Sandbox Code Playgroud)
并删除无用的
gbl.setConstraints(sc1.speciesL, gbc);
Run Code Online (Sandbox Code Playgroud)