将JPanel添加到JFrame可以在50%的时间内工作

时间:2017-03-06 13:32:59

标签: java swing netbeans jframe jpanel

以下两张图片展示了我面临的问题。每当我运行项目时,我的JPanels有50/50的可能性正确加载,否则只加载1个JPanel,即使我只是循环遍历数组并将JPanels添加到JFrame。

        viewComponents.forEach(viewComponent -> this.add(viewComponent));

Working

Not working

DashboardView.java

public class DashboardView extends JFrame{
    List<ViewComponent> viewComponents = new ArrayList();
    ViewComponentFactory viewComponentFactory = new ViewComponentFactory();

    JFrame dashboardInput = new JFrame();

    public DashboardView(){
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        this.setLayout(new FlowLayout());

        createGauges(); //Adding 2 JPanels
        viewComponents.forEach(viewComponent -> this.add(viewComponent));

        this.pack();
        this.setLocationRelativeTo(null);
        this.setVisible(true);

        dashboardInput.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        dashboardInput.setLayout(new FlowLayout());
        createInputs(); //Adding JPanels
        dashboardInput.pack();     
        dashboardInput.setLocation(this.getX()+(this.getWidth()/2)-(dashboardInput.getWidth()/2), this.getY()+this.getHeight());
        dashboardInput.setVisible(true);

    }
private void createGauges(){
    viewComponents.add(viewComponentFactory.getViewComponent(ViewComponentFactory.ViewComponentType.RadialCircleGauge,0,800, "Speedometer", "KM/H")); 
    viewComponents.add(viewComponentFactory.getViewComponent(ViewComponentFactory.ViewComponentType.LinearGauge, -100,100, "Temperature", "Celcius"));
}

Main.java

public class Main {

    public static void main(String[] args) {

        DashboardView dashboardView = new DashboardView();
        dashboardView.setVisible(true);
    }
}

1 个答案:

答案 0 :(得分:1)

主要问题似乎是 DashboadView 未在 EDT - 线程(事件调度线程)中初始化。所有GUI操作都必须在此线程内完成。否则会发生奇怪的事情(例如更新UI时的工件)。

应该以这种方式初始化其GUI,以确保开始是正确的线程。

public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}