How to overlay, resize and centre a component on a JPanel?

穿精又带淫゛_ 提交于 2019-11-30 21:15:43

The preferred size of JProgressBar is specified by the UI delegate, BasicProgressBarUI. The example below illustrates the effect of various layout managers. FlowLayout simply uses the UIManager default, ProgressBar.horizontalSize, while GridLayout and BorderLayout.CENTER fill the available space. BoxLayout, with flanking glue, adjusts proportionally as the frame is resized.

I am already using a SwingWorker

Updating the GUI from the process() method of your SwingWorker should be safe. You can change layers or even remove components, but I'd be wary of anything overly complicated.

Addendum: Here's the relevant default.

System.out.println(UIManager.get("ProgressBar.horizontalSize"));
javax.swing.plaf.DimensionUIResource[width=146,height=12]

Code:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;

/** @see http://stackoverflow.com/questions/7256775 */
public class ProgressTest {

    private static final Color border = Color.gray;

    private static void display() {
        JFrame f = new JFrame("ProgressTest");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(new GridLayout(0, 1));
        f.add(createPanel(new FlowLayout()));
        f.add(createPanel(new GridLayout()));
        f.add(createPanel(new BorderLayout()));

        JPanel p = new JPanel();
        p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
        p.setBorder(BorderFactory.createLineBorder(border));
        JProgressBar jpb = new JProgressBar();
        p.add(Box.createHorizontalGlue());
        p.add(jpb);
        p.add(Box.createHorizontalGlue());
        jpb.setIndeterminate(true);
        f.add(p);

        f.pack();
        f.setSize(320, 240);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private static JPanel createPanel(LayoutManager layout) {
        JPanel p = new JPanel();
        p.setBorder(BorderFactory.createLineBorder(border));
        p.setLayout(layout);
        JProgressBar jpb = new JProgressBar();
        jpb.setIndeterminate(true);
        p.add(jpb);
        return p;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                display();
            }
        });
    }
}
Catalina Island

I know this is a layout question, but SwingWorker might make the problem simpler if you have useful interim results. I sometimes start with this example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!