Swing用户界面组件-1

布局管理器

为容器设置布局管理器:setLayout(LayoutManager m);

将组件添加到容器中,并返回组件的引用:

Component add(Component c)

Component  add(Component c,Object constraints)(要添加的组件,布局管理器理解的标识符)

构造一个新的FlowLayout对象:

FlowLayout()

FlowLayout(int align)

FlowLayout(int align,int hgap,int vgap)

边框布局

BorderLayout()
BorderLayout(int hgap,int vgap)(以像素为单位的水平间距,垂直间距)
构造一个一个新的BorderLayout对象:

JPanel panel = new JPanel();

panel.add(yelloButton);

Panel.add(blueButton);

frame.add(panel,BorderLayout.SOUTH);

网格布局:

在网格布局对象的构造器中,需要制定行数和列数:

panel.setLayout(new GridLayout(5,4));

构造一个新的GridLayout对象,rows或者columns可以为零,但不能同时为零,指定的每行或每列的组件数量可以任意:

GridLayout(int rows,int cols)

GridLayout(int rows,int cols,int hgap,int vgap)(行数,列数,以像素为单位的水平间距,垂直间距)

缩放窗口时,将组件调整到最佳尺寸:   pack()

文本输入:

获取或设置文本组件中的文本:

String getText()

void setText(String text)

获取或设置editable特性,这个特性决定了用户是否可以编辑文本组件中 的内容:

boolean isEditable()

void setEditable(boolean b)

文本域:

JPanel panel = new JPanel();
JTextField textField = new JTextField("Default input",20);//JTextField textField = new JTextField(20)空白文本域
panel.add(textField);

改变文本域的大小:

        textField.setColumns(10);
        panel.revalidate();//冲洗计算组件位置和大小

改变文本域中的内容:

textField.setText("hello!");

将getText方法发挥的文本域中的内容前后空格去掉:

        String text = textField.getText().trim();

改变文本字体用:setFont()

获取组件字体:getFont()

标签和标签组件

右对齐标签:

        JLabel label = new JLabel("User name:",SwingConstants.RIGHT);//或者JLabel.RIGHT

构造一个标签:

JLabel(String text)

JLabel(Icon icon)

JLabel(String text,int align)

JLabel(String text,Icon icon,int align)

获取或设置标签的文本:

String getText()

void setText(String text)

获取或设置标签的图标:

Icon getIcon()

void setIcon(Icon icon)

密码域

构造一个新密码域对象:

JPasswordField(String text,int columns)

为密码域设置回显字符:

void setEchoChar(char echo)

返回密码域中的文本:

char[] getPassword()

文本区

textArea = new JTextArea(8,20);//八行20列

开启换行特性来避免剪裁过长的行:

textArea.setLineWrap(true);

滚动窗格

在文本区插入滚动窗格:

textArea = new JTextArea(8,40);

JScrollPane scrollPane = new JScrollPane(textArea);

原文地址:https://www.cnblogs.com/tt-t/p/5896075.html