当前位置: 首页 > 知识库问答 >
问题:

调用setComponentAt()后无法将面板添加到jtabbed窗格

齐鸿光
2023-03-14

我添加了一个名为MyEditorPanel的自定义面板,它将JPanel扩展到JTabbedPanel,并希望在每个选项卡上都有一个关闭按钮,为此,我使用了以下代码并使用了ButtonTabbedComponent.java的ButtonTabbedComponent.java

public void addTab(String name, String desc) {
    MyEditorPane textEditorPane = new MyEditorPane(this, name, desc);
    this.addTab(name, normal, textEditorPane, desc);
    int i = this.getComponentCount() - 1;
    textEditorPane.setTabCount(i);
    this.setTabComponentAt(i, new ButtonTabComponent(this, normal, normalFont));
}

但是我想在关闭之前保存MyEditorPane中的文本,我怎么知道单击关闭按钮时哪个MyEditorPane将要关闭

当我得到JTabbedPane类中组件的名称时,它没有MyEditorPane类对象

@Override
public void remove(int index) {

Component component = this.getTabComponentAt(index);
if (component instanceof ButtonTabComponent) {
    ButtonTabComponent tab = (ButtonTabComponent) component;
    System.out.println("remove method called if : " + tab.getComponentCount());
    component = tab.getComponent(0);
    System.out.println("remove method called if : " + component.getClass().getName());

    component = tab.getComponent(1);
    System.out.println("remove method called if : " + component.getClass().getName());
    JPanel pane = (JPanel) component;
    Component[] components = pane.getComponents();
    for (int i = 0, l = components.length; i < l; i++) {
            System.out.println("remove method called for : " + components[i].getClass().getName());                
    }
    super.remove(index);
}
}

方法删除的输出

remove method called if : 2
remove method called if : javax.swing.JLabel
remove method called if : javax.swing.JPanel
remove method called for : pkginterface.ButtonTabComponent$1
remove method called for : pkginterface.ButtonTabComponent$TabButton

共有1个答案

程吕恭
2023-03-14

因此,基于如何使用选项卡式窗格的例子,您可以使用类似...

public void actionPerformed(ActionEvent e) {
    int i = pane.indexOfTabComponent(ButtonTabComponent.this);
    if (i != -1) {
        Component comp = pane.getComponentAt(i);
        if (comp instanceof JLabel) {
            JLabel label = (JLabel) comp;
            System.out.println("Label text = " + label.getText());
            switch (JOptionPane.showConfirmDialog(this, "Are you sure you want to close the \"" + pane.getTitleAt(i) + "\" tab?", "Close", JOptionPane.OK_CANCEL_OPTION)) {
                case JOptionPane.OK_OPTION:
                    pane.remove(i);
                    break;
            }
        }
    }
}

这允许您确定已关闭的选项卡,找到充当选项卡视图的组件,询问用户是否要关闭此特定选项卡,并根据他们的反馈采取适当的行动

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.plaf.basic.BasicButtonUI;

public class TabComponentsDemo extends JFrame {

    private final int tabNumber = 5;
    private final JTabbedPane pane = new JTabbedPane();
    private JMenuItem tabComponentsItem;
    private JMenuItem scrollLayoutItem;

    public static void main(String[] args) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    //Turn off metal's use of bold fonts
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }
                new TabComponentsDemo("TabComponentsDemo").runTest();
            }
        });
    }

    public TabComponentsDemo(String title) {
        super(title);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initMenu();
        add(pane);
    }

    public void runTest() {
        pane.removeAll();
        for (int i = 0; i < tabNumber; i++) {
            String title = "Tab " + i;
            pane.add(title, new JLabel(title));
            initTabComponent(i);
        }
        tabComponentsItem.setSelected(true);
        pane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);
        scrollLayoutItem.setSelected(false);
        setSize(new Dimension(400, 200));
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void initTabComponent(int i) {
        pane.setTabComponentAt(i,
                new ButtonTabComponent(pane));
    }

    //Setting menu
    private void initMenu() {
        JMenuBar menuBar = new JMenuBar();
        //create Options menu
        tabComponentsItem = new JCheckBoxMenuItem("Use TabComponents", true);
        tabComponentsItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.ALT_MASK));
        tabComponentsItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                for (int i = 0; i < pane.getTabCount(); i++) {
                    if (tabComponentsItem.isSelected()) {
                        initTabComponent(i);
                    } else {
                        pane.setTabComponentAt(i, null);
                    }
                }
            }
        });
        scrollLayoutItem = new JCheckBoxMenuItem("Set ScrollLayout");
        scrollLayoutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.ALT_MASK));
        scrollLayoutItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (pane.getTabLayoutPolicy() == JTabbedPane.WRAP_TAB_LAYOUT) {
                    pane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
                } else {
                    pane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);
                }
            }
        });
        JMenuItem resetItem = new JMenuItem("Reset JTabbedPane");
        resetItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.ALT_MASK));
        resetItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                runTest();
            }
        });

        JMenu optionsMenu = new JMenu("Options");
        optionsMenu.add(tabComponentsItem);
        optionsMenu.add(scrollLayoutItem);
        optionsMenu.add(resetItem);
        menuBar.add(optionsMenu);
        setJMenuBar(menuBar);
    }

    public static class ButtonTabComponent extends JPanel {

        private final JTabbedPane pane;

        public ButtonTabComponent(final JTabbedPane pane) {
            //unset default FlowLayout' gaps
            super(new FlowLayout(FlowLayout.LEFT, 0, 0));
            if (pane == null) {
                throw new NullPointerException("TabbedPane is null");
            }
            this.pane = pane;
            setOpaque(false);

            //make JLabel read titles from JTabbedPane
            JLabel label = new JLabel() {
                public String getText() {
                    int i = pane.indexOfTabComponent(ButtonTabComponent.this);
                    if (i != -1) {
                        return pane.getTitleAt(i);
                    }
                    return null;
                }
            };

            add(label);
            //add more space between the label and the button
            label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
            //tab button
            JButton button = new TabButton();
            add(button);
            //add more space to the top of the component
            setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
        }

        private class TabButton extends JButton implements ActionListener {

            public TabButton() {
                int size = 17;
                setPreferredSize(new Dimension(size, size));
                setToolTipText("close this tab");
                //Make the button looks the same for all Laf's
                setUI(new BasicButtonUI());
                //Make it transparent
                setContentAreaFilled(false);
                //No need to be focusable
                setFocusable(false);
                setBorder(BorderFactory.createEtchedBorder());
                setBorderPainted(false);
                //Making nice rollover effect
                //we use the same listener for all buttons
                addMouseListener(buttonMouseListener);
                setRolloverEnabled(true);
                //Close the proper tab by clicking the button
                addActionListener(this);
            }

            public void actionPerformed(ActionEvent e) {
                int i = pane.indexOfTabComponent(ButtonTabComponent.this);
                if (i != -1) {
                    Component comp = pane.getComponentAt(i);
                    if (comp instanceof JLabel) {
                        JLabel label = (JLabel) comp;
                        System.out.println("Label text = " + label.getText());
                        switch (JOptionPane.showConfirmDialog(this, "Are you sure you want to close the \"" + pane.getTitleAt(i) + "\" tab?", "Close", JOptionPane.OK_CANCEL_OPTION)) {
                            case JOptionPane.OK_OPTION:
                                pane.remove(i);
                                break;
                        }
                    }
                }
            }

            //we don't want to update UI for this button
            public void updateUI() {
            }

            //paint the cross
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D) g.create();
                //shift the image for pressed buttons
                if (getModel().isPressed()) {
                    g2.translate(1, 1);
                }
                g2.setStroke(new BasicStroke(2));
                g2.setColor(Color.BLACK);
                if (getModel().isRollover()) {
                    g2.setColor(Color.MAGENTA);
                }
                int delta = 6;
                g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1);
                g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1);
                g2.dispose();
            }
        }

        private final static MouseListener buttonMouseListener = new MouseAdapter() {
            public void mouseEntered(MouseEvent e) {
                Component component = e.getComponent();
                if (component instanceof AbstractButton) {
                    AbstractButton button = (AbstractButton) component;
                    button.setBorderPainted(true);
                }
            }

            public void mouseExited(MouseEvent e) {
                Component component = e.getComponent();
                if (component instanceof AbstractButton) {
                    AbstractButton button = (AbstractButton) component;
                    button.setBorderPainted(false);
                }
            }
        };
    }
}
 类似资料:
  • 我正在构建一个Java程序。该程序的核心在JFrame中可视化,其中包含一个JMenuBar和各种JMenuItem和JMenu。关键是我在所有框架中添加了一个centralPanel,但是如果我在centralPanel中添加了一些内容,那么只有在调整主框架的大小、缩小或放大它时,它才会显示出来!代码如下: 这是构造函数: 在这里,我添加了中央面板,在这里,在ActionListener中,我试

  • 问题内容: 我有3个JPanels,我想将它们全部放在一个JPanel中。我将GridBagLayout用于主面板。但是只添加了一个面板。为什么会这样呢? 定制程序方法是将项目添加到这些面板中的方法。 问题答案: 我不确定,但是我认为您需要在GridBagLayout中添加一个GridBagConstraints。尝试查看此站点,以获取有关如何使用GridBagLayout的想法: 链接 或者也许

  • 我试图通过点击JButton将一张新卡添加到现有的JPanel(cardLayout)中,然后转到该新卡,但由于新卡未注册,我得到了空异常。 我试着在谷歌上搜索,但找不到和示例,我试着用 但什么都不管用,这是可能的吗?如果是的话,有人知道任何例子吗? 代码如下,jPanelSliding1。NextSlidePanel只需移动到CardLayout中选定的JPanel。此处创建的新面板由于找不到面

  • 我有J标签窗格和几个标签。我面临的问题是我有一个面板,里面有2个按钮和一个文本区域。面板位于 JScroll 面板内。然后,我将 JScrollPane 添加到选项卡中,但按钮和文本区域彼此相邻,并在中心对齐。我想要的是JTextArea在按钮下方,而不是在按钮的右侧。我尝试过将BorderLayout用于按钮和文本区域(将按钮放在页面开始和文本区域页面结束),但它不会改变任何东西。

  • 我一直在尝试创建一个代码来模拟学校的队列(目前还没有),并尝试创建多个图片框并将它们存储在一个列表中。由于某种原因,他们没有出现。。。有人有什么建议吗?