javaGUI可以自定义对话框吗,请举一个例子
时间: 2024-01-11 17:42:33 浏览: 90
是的,Java GUI可以自定义对话框。下面是一个简单的例子,演示如何创建一个自定义对话框:
```java
import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CustomDialog extends JDialog implements ActionListener {
private JTextField textField;
public CustomDialog(Frame parent) {
super(parent, "Custom Dialog", true);
JPanel panel = new JPanel(new GridLayout(2, 1));
JLabel label = new JLabel("Enter some text:");
panel.add(label);
textField = new JTextField();
panel.add(textField);
getContentPane().add(panel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
JButton okButton = new JButton("OK");
okButton.addActionListener(this);
buttonPanel.add(okButton);
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
buttonPanel.add(cancelButton);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(parent);
}
public void actionPerformed(ActionEvent e) {
if ("OK".equals(e.getActionCommand())) {
dispose();
} else if ("Cancel".equals(e.getActionCommand())) {
textField.setText("");
}
}
public String getText() {
return textField.getText();
}
public static void main(String[] args) {
Frame frame = new Frame();
CustomDialog dialog = new CustomDialog(frame);
dialog.setVisible(true);
System.out.println(dialog.getText());
}
}
```
这个自定义对话框包含一个文本框和两个按钮:OK和Cancel。当用户单击OK按钮时,对话框将关闭。当用户单击Cancel按钮时,文本框将被清空。在main方法中,我们创建一个CustomDialog实例并显示它。当对话框关闭时,我们打印出用户输入的文本。
阅读全文