MigLayout:相对于屏幕大小调整组件大小

时间:2016-01-30 10:05:14

标签: java swing

我正在使用MigLayout来对齐Swing应用程序中的组件。我有2个JPanel组件和一个工具栏。我想将工具栏放在顶部,然后将3个面板放在一起,但是它们的大小应该以百分比(%)定义,并且相对于屏幕大小。 我知道如何根据固定大小(px)对齐所有这些组件,但是如何切换到相对于屏幕大小的%?

JPanel contentPanel = new JPanel();
contentPanel.setBorder(BorderFactory.createEmptyBorder(0, 4, 4, 4));        
contentPanel.setLayout(new MigLayout("fillx,insets 1")); 
JScrollPane westPanel = new JScrollPane(createParametersPanel());
JScrollPane eastPanel = new JScrollPane(createPanel());        
JEditorPane editor = new JEditorPane("text/plain", "Hello World");
contentPanel.add(toolbar,"wrap");
contentPanel.add(westPanel,"width :200:");
contentPanel.add(editor,"width :200:");
contentPanel.add(eastPanel,"width :400:");
setContentPane(contentPanel);

1 个答案:

答案 0 :(得分:2)

可以在MigLayout内直接使用%width尝试此示例:

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import net.miginfocom.swing.MigLayout;

public class Main
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(100, 100, 500, 500);

        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new MigLayout("insets 4 4 4 4",
                "[fill,30%][fill,40%][fill,30%]", "[fill,grow]"));

        JMenuBar menubar = new JMenuBar();
        JMenu menu = new JMenu("File");
        JMenuItem item = new JMenuItem("Open");
        menu.add(item);
        menubar.add(menu);
        frame.setJMenuBar(menubar);

        contentPanel.add(new JScrollPane());
        contentPanel.add(new JScrollPane(new JEditorPane("text/plain", "Hello World")));
        contentPanel.add(new JScrollPane());
        frame.setContentPane(contentPanel);
        frame.setVisible(true);
    }
}

要完全找不到如何使用MigLayout,请按照此Whitepaper