Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a separator across a panel using MigLayout

This is a MigLayout-newbie question. I'd like to know how to draw a separator from the end of a label across the width of a panel.

Here's my example code:

package com.ndh.swingjunk;

import java.awt.*;
import javax.swing.*;
import net.miginfocom.swing.MigLayout;

class MyJFrame extends JFrame {
    public MyJFrame() {
        super();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel label = new JLabel("foo");
        label.setFont(new Font("Tahoma", Font.BOLD, 11));
        JSeparator separator = new JSeparator();
        JLabel anotherLabel = new JLabel("some other label");
        anotherLabel.setFont(new Font("Tahoma", Font.PLAIN, 11));
        JButton button1 = new JButton("button 1");
        JButton button2 = new JButton("button 2");
        JPanel panel = new JPanel(new MigLayout());
        panel.add(label);
        panel.add(separator, "growx, wrap");
        panel.add(anotherLabel);
        panel.add(button1);
        panel.add(button2);
        getContentPane().add(panel);
        pack();
    }
}

public class SeparatorLayoutQuestion {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override public void run() {new MyJFrame().setVisible(true);}});}}

and here's the result:

image of messed-up layout

which is terribly lame. I'd like the separator to stretch from the end of "Foo" to the end of the panel, all the way across button 2.

like image 917
Nathan Hughes Avatar asked May 26 '11 16:05

Nathan Hughes


People also ask

How do I add a separator to a swing?

Swing Examples - Add Separator JMenu − To create a menu. JMenuItem − To create a menu item. JMenu. addSeparator(); − To add a separator in the menu.

How do you create a separator in Java?

In JMenu or JPopupMenu addSeparartor function can also be used to create a separator. Constructor of the class are: separator(): Creates a new horizontal separator. JSeparator(int o): Creates a new separator with the specified horizontal or vertical orientation.


2 Answers

Here's what worked for me, I had to use "split" so the label and separator could share the same cell:

JPanel panel = new JPanel(new MigLayout());
panel.add(label, "split 2, span");
panel.add(separator, "growx, wrap");
panel.add(anotherLabel);
panel.add(button1);
panel.add(button2);
like image 174
Nathan Hughes Avatar answered Sep 28 '22 09:09

Nathan Hughes


try adding

 "span 3"

to the first label

like image 20
meverett Avatar answered Sep 28 '22 08:09

meverett