public static void main(String[] args) { // 创建 JFrame 实例 JFrame frame = new JFrame("标题"); // Setting the width and height of frame frame.setSize(1150, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); /* 创建面板,这个类似于 HTML 的 div 标签 * 我们可以创建多个面板并在 JFrame 中指定位置 * 面板中我们可以添加文本字段,按钮及其他组件。 */ JPanel panel = new JPanel(); // 添加面板 frame.add(panel); /* * 调用用户定义的方法并添加组件到面板 */ placeComponents(panel); // 设置界面可见 frame.setVisible(true); } private static void placeComponents(JPanel panel) { /* 布局部分我们这边不多做介绍 * 这边设置布局为 null */ panel.setLayout(null); // 创建 JLabel JLabel userLabel = new JLabel("参数:"); /* 这个方法定义了组件的位置。 * setBounds(x, y, width, height) * x 和 y 指定左上角的新位置,由 width 和 height 指定新的大小。 */ userLabel.setBounds(10,20,100,25); panel.add(userLabel); /* * 创建文本域用于用户输入 */ JTextField userText = new JTextField(20); userText.setBounds(100,20,1000,25); panel.add(userText); /** * 多行 */ //JTextArea area = new JTextArea(); //area.setBounds(200, 20, 300, 300); // panel.add(area); // area.setText("aa bb"); // 输入密码的文本域 JLabel passwordLabel = new JLabel("结果:"); passwordLabel.setBounds(10,50,80,25); panel.add(passwordLabel); JTextField passwordText = new JTextField(20); passwordText.setBounds(100,50,1000,25); panel.add(passwordText); /**这个类似用于输入的文本域 * 但是输入的信息会以点号代替,用于包含密码的安全性 */ /* JPasswordField passwordText = new JPasswordField(20); passwordText.setBounds(100,50,200,50); panel.add(passwordText);*/ // 创建清空按钮 JButton clearButton = new JButton("清空"); clearButton.setBounds(10, 120, 80, 25); clearButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { passwordText.setText(""); userText.setText(""); } }); panel.add(clearButton); JButton inButton = new JButton("button"); inButton.setBounds(10, 80, 80, 25); inButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { //label.setText("按钮被单击了 "+(clicks++)+" 次"); passwordText.setText(""); String qr = userText.getText(); //System.out.println(qr); String doSome = dosomeOfIn(qr); //System.out.println(doSome); passwordText.setText(doSome); } }); panel.add(inButton); }
原文: https://www.runoob.com/w3cnote/java-swing-demo-intro.html