使用java swing创建一个包含两个文本框、一个文件选中按钮、一个密码框、一个提交按钮的UI程序,其中第二个文本框的值由点击文件选择按钮后获取到选中文件的绝对路径
时间: 2023-11-27 14:50:11 浏览: 77
JAVA gui swing程序设计
以下是一个简单的Java Swing程序,其中包含两个文本框、一个文件选中按钮、一个密码框和一个提交按钮。点击文件选择按钮后,将获取选中文件的绝对路径,并将其填充到第二个文本框中。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
public class FileChooserExample extends JFrame implements ActionListener {
private JTextField textField1;
private JTextField textField2;
private JPasswordField passwordField;
private JButton fileChooserButton;
private JButton submitButton;
public FileChooserExample() {
super("File Chooser Example");
// Create components
JLabel label1 = new JLabel("Text Field 1:");
textField1 = new JTextField(20);
JLabel label2 = new JLabel("Text Field 2:");
textField2 = new JTextField(20);
passwordField = new JPasswordField(20);
fileChooserButton = new JButton("Choose File");
submitButton = new JButton("Submit");
// Set file chooser button action listener
fileChooserButton.addActionListener(this);
// Set submit button action listener
submitButton.addActionListener(this);
// Create layout
JPanel panel = new JPanel(new GridLayout(4, 2));
panel.add(label1);
panel.add(textField1);
panel.add(label2);
panel.add(textField2);
panel.add(new JLabel("Password:"));
panel.add(passwordField);
panel.add(fileChooserButton);
panel.add(submitButton);
// Set window properties
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(panel);
pack();
setVisible(true);
}
// Handle button clicks
public void actionPerformed(ActionEvent e) {
if (e.getSource() == fileChooserButton) {
// Show file chooser dialog
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
// Get selected file and set text field value
File selectedFile = fileChooser.getSelectedFile();
textField2.setText(selectedFile.getAbsolutePath());
}
} else if (e.getSource() == submitButton) {
// Handle submit button click
String value1 = textField1.getText();
String value2 = textField2.getText();
char[] password = passwordField.getPassword();
// Do something with the values and password
System.out.println("Value 1: " + value1);
System.out.println("Value 2: " + value2);
System.out.println("Password: " + new String(password));
}
}
public static void main(String[] args) {
new FileChooserExample();
}
}
```
阅读全文