Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package modeless;
- import java.awt.BorderLayout;
- import java.awt.FlowLayout;
- import java.awt.Window;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.WindowAdapter;
- import java.awt.event.WindowEvent;
- import javax.swing.JButton;
- import javax.swing.JDialog;
- import javax.swing.JFrame;
- import javax.swing.JTextArea;
- import javax.swing.SwingUtilities;
- public class ModelessTest extends JFrame {
- private static int dialogCount = 0;
- private JTextArea taMessages = new JTextArea(10, 0);
- public ModelessTest() {
- setDefaultCloseOperation(EXIT_ON_CLOSE);
- setTitle("Modeless dialogs with callbacks");
- setLayout(new BorderLayout());
- taMessages.setEditable(false);
- add(taMessages, BorderLayout.CENTER);
- JButton btnSpawnModeless = new JButton("Spawn modeless dialog");
- btnSpawnModeless.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- ++dialogCount;
- final String dialogTitle = "Dialog #" + dialogCount;
- DialogCallback callback = new DialogCallback() {
- @Override
- public void ok() {
- taMessages.append("OK: " + dialogTitle + "\n");
- }
- @Override
- public void cancel() {
- taMessages.append("Cancel: " + dialogTitle + "\n");
- }
- };
- MyModelessDialog dialog = new MyModelessDialog(ModelessTest.this, dialogTitle, callback);
- dialog.setVisible(true);
- }
- });
- add(btnSpawnModeless, BorderLayout.SOUTH);
- pack();
- }
- public static void main(String[] args) {
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- new ModelessTest().setVisible(true);
- }
- });
- }
- }
- class MyModelessDialog extends JDialog {
- private final DialogCallback cbk;
- private JButton okButton, cancelButton;
- public MyModelessDialog(Window owner, String title, DialogCallback callback) {
- super(owner, title);
- cbk = callback;
- setModalityType(ModalityType.MODELESS);
- createLayout();
- okButton.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- onOK();
- }
- });
- cancelButton.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- onCancel();
- }
- });
- // Treat closing the dialog the same as pressing "Cancel":
- addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- onCancel();
- }
- });
- }
- private void createLayout() {
- setLayout(new FlowLayout());
- okButton = new JButton("OK");
- add(okButton);
- cancelButton = new JButton("Cancel");
- add(cancelButton);
- pack();
- }
- private void onOK() {
- cbk.ok();
- setVisible(false);
- }
- private void onCancel() {
- cbk.cancel();
- setVisible(false);
- }
- }
- interface DialogCallback {
- void ok();
- void cancel();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement