在Java Swing中,对话框(JDialog)的事件处理通常涉及到以下几个方面:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DialogExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Dialog Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
JButton button = new JButton("Open Dialog");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openDialog(frame);
}
});
frame.getContentPane().add(button, BorderLayout.CENTER);
}
private static void openDialog(JFrame parent) {
JDialog dialog = new JDialog(parent, "My Dialog", true);
dialog.setSize(200, 100);
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("OK button clicked");
dialog.dispose();
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Cancel button clicked");
dialog.dispose();
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(okButton);
buttonPanel.add(cancelButton);
dialog.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
dialog.setLocationRelativeTo(parent);
dialog.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class DialogExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Dialog Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
JButton button = new JButton("Open Dialog");
button.addActionListener(e -> openDialog(frame));
frame.getContentPane().add(button, BorderLayout.CENTER);
}
private static void openDialog(JFrame parent) {
JDialog dialog = new JDialog(parent, "My Dialog", true);
dialog.setSize(200, 100);
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println("Dialog closed");
dialog.dispose();
}
});
JLabel label = new JLabel("This is a dialog");
dialog.getContentPane().add(label, BorderLayout.CENTER);
dialog.setLocationRelativeTo(parent);
dialog.setVisible(true);
}
}
这些示例展示了如何在Java Swing对话框中处理按钮点击和对话框关闭事件。你可以根据自己的需求进行修改和扩展。