java窗口设计中, 如何设置多行输入框

2025-03-24 17:56:43
推荐回答(2个)
回答1:

用网格布局写了个简单的例子!~想美观可使用GridBagLayout布局方式。

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class Login extends JFrame implements ActionListener {

private static final long serialVersionUID = -2890322100614715274L;

//文本框
private JTextField jtf = null;
private JPasswordField jpf = null;
private JLabel jl = null;

public Login() {
// TODO Auto-generated constructor stub
//获取容器
Container c = this.getContentPane();
//设置布局方式, 网格布局 3行2列
c.setLayout(new GridLayout(3, 2));

jtf = new JTextField();
jpf = new JPasswordField();

JButton b = new JButton("显示");
// 添加按钮监听
b.addActionListener(this);

jl = new JLabel();

c.add(new JLabel("用户名:"));
c.add(jtf);
c.add(new JLabel("密 码:"));
c.add(jpf);
c.add(b);
c.add(jl);

this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

/**
* 事件监听方法.
*

Title: actionPerformed


*

Description:


* @param e
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
//获取监听 组件的文本
String str = e.getActionCommand();
if("显示".equals(str)) {
jl.setText("用户名是:" + jtf.getText() + "\n密码是:" + new String(jpf.getPassword()));
}

}

public static void main(String[] args) {
new Login();
}

}

回答2:

JLabel + JTextField