Klausos Klausos
Klausos Klausos

Reputation: 16050

MigLayout: Resize components relatively to a screen size

I am using MigLayout to align components in the Swing application. I have 2 JPanel components and a toolbar. I want to put toolbar on top and then to put 3 panels next to each other, however their size should be defined in percentages (%) and be relative to a screen size. I know how to align all these components based on fixed size (px), however how can I switch to % relative to screen size?

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);

Upvotes: 0

Views: 2819

Answers (1)

Naruto Biju Mode
Naruto Biju Mode

Reputation: 2091

It's possible to use directly % width inside MigLayout try this example :

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);
    }
}

To fully undestand how to use MigLayout follow this Whitepaper.

Upvotes: 2

Related Questions