Java 如何在Jpanel中的JLabel旁边添加JSepator?
如何使用Java 如何在Jpanel中的JLabel旁边添加JSepator?,java,swing,layout,miglayout,Java,Swing,Layout,Miglayout,如何使用MigLayout将所有这些组件添加到JPanel中,并实现上图所述的其余条件?使用MigLayout您只需将jsepator添加到相邻单元格中,并赋予其growx属性即可。例如: JLabel lblPersonal = new JLabel("Personal"); contentPane.add(lblPersonal, "cell 0 0"); contentPane.add(new JSeparator(), "cell 1 0,growx"); 或者,也许更好的方法是在面
MigLayout
将所有这些组件添加到JPanel
中,并实现上图所述的其余条件?使用MigLayout
您只需将jsepator
添加到相邻单元格中,并赋予其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
。+1但textField=new JTextField()
plustextField.setColumns(10)代码>等于textField=新的JTextField(10)代码>不确定这是否符合OP的要求,但您也可以使用BorderFactory.createTitleBorder(新的MatteBorder(1,0,0,Color.BLACK),“Title”)
您的代码不是答案。尽管你在评论中触及了我的问题答案。@user28606:你在他的答案中遗漏了什么?我认为他解释得很好,甚至给了你一个完整的代码示例。我认为你必须提供一个函数,该函数将字符串作为JSepator的标题,并且该函数将返回一个JPanel。也许你没有读过我问的问题