简体   繁体   English

在 Java 中将组件添加到面板

[英]add components to a panel in Java

I'm creating an applet which consists of a class which extends JApplet, with a menubar and a class which extends a JPanel.(So there is a menubar and a JPanel shown in the applet).我正在创建一个小程序,它由一个扩展 JApplet 的 class 和一个菜单栏和一个扩展 JPanel 的 class 组成。(所以小程序中显示了一个菜单栏和一个 JPanel)。

In this class I add and remove some textfields to the JPanel.在这个 class 中,我向 JPanel 添加和删除了一些文本字段。 This all works fine.这一切都很好。 Here's where it gets tricky: it only works the first time.这就是它变得棘手的地方:它只在第一次工作。 When I add some new textfields to the JPanel, they are added and visible in the JPanel, but the menubar in the JFrame stops working.当我向 JPanel 添加一些新的文本字段时,它们会被添加并在 JPanel 中可见,但 JFrame 中的菜单栏停止工作。

Since the code is too extensive I'll only post parts of it.由于代码过于广泛,我将只发布其中的一部分。

Here's the code where I add the JPanel to the JApplet:这是我将 JPanel 添加到 JApplet 的代码:

public class Simulator extends JApplet implements ItemListener, ActionListener {
    Container pane = getContentPane();
    canvas = new DrawCanvas();
    pane.add(canvas, BorderLayout.LINE_END);
}

Here's the code of the JPanel:这是JPanel的代码:

class DrawCanvas extends JPanel {
    public void paintComponent(Graphics g) {
        if(textfield != null)
            remove(textfield);
        textfield = new JTextField();
        this.add(textfield);
    }
}

This works the first time(when nothing is removed), but the second time the menubar stops working.这第一次有效(没有删除任何内容),但第二次菜单栏停止工作。 When I leave out the this.add(textfield);当我省略 this.add(textfield); line, the menubar keeps working.行,菜单栏继续工作。

I believe you are running into issues with threading.我相信您遇到了线程问题。 Adding and removing JComponents during painting might mess up the EDT (which is calling the paint method in the first place).在绘制期间添加和删除 JComponents 可能会弄乱 EDT(它首先调用绘制方法)。

I once had similar problems with popup menus beeing painted behind other components.我曾经在其他组件后面绘制弹出菜单时遇到过类似的问题。 Try calling static JPopupMenu.setDefaultLightWeightPopupEnabled(false);尝试调用 static JPopupMenu.setDefaultLightWeightPopupEnabled(false); or the setLightWeightPopupEnabled on your specific submenu.或特定子菜单上的setLightWeightPopupEnabled This will make (all) popup menus (ie submenus) to heavy weight components that have a native peer.这将使(所有)弹出菜单(即子菜单)成为具有本地对等点的重量级组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM