关闭 JFrame 时执行操作

发布于 2024-11-03 04:05:29 字数 1245 浏览 5 评论 0原文

在我的程序中,我有一个包含按钮的主 JFrame。单击此按钮时,会出现一个新的 JFrame,我可以在其中更改一些信息。每当我完成编辑时,我都会按新 JFrame 上的保存按钮,该按钮将保存更改并处置 JFrame。现在,完成此操作后,我还想在主 JFrame 中执行一个操作,但前提是某些内容发生了变化。如果我打开新的 JFrame 并在不使用保存按钮的情况下再次关闭它,我不想在主框架中执行任何操作。 我尝试在网上搜索解决方案,但似乎没有任何有用的东西。

到目前为止我得到的代码示例: 主框架...


public class MainFrame extends JFrame
 {
     public MainFrame()
     {
         super("Main Frame");
         JButton details = new JButton("Add Detail");
         add(details);
         details.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e)
             {
                 new DetailFrame().setVisible(true);
             }
         });
     }
 }

细节框架...


 public class DetailFrame extends JFrame
 {
     public DetailFrame()
     {
         super("Detail Frame");
         JButton save = new JButton("Save");
         add(save);
         save.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e)
             {
                 // Save whatever content
                 dispose();
             }
         });
     }
 }

因此,当我单击细节框架上的“保存”按钮时,我想在主框架中执行某些操作,而当单击细节框架上的“x”时,我不想这样做不想做任何事..

希望有人能够帮助我,并对我的英语感到抱歉..

In my program I have a main JFrame that holds a button. When this button is clicked a new JFrame appears in which I can change some information. Whenever I finish editing I press a save button on the new JFrame which saves the changes and disposes the JFrame. Now when this is done, I'd like to perform an action in the main JFrame as well, but only if something changed. If I open the new JFrame and just close it again without using the save button, I don't want to do anything in the main frame.
I've tried searching the web for a solution, but just don't seem to be anything useful out there..

An example of the code I've got so far:
Main Frame...


public class MainFrame extends JFrame
 {
     public MainFrame()
     {
         super("Main Frame");
         JButton details = new JButton("Add Detail");
         add(details);
         details.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e)
             {
                 new DetailFrame().setVisible(true);
             }
         });
     }
 }

Detail Frame...


 public class DetailFrame extends JFrame
 {
     public DetailFrame()
     {
         super("Detail Frame");
         JButton save = new JButton("Save");
         add(save);
         save.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e)
             {
                 // Save whatever content
                 dispose();
             }
         });
     }
 }

So when I click the "Save" button on the Detail Frame, I want to do something in the Main Frame, whereas when the "x" is clicked on the Detail Frame, I don't want to do anything..

Hope someone is able to help me, and sorry for my english..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

如梦亦如幻 2024-11-10 04:05:29

您可以将 MainFrame 句柄传递给 DetailFrame 构造函数。然后,单击“保存”按钮后,DetailFrame 将调用 MainFrame 中的函数并将更改传递给它。

另一种方法是在 DetailFrame 中创建一个 public boolean 变量,并在单击“保存”按钮时将其设置为 true。这样 MainFrame 将知道 DetailFrame 是否已关闭或已保存。

编辑:更多想法:

使用JDialog而不是JFrameJDialog.setVisible 是模态的,即它将阻塞调用函数直到对话框关闭;这样您就可以在同一个“详细信息”按钮侦听器中处理对话框的结果。

要在调用对话框后访问该对话框,请将对话框存储在单独的变量中。首先构造对话框,然后显示它,然后通过分析其变量来处理结果。

将编辑结果存储在 DetailFrame(或者我们称之为 DetailDialog)的其他公共变量中。仅当单击“保存”按钮时才会发生这种情况。这甚至可以允许不使用布尔变量(取决于您正在编辑的值的类型)。

DetailDialog dlg = new DetailDialog();
dlg.setVisible(true);
if(dlg.approvedResult != null) {
    // process the result...
}

编辑:抱歉,JDialog默认情况下不是模态的。需要调用一个特殊的 super 构造函数来使其成为模态。

另外,在这里您必须将对 MainFrame 的引用传递给对话框构造函数,但您仍然可以将其声明为简单的 JFrame 并避免不必要的依赖关系。

要从匿名 ActionListener 中获取对封闭 MainFrame 的引用,请使用 MainFrame.this

为了能够在创建后更改按钮文本,您必须将按钮存储在成员变量中。

主框架...

public class MainFrame extends JFrame
{
    private JButton details = new JButton("Add Detail");

    public MainFrame()
    {
        super("Main Frame");
        getContentPane().add(details);
        details.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                DetailDialog dlg = new DetailDialog(MainFrame.this);
                dlg.setVisible(true);
                if(dlg.approved){
                    details.setText("Edit Detail");
                }
            }
        });
    }
}

详细对话框...(不是框架)

public class DetailDialog extends JDialog
{
    public boolean approved = false;

    public DetailDialog(JFrame parent)
    {
        super(parent,"Detail Dialog",true);        // modal dialog parented to the calling frame
        JButton save = new JButton("Save");
        getContentPane().add(save);
        save.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                // Save whatever content
                approved = true;
                dispose();
            }
        });
    }
}

You can pass a MainFrame handle to the DetailFrame constructor. Then, on clicking the Save button, the DetailFrame would call a function in MainFrame and pass the changes to it.

Another way is to create a public boolean variable in DetailFrame and set it to true when the Save button is clicked. This way MainFrame will know whether the DetailFrame was closed or Save'd.

EDIT: Some more ideas:

Use JDialog instead of JFrame. JDialog.setVisible is modal, i.e. it will block the calling function until the dialog is closed; this way you can process the results of the dialog in the same "Details" button listener.

To access the dialog after it is called, store the dialog in a separate variable. First construct the dialog, then show it, and then process the result by analyzing its variables.

Store the results of editing in other public variables of DetailFrame (or let's call it DetailDialog). This should happen only when the "Save" button is clicked. This may even allow to go without the boolean variable (depends on the types of values you are editing).

DetailDialog dlg = new DetailDialog();
dlg.setVisible(true);
if(dlg.approvedResult != null) {
    // process the result...
}

EDIT: Sorry, JDialog is not modal by default. Need to call a special super constructor to make it modal.

Also, here you will have to pass the reference to MainFrame to the dialog constructor, but you still can declare it as a simple JFrame and avoid unnecessary dependencies.

To get the reference to the enclosing MainFrame from within the anonymous ActionListener, use MainFrame.this.

To be able to change the button text after it was created, you will have to store the button in a member variable.

Main Frame...

public class MainFrame extends JFrame
{
    private JButton details = new JButton("Add Detail");

    public MainFrame()
    {
        super("Main Frame");
        getContentPane().add(details);
        details.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                DetailDialog dlg = new DetailDialog(MainFrame.this);
                dlg.setVisible(true);
                if(dlg.approved){
                    details.setText("Edit Detail");
                }
            }
        });
    }
}

Detail Dialog... (not Frame)

public class DetailDialog extends JDialog
{
    public boolean approved = false;

    public DetailDialog(JFrame parent)
    {
        super(parent,"Detail Dialog",true);        // modal dialog parented to the calling frame
        JButton save = new JButton("Save");
        getContentPane().add(save);
        save.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                // Save whatever content
                approved = true;
                dispose();
            }
        });
    }
}
碍人泪离人颜 2024-11-10 04:05:29

在主框架中创建细节框架,并使用 windowadapter 类向其中添加一个窗口侦听器。通过检查更改来实现窗口关闭事件,处理这些更改,然后处理详细信息框架。这一切都是在大型机中完成的。

细节框架不应在关闭集上执行任何操作,以防止细节框架在记录更改之前被处置。

您可能希望将详细框架中的更改检查作为返回保存感兴趣数据的类的方法来实现。这样你的窗口侦听器就可以很小而且很重要。

Create the detail frame in the main frame, and add a windowlistener to it, using the windowadapter class. Implement the windowclosing event by checking for changes, handle those, and then dispose the detail frame. This is all done in the mainframe.

The detail frame should have do nothing on close set to prevent the detail frame being disposed before you recorded the changes.

You may wish to implement checking for changes in the detailframe as a method returning a class holding the interesting data. That way your windowlistener can be small an to the point.

以为你会在 2024-11-10 04:05:29

忘记第二个JFrame。请改用模式对话框。它将阻止输入直到被解除。一旦驳回,唯一要做的就是决定是否更新原始数据。 JOptionPane 有一些内置功能可以让这一切变得简单。如果用户按 Cancelesc 键,则 showInputDialog() 方法将返回 null 作为结果。

import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

class EditInfo {

    public static void main(String[] args) {

        Runnable r = new Runnable() {
            public void run() {
                final JFrame f = new JFrame("Uneditable");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                JPanel p = new JPanel(new BorderLayout(10,10));

                final JTextField tf = new JTextField("Hello World!", 20);
                tf.setEnabled(false);
                p.add(tf, BorderLayout.CENTER);

                JButton edit = new JButton("Edit");
                edit.addActionListener( new ActionListener(){
                    public void actionPerformed(ActionEvent ae) {
                        String result = JOptionPane.showInputDialog(
                            f,
                            "Edit text",
                            tf.getText());
                        if (result!=null) {
                            tf.setText(result);
                        }
                    }
                } );
                p.add(edit, BorderLayout.EAST);

                p.setBorder(new EmptyBorder(10,10,10,10));

                f.setContentPane(p);
                f.pack();
                f.setLocationByPlatform(true);
                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

如果需要在 JOptionPane 中同时编辑多个字段,请使用 JPanel 包含所有字段,并将它们放入 showMessageDialog() 中调用。检查基于整数的返回结果以确定用户是否同意更改。

Forget the 2nd JFrame. use a modal dialog instead. It will block input until dismissed. Once dismissed, the only thing to do is decide whether to update the original data. JOptionPane has some inbuilt functionality that makes that easy. If the user presses Cancel or the esc key, the showInputDialog() method will return null as the result.

import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

class EditInfo {

    public static void main(String[] args) {

        Runnable r = new Runnable() {
            public void run() {
                final JFrame f = new JFrame("Uneditable");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                JPanel p = new JPanel(new BorderLayout(10,10));

                final JTextField tf = new JTextField("Hello World!", 20);
                tf.setEnabled(false);
                p.add(tf, BorderLayout.CENTER);

                JButton edit = new JButton("Edit");
                edit.addActionListener( new ActionListener(){
                    public void actionPerformed(ActionEvent ae) {
                        String result = JOptionPane.showInputDialog(
                            f,
                            "Edit text",
                            tf.getText());
                        if (result!=null) {
                            tf.setText(result);
                        }
                    }
                } );
                p.add(edit, BorderLayout.EAST);

                p.setBorder(new EmptyBorder(10,10,10,10));

                f.setContentPane(p);
                f.pack();
                f.setLocationByPlatform(true);
                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

If it is necessary to edit a number of fields all at once in the JOptionPane, use a JPanel to contain them all, and put them in a showMessageDialog() call. Check the integer based return result to determine if the user OK'd the changes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文