在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對話框中處理按鈕點擊和對話框關閉事件。你可以根據自己的需求進行修改和擴展。