How do I add all of these component in a
JPanel
by using MigLayout
and achieve the rest of the conditions as described in the above picture?
Asked
Active
Viewed 1,679 times
-2

user282606
- 9
- 7
1 Answers
6
Using MigLayout
you can simply add a JSeparator
to the adjacent cell, giving it the growx
property. For instance:
JLabel lblPersonal = new JLabel("Personal");
contentPane.add(lblPersonal, "cell 0 0");
contentPane.add(new JSeparator(), "cell 1 0,growx");
Or, perhaps a nicer way, is to use a border on a panel, while giving the panel a title as such:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import net.miginfocom.swing.MigLayout;
public class TitledPanel extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TitledPanel frame = new TitledPanel();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public TitledPanel() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new MigLayout("", "[grow]", "[grow]"));
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY), "Personal"));
contentPane.add(panel, "cell 0 0,grow");
JLabel lblLabel = new JLabel("Label 1");
panel.add(lblLabel);
textField = new JTextField();
panel.add(textField);
textField.setColumns(10);
pack();
}
}
Now, if you want to create a function that returns such panels when you pass a string parameter, you could extend a JPanel
or create your own class that returns your custom-created JPanel
with the given title label and separator.

David Yee
- 3,515
- 25
- 45
-
+1 but `textField = new JTextField();` plus `textField.setColumns(10);` equals `textField = new JTextField(10);` – mKorbel Jun 11 '14 at 10:31
-
Not sure if this will meet the requirements of the OP, but you could also use `BorderFactory.createTitledBorder(new MatteBorder(1, 0, 0, 0, Color.BLACK), "Title")` – MadProgrammer Jun 11 '14 at 11:42
-
Your code is not the answer. Though you touch my question answer in your comments. – user282606 Jun 11 '14 at 12:58
-
@user282606: What do you miss in his answer? I think he explained very well and even gave you a complete code example. – Thomas Jun 11 '14 at 18:16
-
I think you have to provide a function that will take a string as JSeparator's title and the function will return a JPanel. Probably, you did not read the question that I asked – user282606 Jun 11 '14 at 19:26
-
@user282606 You can easily make such said function yourself with the given information and from the hint I gave you in the last paragraph of my answer. Give it a try first and ask questions if you run into specific problems. – David Yee Jun 11 '14 at 19:42