JAVA:按钮不关闭与其关联的选项卡

时间:2016-01-25 17:18:39

标签: java swing tabs

以下是snapshot of my problem。在这里我按下了3号标签的关闭按钮,但它要求保存标签1的工作

以下是我的文件Tab.java

中的代码
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.Insets;
    import java.awt.Rectangle;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.io.File;

    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextArea;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.text.Element;

    public class Tab {
    JTextArea textArea, linesTestarea;
    JScrollPane scrollPane;
    JTabbedPane tabbedPane;
    JLabel label;
    final JButton button = new JButton("x");;
    boolean newFile;
    String filename, filepath;
    JPanel panel;

    public Tab(JTabbedPane tabbedPane) {
        this.tabbedPane = tabbedPane;
        newFile = true;
        filename = "untitled.txt";
    }

    public Tab addTab(boolean newBlankTab) {
        textArea = new JTextArea();

        setLineNumberProperty();
        textArea.setFont(new Font("Serif", Font.PLAIN,    StaticVariables.fontSize));
        scrollPane = new JScrollPane();
        tabbedPane.addTab(null, scrollPane);
        tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
        tabbedPane.setTabComponentAt(tabbedPane.getTabCount() - 1,
                addPaneltoTabs(new JPanel()));
        tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(),
                Color.lightGray);
        System.out.println("from add tab " + tabbedPane.getSelectedIndex());
        filepath = new File(filename).getAbsolutePath();
        if (newBlankTab)
            StaticVariables.openedfiles.add(filepath);
        textArea.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void removeUpdate(DocumentEvent arg0) {
                linesTestarea.setText(showLineNumber(textArea));
                setTabTitle();
                if (StaticVariables.unsavedfiles.contains(getFilePath()) == false) {
                    StaticVariables.unsavedfiles.add(getFilePath());
                }
            }

            @Override
            public void insertUpdate(DocumentEvent arg0) {
                linesTestarea.setText(showLineNumber(textArea));
                if (StaticVariables.unsavedfiles.contains(getFilePath()) == false) {
                    setTabTitle();
                    StaticVariables.unsavedfiles.add(getFilePath());
                }
            }

            @Override
            public void changedUpdate(DocumentEvent arg0) {
                linesTestarea.setText(showLineNumber(textArea));
                setTabTitle();
                if (StaticVariables.unsavedfiles.contains(getFilePath()) == false) {
                    StaticVariables.unsavedfiles.add(getFilePath());
                }
            }
        });
        scrollPane.setViewportView(textArea);
        scrollPane.setRowHeaderView(linesTestarea);
        return this;
    }

    public JPanel addPaneltoTabs(JPanel panel) {
        panel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
        panel.setOpaque(false);
        filename = filename + tabbedPane.getSelectedIndex();
        System.out.println("from label" + tabbedPane.getSelectedIndex());
        label = new JLabel(filename);
        label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
        panel.add(label);

        setTabButtonProperty();
        panel.add(button);

        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                System.out.println(button.getParent().getParent()
                        .getComponent(0));
                button.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1,
                        new Color(0.200f, 0.123f, 0.123f, .2f)));
                button.setFont(StaticVariables.btnEnteredFont);
                button.setForeground(Color.BLACK);
            }

            public void mouseExited(MouseEvent e) {
                button.setBorder(BorderFactory.createEmptyBorder());
                button.setFont(StaticVariables.btnExitedFont);
                button.setForeground(Color.WHITE);
            }

            public void mouseClicked(MouseEvent e) {
                if (StaticVariables.unsavedfiles.contains(getFilePath())) {
                    String activeFilename = new File(getFilePath()).getName();
                    int opt = JOptionPane.showOptionDialog(null, activeFilename
                            + " is not saved", "Sodalime Save files alert",
                            JOptionPane.YES_NO_CANCEL_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null,
                            (Object[]) obj(), null);
                    if (opt == 0) {

                    } else if (opt == 1) {
                        removeTabs();
                    } else {
                        Tab temp = StaticVariables.tablist.get(tabbedPane
                                .getSelectedIndex());
                        FileAction fa = new FileAction();
                        fa.FileSaveaction(temp);
                        removeTabs();
                    }
                } else {
                    removeTabs();
                }

            }
        });
        return panel;
    }

    public void showTabList() {
        JPanel tabPanel = new JPanel();
        tabPanel.setSize(200, StaticVariables.tablist.size() * 10);
    }

    public String showLineNumber(JTextArea textArea) {
        int caretPosition = textArea.getDocument().getLength();
        Element root = textArea.getDocument().getDefaultRootElement();
        String text = "1" + System.getProperty("line.separator");
        for (int i = 2; i < root.getElementIndex(caretPosition) + 2; i++) {
            text += i + System.getProperty("line.separator");
        }
        return text;
    }

    public void setTabButtonProperty() {
        button.setOpaque(false);
        button.setFocusPainted(false);
        button.setContentAreaFilled(false);
        button.setPreferredSize(new Dimension(20, 20));
        button.setToolTipText("close this tab");
        button.setFocusable(false);
        button.setBorder(BorderFactory.createEmptyBorder());
        button.setForeground(Color.WHITE);
    }

    public void setLineNumberProperty() {
        Dimension d = new Dimension(20, textArea.getHeight());
        linesTestarea = new JTextArea("1");
        linesTestarea.setPreferredSize(d);
        linesTestarea.setBorder(BorderFactory.createEmptyBorder(7, 0, 0, 1));
        linesTestarea.setEditable(false);
        linesTestarea.setFont(new Font("Serif", Font.ITALIC,
                StaticVariables.fontSize));
        linesTestarea.setForeground(StaticVariables.linesColor);
    }

    public Object obj() {
        String options[] = { "Cancel", "close anyway", "Save and close" };
        return options;
    }

    public void removeTabs() {
        try {

            StaticVariables.openedfiles.remove(tabbedPane.getSelectedIndex());
            StaticVariables.tablist.remove(tabbedPane.getSelectedIndex());
            tabbedPane.remove(tabbedPane.getSelectedIndex());
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    }

    public void setTabTitle() {
        this.label.setFont(StaticVariables.tabUnsavedTitleFont);
    }

    public String getFilePath() {
        return StaticVariables.openedfiles.get(tabbedPane.getSelectedIndex());
    }
}

在附加的快照中,选中的选项卡是选项卡1,因此,由于方法getFilePath(),每当我按下关闭按钮时,它将返回所选选项卡的索引,而不是按钮实际关联的索引。那么如何使与3号标签相关联的按钮实际上关闭了3号标签?

StaticVariables类包含以下代码

    public class StaticVariables {

    public static int minWidth = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().width;
    public static int minHeight = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height;
    public static int menubarHeight = 150;
    public static int initialXcoordinates = 0;
    public static int initialYcoordinates = 0;
    public static int fontSize = 18;


    public static Color textareabgcolor = new Color(0.200f, 0.123f, 0.123f, .5f);
    public static Color linesColor = new Color(0.123f, 0.123f, 0.123f, .5f);

    public static ArrayList<Tab> tablist = new ArrayList<Tab>();
    public static ArrayList<String> unsavedfiles = new ArrayList<String>();
    public static ArrayList<String> openedfiles = new ArrayList<String>();
    public static ArrayList<String> fromOpenfile = new ArrayList<String>();

    public static Font btnEnteredFont = new Font("Times new Roman", Font.BOLD, 18);
    public static Font btnExitedFont = new Font("Times new Roman", Font.PLAIN, 18);
    public static Font tabUnsavedTitleFont = new Font("Times new Roman", Font.BOLD, 16);
    public static Font tabSavedTitleFont = new Font("Times new Roman", Font.PLAIN, 16);

}

这个问题让我的步伐变得非常慢,所以如果有人需要完整的源代码就可以了LINK

1 个答案:

答案 0 :(得分:0)

您错误地使用了JOptionPane。可以读取对话框选项创建参数详细信息here -

现在,当您选择了YES_NO_CANCEL_OPTION时,您传递的参数列表应为new String[]{ "Label For Yes Button", "Label For No Button", "Label For Cancel Button" }

将您的硬编码代码替换为JOptionPane常量,如下所示

if (opt == JOptionPane.CANCEL_OPTION) {
    //Do nothing
} else if (opt == JOptionPane.NO_OPTION) {
    removeTabs();
} else {
    Tab temp = StaticVariables.tablist.get(tabbedPane.getSelectedIndex());
    FileAction fa = new FileAction();
    fa.FileSaveaction(temp);
    removeTabs();
}

您仍将面临ArrayIndexOutOfBounds例外的问题。确保您的StaticVariables.tablistStaticVariables.unsavedfilesStaticVariables.openedfilesStaticVariables.fromOpenfile与当前窗口状态一致。意味着它们应该包含正确的值,直到与它们对应的选项卡可见,并且当它们的选项卡不存在时不应该存在。