java - 实时向 JFrame 添加多个 JPanel

标签 java swing

我正在编写一个工具,用于在文本文件上执行任务。该任务需要一些时间才能执行,因此我制作了一个面板来显示文件名和进度百分比。 用户可以在一个或多个文件上运行该任务,因此我需要为每个文件显示一个面板。问题是没有添加面板。 我正在将我的代码更新为独立的,如下所示:

package sscce.jpanel;

import javax.swing.JFrame;
import javax.swing.JTextArea;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class FProgressDisplay extends JFrame {
    private final static Logger LOGGER = Logger.getLogger(FProgressDisplay.class.getName());
    private List<PanelTaskProgress> tasks;
    JTextArea txtLog;
    JButton btnAbort;
    JButton btnClose;


    public static void main(String[] args) {
        try {
            FProgressDisplay frame = new FProgressDisplay();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);

            for(int i = 0; i < 10; i++) {
                frame.addTask(i, "Task"+i);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to initialize application.");
        }
    }
    /**
     * Create the frame.
     */
    public FProgressDisplay() {
        setTitle("Mask tool - Progress");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        getContentPane().setLayout(null);
        getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

        JPanel panel = new JPanel();
        getContentPane().add(panel);

        btnAbort = new JButton("Abort");
        panel.add(btnAbort);

        btnClose = new JButton("Close");
        panel.add(btnClose);

        txtLog = new JTextArea();
        txtLog.setLineWrap(true);
        getContentPane().add(txtLog);

        tasks = new ArrayList<PanelTaskProgress>();
    }

    public void addTask(long id, String fileName) {
        PanelTaskProgress newTaskPanel = new PanelTaskProgress(id, fileName);
        tasks.add(newTaskPanel);
        getContentPane().add(newTaskPanel);
        validate();
        repaint();
        LOGGER.info("Added new panel");
    }

    public class PanelTaskProgress extends JPanel {
        private static final long serialVersionUID = 1L;
        JLabel lblTaskDescription;
        JLabel lblProgress;
        private long id;
        /**
         * Create the panel.
         */
        public PanelTaskProgress(long id, String fileName) {
            try {
                setLayout(null);

                lblTaskDescription = new JLabel(id + " " + fileName);
                //lblTaskDescription.setBounds(10, 11, 632, 14);
                add(lblTaskDescription);

                lblProgress = new JLabel("0%");
                lblProgress.setHorizontalAlignment(SwingConstants.CENTER);
                //lblProgress.setBounds(664, 11, 51, 14);
                add(lblProgress);

                LOGGER.info("Created new panel; Id: " + id + "; File: " + fileName);
            } catch (Exception e) {
                LOGGER.severe("Error creating new panel; " + e.getMessage());
            }
        }
    }
}

最佳答案

调用validate(),然后调用repaint()

<小时/>

这是您的 SSCCE 的黑客版本。不确定最终的要求是什么,但我添加了一个按钮,允许在 GUI 可见后添加新任务。似乎不需要 repaint() 调用,所以我将其编辑掉。

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.util.logging.Logger;

public class FProgressDisplay extends JFrame {
    private final static Logger LOGGER = Logger.getLogger(FProgressDisplay.class.getName());
    private List<PanelTaskProgress> tasks;
    JTextArea txtLog;
    JButton btnNew;
    JButton btnAbort;
    JButton btnClose;
    static int i;
    JPanel taskPanel;

    public static void main(String[] args) {
        try {
            FProgressDisplay frame = new FProgressDisplay();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to initialize application.");
        }
    }
    /**
     * Create the frame.
     */
    public FProgressDisplay() {
        setTitle("Mask tool - Progress");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // should be done AFTER components are added
        //pack();
        getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
        taskPanel = new JPanel();
        taskPanel.setLayout(new BoxLayout(taskPanel, BoxLayout.Y_AXIS));

        JPanel panel = new JPanel();
        getContentPane().add(panel);

        btnNew = new JButton("New");
        panel.add(btnNew);
        btnNew.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                addTask(++i, "Task " + i);
            }
        });

        btnAbort = new JButton("Abort");
        panel.add(btnAbort);

        btnClose = new JButton("Close");
        panel.add(btnClose);

        txtLog = new JTextArea();
        txtLog.setLineWrap(true);
        getContentPane().add(txtLog);

        tasks = new ArrayList<PanelTaskProgress>();

        JScrollPane scrollPane = new JScrollPane(taskPanel);
        getContentPane().add(scrollPane);

        for(i = 0; i < 10; i++) {
            addTask(i, "Task"+i);
        }
        pack();
    }

    public void addTask(long id, String fileName) {
        PanelTaskProgress newTaskPanel = new PanelTaskProgress(id, fileName);
        tasks.add(newTaskPanel);
        taskPanel.add(newTaskPanel);
        validate();
        //repaint();
        LOGGER.info("Added new panel");
    }

    public class PanelTaskProgress extends JPanel {
        private static final long serialVersionUID = 1L;
        JLabel lblTaskDescription;
        JLabel lblProgress;
        private long id;
        /**
         * Create the panel.
         */
        public PanelTaskProgress(long id, String fileName) {
            try {
                //setLayout(null);

                lblTaskDescription = new JLabel(id + " " + fileName);
                //lblTaskDescription.setPreferredSize(new Dimension(632, 14));
                add(lblTaskDescription);

                lblProgress = new JLabel("0%");
                lblProgress.setHorizontalAlignment(SwingConstants.CENTER);
                //lblProgress.setBounds(664, 11, 51, 14);
                add(lblProgress);

                LOGGER.info("Created new panel; Id: " + id + "; File: " + fileName);
            } catch (Exception e) {
                LOGGER.severe("Error creating new panel; " + e.getMessage());
            }
        }
    }
}

关于java - 实时向 JFrame 添加多个 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7804959/

相关文章:

java - 迭代器删除与 ArrayList 删除之间的区别?

Java命令在docker容器中不起作用

java - 按键事件不会触发

java - 这个 Swing 代码是如何工作的?

java - CardLayout 更新信息时删除旧面板

java - 使用 Apache POI 获取行数

java - 如何在java swing中自动扩展框架的高度

java - JButtons 未显示在 JFrame 上的 JPanel 上

java - 无法在Eclipse中运行build.gradle

java - gui 帮助...使用 actionListener