如何使用
JPanel
在MigLayout
中添加所有这些组件,并实现上图所述的其他条件?
答案 0 :(得分:6)
使用MigLayout
,您只需向相邻的单元格添加JSeparator
,即可为其提供growx
属性。例如:
JLabel lblPersonal = new JLabel("Personal");
contentPane.add(lblPersonal, "cell 0 0");
contentPane.add(new JSeparator(), "cell 1 0,growx");
或者,也许更好的方法是在面板上使用边框,同时为面板提供标题:
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();
}
}
现在,如果要在传递字符串参数时创建一个返回此类面板的函数,可以扩展JPanel
或创建自己的类,返回自定义创建的JPanel
给出标题标签和分隔符。