如何防止在 JTabbedPane 上留下选项卡

发布于 2024-12-28 12:25:15 字数 4259 浏览 1 评论 0原文

我有一个嵌套 JTabbedPanes 的应用程序。每个 JTabbedPanes 都包含其他 JTabbedPanes。

我想在允许用户离开当前选项卡之前检查一些内容。

当您运行下面的代码时,您将看到“月份->二月”选项卡有一个“允许”复选框。

如果选中“允许”复选框,那么我想允许用户导航离开当前面板。如果不是,那么他们就不能离开,直到它成为为止。

我似乎找不到一种方法来处理在显示下一个组件(可能位于另一个 JTabbedPane 上)之前离开的请求。

这可以通过转到“月份->二月”选项卡,然后选择“颜色”选项卡来演示。

有什么想法吗?

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;

public class VerifyBeforeLeavingTab extends JFrame
{
    private static final long   serialVersionUID    = 1L;

    public VerifyBeforeLeavingTab()
    {
        setSize(700, 700);

        JTabbedPane mainTabbedPane = new JTabbedPane(JTabbedPane.TOP);

        MyJTabbedPane colorsPane = new MyJTabbedPane(JTabbedPane.TOP, "colors");
        JPanel bluePanel = new JPanel();
        bluePanel.setBackground(Color.blue);
        colorsPane.addTab("Blue", bluePanel);

        JPanel redPanel = new JPanel();
        redPanel.setBackground(Color.red);
        colorsPane.addTab("Red", redPanel);

        mainTabbedPane.addTab("Colors", colorsPane);

        JTabbedPane monthsPane = new MyJTabbedPane(JTabbedPane.TOP, "months");

        JPanel janPanel = new JPanel();
        monthsPane.addTab("January", janPanel);

        JPanel febPanel = new MyUnleavableJPanel();
        monthsPane.addTab("February", febPanel);

        mainTabbedPane.addTab("Months", monthsPane);

        add(mainTabbedPane, BorderLayout.CENTER);

        getContentPane().add(mainTabbedPane);
    }

    private class MyUnleavableJPanel extends JPanel
    {
        private static final long   serialVersionUID    = 1L;

        public MyUnleavableJPanel()
        {
            final JCheckBox chckBoxAllowToLeave = new JCheckBox("Allow to leave");
            chckBoxAllowToLeave.setBounds(100, 100, 50, 50);
            this.add(chckBoxAllowToLeave);

            addHierarchyListener(new HierarchyListener()
            {
                public void hierarchyChanged(HierarchyEvent e)
                {
                    if ((HierarchyEvent.SHOWING_CHANGED & e.getChangeFlags()) != 0)
                    {
                        if (isShowing())
                        {
                            System.out.println("Showing an unleavable panel");
                        }
                        else
                        {
                            // TODO: Do not let them leave this JCheckbox is selected
                            if (chckBoxAllowToLeave.isSelected())
                            {
                                System.out.println("OK to leave");
                            }
                            else
                            {
                                System.out.println("Not allowed to leave");
                            }
                        }
                    }
                }
            });
        }
    }

    private class MyJTabbedPane extends JTabbedPane
    {
        private static final long   serialVersionUID    = 1L;

        public MyJTabbedPane(int i, String name)
        {
            super(i);
            setName(name);
        }

        @Override
        public void setSelectedIndex(int index)
        {
            System.out.println("Now on '" + getName() + "' tab #" + index);
            super.setSelectedIndex(index);
        }
    }

    private static void createAndShowGUI()
    {
        // Create and set up the window.
        VerifyBeforeLeavingTab frame = new VerifyBeforeLeavingTab();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                try
                {
                    createAndShowGUI();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    System.exit(0);
                }
            }
        });
    }

}

I have an application that has nested JTabbedPanes. Each of the JTabbedPanes include other JTabbedPanes.

I want to check something before allowing the user to leave the current tab.

When you run the code below, you'll see that the Months->February tab has an ALLOW checkbox.

If the ALLOW checkbox is selected, then I want to allow the user navigate to leave the current panel. If it is not, then they can't leave until it is.

I can't seem to find a way to handle the request to leave BEFORE the next Component (which may be on another JTabbedPane) is shown.

This can be demonstrated by going to the Months->February tab, and then selecting the Colors Tab.

Any ideas?

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;

public class VerifyBeforeLeavingTab extends JFrame
{
    private static final long   serialVersionUID    = 1L;

    public VerifyBeforeLeavingTab()
    {
        setSize(700, 700);

        JTabbedPane mainTabbedPane = new JTabbedPane(JTabbedPane.TOP);

        MyJTabbedPane colorsPane = new MyJTabbedPane(JTabbedPane.TOP, "colors");
        JPanel bluePanel = new JPanel();
        bluePanel.setBackground(Color.blue);
        colorsPane.addTab("Blue", bluePanel);

        JPanel redPanel = new JPanel();
        redPanel.setBackground(Color.red);
        colorsPane.addTab("Red", redPanel);

        mainTabbedPane.addTab("Colors", colorsPane);

        JTabbedPane monthsPane = new MyJTabbedPane(JTabbedPane.TOP, "months");

        JPanel janPanel = new JPanel();
        monthsPane.addTab("January", janPanel);

        JPanel febPanel = new MyUnleavableJPanel();
        monthsPane.addTab("February", febPanel);

        mainTabbedPane.addTab("Months", monthsPane);

        add(mainTabbedPane, BorderLayout.CENTER);

        getContentPane().add(mainTabbedPane);
    }

    private class MyUnleavableJPanel extends JPanel
    {
        private static final long   serialVersionUID    = 1L;

        public MyUnleavableJPanel()
        {
            final JCheckBox chckBoxAllowToLeave = new JCheckBox("Allow to leave");
            chckBoxAllowToLeave.setBounds(100, 100, 50, 50);
            this.add(chckBoxAllowToLeave);

            addHierarchyListener(new HierarchyListener()
            {
                public void hierarchyChanged(HierarchyEvent e)
                {
                    if ((HierarchyEvent.SHOWING_CHANGED & e.getChangeFlags()) != 0)
                    {
                        if (isShowing())
                        {
                            System.out.println("Showing an unleavable panel");
                        }
                        else
                        {
                            // TODO: Do not let them leave this JCheckbox is selected
                            if (chckBoxAllowToLeave.isSelected())
                            {
                                System.out.println("OK to leave");
                            }
                            else
                            {
                                System.out.println("Not allowed to leave");
                            }
                        }
                    }
                }
            });
        }
    }

    private class MyJTabbedPane extends JTabbedPane
    {
        private static final long   serialVersionUID    = 1L;

        public MyJTabbedPane(int i, String name)
        {
            super(i);
            setName(name);
        }

        @Override
        public void setSelectedIndex(int index)
        {
            System.out.println("Now on '" + getName() + "' tab #" + index);
            super.setSelectedIndex(index);
        }
    }

    private static void createAndShowGUI()
    {
        // Create and set up the window.
        VerifyBeforeLeavingTab frame = new VerifyBeforeLeavingTab();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                try
                {
                    createAndShowGUI();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    System.exit(0);
                }
            }
        });
    }

}

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

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

发布评论

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

评论(3

傲影 2025-01-04 12:25:15

我扩展了 JTabbedPane 并覆盖了 setSelectedIndex()。如果想让选择成功,调用super.setSelectedIndex;否则不要。

我用它来调用与选项卡关联的验证例程,并在验证失败时否决更改。这种方法的一个好处是它完全不依赖于用户如何更改选项卡——他可以单击选项卡,单击移动选项卡的按钮等。

I extended JTabbedPane and overrode setSelectedIndex(). If you want to allow the selection to succeed, call super.setSelectedIndex; otherwise don't.

I use this to call a validation routine associated with the tab, and veto the change if validation fails. One nice thing about this method is that it is not at all dependent on how the user changes tabs -- he could click on a tab, click a button that moves tabs, etc.

还如梦归 2025-01-04 12:25:15

好吧,决定继续我自己的例子;两个类,运行主类会生成一个摆动窗口,允许您每次单击时更改选项卡。

    import javax.swing.JFrame;
    import javax.swing.JPanel;

    public class TabbedPaneExample extends JFrame
    {
        public static void main(String[] args)
        {
            TabbedPaneExample example = new TabbedPaneExample();
            example.go();
        }

        public void go()
        {
            ValidatingTabbedPane vtp = new ValidatingTabbedPane();
            for(int i=0; i<3; i++)
            {
                vtp.addTab(""+i, new JPanel());
            }
            vtp.setSelectedIndex(0);

            getContentPane().add(vtp);
            pack();
            setVisible(true);
        }
    }

和另一堂课:

    import javax.swing.JOptionPane;
    import javax.swing.JTabbedPane;

    public class ValidatingTabbedPane extends JTabbedPane
    {
      private static final long serialVersionUID = 1L;
      private static void debug(String msg) { System.out.println(msg); }
      private static boolean thisTime = true;

      /**
       * override of selecting a new panel; the new panel selection
       * is only allowed after the current panel determines that
       * its data is valid.
       */
        @Override
        public void setSelectedIndex(int newIndex)
        {
            int currentIndex = getSelectedIndex();
            if (newIndex >=0 && newIndex < getTabCount())
            {
                // if we are currently setting the selected tab for the first
                // time, we don't need to validate the currently selected panel;
                // same if we're (somehow) selecting the current panel
                if(currentIndex == -1)
                {
                    super.setSelectedIndex(newIndex);
                }
          else
          {
              if (currentIndex != newIndex)
              {
                if (thisTime)
                {
                    super.setSelectedIndex(newIndex);
                }
                else
                {
                    JOptionPane.showMessageDialog(null, "Not this time");
                }
                thisTime = !thisTime;
                // ok, the user wants to go from one panel to another.
                // ensure there are no validation errors on the current
                // panel before he moves on.
    //          DataPanel panel = (DataPanel) getSelectedComponent();
    //          if (panel.validateData())
    //          {
    //              super.setSelectedIndex(newIndex);
    ////                tabChangeListener.tabsChanged();
    //          }
            }
          }
            }
            else
            {
                debug("setting new tabbed pane index to " + newIndex + "; wonder why?");
            }
        }



    }

我留下了评论以显示我在实际程序中验证的位置。

Ok, decided to go ahead with my own example; two classes, running the main class produces a swing window that allows you to change tabs every other time you click.

    import javax.swing.JFrame;
    import javax.swing.JPanel;

    public class TabbedPaneExample extends JFrame
    {
        public static void main(String[] args)
        {
            TabbedPaneExample example = new TabbedPaneExample();
            example.go();
        }

        public void go()
        {
            ValidatingTabbedPane vtp = new ValidatingTabbedPane();
            for(int i=0; i<3; i++)
            {
                vtp.addTab(""+i, new JPanel());
            }
            vtp.setSelectedIndex(0);

            getContentPane().add(vtp);
            pack();
            setVisible(true);
        }
    }

and the other class:

    import javax.swing.JOptionPane;
    import javax.swing.JTabbedPane;

    public class ValidatingTabbedPane extends JTabbedPane
    {
      private static final long serialVersionUID = 1L;
      private static void debug(String msg) { System.out.println(msg); }
      private static boolean thisTime = true;

      /**
       * override of selecting a new panel; the new panel selection
       * is only allowed after the current panel determines that
       * its data is valid.
       */
        @Override
        public void setSelectedIndex(int newIndex)
        {
            int currentIndex = getSelectedIndex();
            if (newIndex >=0 && newIndex < getTabCount())
            {
                // if we are currently setting the selected tab for the first
                // time, we don't need to validate the currently selected panel;
                // same if we're (somehow) selecting the current panel
                if(currentIndex == -1)
                {
                    super.setSelectedIndex(newIndex);
                }
          else
          {
              if (currentIndex != newIndex)
              {
                if (thisTime)
                {
                    super.setSelectedIndex(newIndex);
                }
                else
                {
                    JOptionPane.showMessageDialog(null, "Not this time");
                }
                thisTime = !thisTime;
                // ok, the user wants to go from one panel to another.
                // ensure there are no validation errors on the current
                // panel before he moves on.
    //          DataPanel panel = (DataPanel) getSelectedComponent();
    //          if (panel.validateData())
    //          {
    //              super.setSelectedIndex(newIndex);
    ////                tabChangeListener.tabsChanged();
    //          }
            }
          }
            }
            else
            {
                debug("setting new tabbed pane index to " + newIndex + "; wonder why?");
            }
        }



    }

I left comments in to show where I'm validating in my real program.

鹿! 2025-01-04 12:25:15

@rcook - 我已将您的 setSelected() 方法插入到我的原始代码中。
当您运行该程序时,将显示蓝色面板(在“颜色”选项卡下)。

如果您转到二月面板(在“月份”选项卡下),您将看到一个复选框。此复选框用于确定用户是否应该能够离开二月面板。

取消选中该复选框,然后单击“一月”。正如预期的那样,用户不允许离开面板。

现在,在取消选中复选框的情况下,单击“颜色”。它不起作用 - 用户不应该能够离开二月面板,因为未选中该复选框。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;

public class VerifyBeforeLeavingTab extends JFrame
{
    private static final long       serialVersionUID    = 1L;
    private static final JCheckBox  chckBoxAllowToLeave = new JCheckBox("Allow to leave");

    public VerifyBeforeLeavingTab()
    {
        setSize(700, 700);

        JTabbedPane mainTabbedPane = new JTabbedPane(JTabbedPane.TOP);

        MyJTabbedPane colorsPane = new MyJTabbedPane(JTabbedPane.TOP, "colors");
        JPanel bluePanel = new JPanel();
        bluePanel.setBackground(Color.blue);
        colorsPane.addTab("Blue", bluePanel);

        JPanel redPanel = new JPanel();
        redPanel.setBackground(Color.red);
        colorsPane.addTab("Red", redPanel);

        mainTabbedPane.addTab("Colors", colorsPane);

        JTabbedPane monthsPane = new MyJTabbedPane(JTabbedPane.TOP, "months");

        JPanel janPanel = new JPanel();
        monthsPane.addTab("January", janPanel);

        JPanel febPanel = new MyUnleavableJPanel();
        monthsPane.addTab("February", febPanel);

        mainTabbedPane.addTab("Months", monthsPane);

        add(mainTabbedPane, BorderLayout.CENTER);

        getContentPane().add(mainTabbedPane);
    }

    private class MyUnleavableJPanel extends JPanel
    {
        private static final long   serialVersionUID    = 1L;

        public MyUnleavableJPanel()
        {
            // final JCheckBox chckBoxAllowToLeave = new JCheckBox("Allow to leave");
            chckBoxAllowToLeave.setBounds(100, 100, 50, 50);
            chckBoxAllowToLeave.setSelected(true);
            this.add(chckBoxAllowToLeave);

            addHierarchyListener(new HierarchyListener()
            {
                public void hierarchyChanged(HierarchyEvent e)
                {
                    if ((HierarchyEvent.SHOWING_CHANGED & e.getChangeFlags()) != 0)
                    {
                        if (isShowing())
                        {
                            System.out.println("Showing an unleavable panel");
                        }
                        else
                        {
                            // TODO: Do not let them leave if this JCheckbox is selected
                            if (chckBoxAllowToLeave.isSelected())
                            {
                                System.out.println("OK to leave");
                            }
                            else
                            {
                                System.out.println("Not allowed to leave");
                            }
                        }
                    }
                }
            });
        }
    }

    private class MyJTabbedPane extends JTabbedPane
    {
        private static final long   serialVersionUID    = 1L;

        public MyJTabbedPane(int i, String name)
        {
            super(i);
            setName(name);
        }

        /**
         * override of selecting a new panel; the new panel selection is only allowed after the current panel determines
         * that its data is valid.
         */
        @Override
        public void setSelectedIndex(int newIndex)
        {
            System.out.println("Now on '" + getName() + "' tab #" + newIndex);
            int currentIndex = getSelectedIndex();
            if (newIndex >= 0 && newIndex < getTabCount())
            {
                // if we are currently setting the selected tab for the first
                // time, we don't need to validate the currently selected panel;
                // same if we're (somehow) selecting the current panel
                if (currentIndex == -1)
                {
                    super.setSelectedIndex(newIndex);
                }
                else
                {
                    if (currentIndex != newIndex)
                    {
                        if (chckBoxAllowToLeave.isSelected())
                        {
                            super.setSelectedIndex(newIndex);
                        }
                        else
                        {
                            JOptionPane.showMessageDialog(null, "Not this time");
                        }

                    }
                }
            }
            else
            {
                System.out.println("setting new tabbed pane index to " + newIndex + "; wonder why?");
            }
        }
    }

    private static void createAndShowGUI()
    {
        // Create and set up the window.
        VerifyBeforeLeavingTab frame = new VerifyBeforeLeavingTab();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                try
                {
                    createAndShowGUI();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    System.exit(0);
                }
            }
        });
    }

}

@rcook - I have inserted your setSelected() method into my original code.
When you run the program, the Blue panel (under Colors Tab) will be displayed.

If you go to the February Panel (under the Months Tab) you will see a Checkbox. This Checkbox is used to determine if the user should be able to leave the February panel.

Un-Select the Checkbox and then click on January. As expected, the user is not allowed to leave the panel.

Now, while the Checkbox is unselected, click on Colors. It does not work - the user should not have been able to leave the February panel because the checkbox was not checked.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;

public class VerifyBeforeLeavingTab extends JFrame
{
    private static final long       serialVersionUID    = 1L;
    private static final JCheckBox  chckBoxAllowToLeave = new JCheckBox("Allow to leave");

    public VerifyBeforeLeavingTab()
    {
        setSize(700, 700);

        JTabbedPane mainTabbedPane = new JTabbedPane(JTabbedPane.TOP);

        MyJTabbedPane colorsPane = new MyJTabbedPane(JTabbedPane.TOP, "colors");
        JPanel bluePanel = new JPanel();
        bluePanel.setBackground(Color.blue);
        colorsPane.addTab("Blue", bluePanel);

        JPanel redPanel = new JPanel();
        redPanel.setBackground(Color.red);
        colorsPane.addTab("Red", redPanel);

        mainTabbedPane.addTab("Colors", colorsPane);

        JTabbedPane monthsPane = new MyJTabbedPane(JTabbedPane.TOP, "months");

        JPanel janPanel = new JPanel();
        monthsPane.addTab("January", janPanel);

        JPanel febPanel = new MyUnleavableJPanel();
        monthsPane.addTab("February", febPanel);

        mainTabbedPane.addTab("Months", monthsPane);

        add(mainTabbedPane, BorderLayout.CENTER);

        getContentPane().add(mainTabbedPane);
    }

    private class MyUnleavableJPanel extends JPanel
    {
        private static final long   serialVersionUID    = 1L;

        public MyUnleavableJPanel()
        {
            // final JCheckBox chckBoxAllowToLeave = new JCheckBox("Allow to leave");
            chckBoxAllowToLeave.setBounds(100, 100, 50, 50);
            chckBoxAllowToLeave.setSelected(true);
            this.add(chckBoxAllowToLeave);

            addHierarchyListener(new HierarchyListener()
            {
                public void hierarchyChanged(HierarchyEvent e)
                {
                    if ((HierarchyEvent.SHOWING_CHANGED & e.getChangeFlags()) != 0)
                    {
                        if (isShowing())
                        {
                            System.out.println("Showing an unleavable panel");
                        }
                        else
                        {
                            // TODO: Do not let them leave if this JCheckbox is selected
                            if (chckBoxAllowToLeave.isSelected())
                            {
                                System.out.println("OK to leave");
                            }
                            else
                            {
                                System.out.println("Not allowed to leave");
                            }
                        }
                    }
                }
            });
        }
    }

    private class MyJTabbedPane extends JTabbedPane
    {
        private static final long   serialVersionUID    = 1L;

        public MyJTabbedPane(int i, String name)
        {
            super(i);
            setName(name);
        }

        /**
         * override of selecting a new panel; the new panel selection is only allowed after the current panel determines
         * that its data is valid.
         */
        @Override
        public void setSelectedIndex(int newIndex)
        {
            System.out.println("Now on '" + getName() + "' tab #" + newIndex);
            int currentIndex = getSelectedIndex();
            if (newIndex >= 0 && newIndex < getTabCount())
            {
                // if we are currently setting the selected tab for the first
                // time, we don't need to validate the currently selected panel;
                // same if we're (somehow) selecting the current panel
                if (currentIndex == -1)
                {
                    super.setSelectedIndex(newIndex);
                }
                else
                {
                    if (currentIndex != newIndex)
                    {
                        if (chckBoxAllowToLeave.isSelected())
                        {
                            super.setSelectedIndex(newIndex);
                        }
                        else
                        {
                            JOptionPane.showMessageDialog(null, "Not this time");
                        }

                    }
                }
            }
            else
            {
                System.out.println("setting new tabbed pane index to " + newIndex + "; wonder why?");
            }
        }
    }

    private static void createAndShowGUI()
    {
        // Create and set up the window.
        VerifyBeforeLeavingTab frame = new VerifyBeforeLeavingTab();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                try
                {
                    createAndShowGUI();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    System.exit(0);
                }
            }
        });
    }

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