There are a ton of parts to this as different parts of the class cause different things to happen. I'm in the process of trying to create a way to reuse code. I was trying to get a tab to go to a popup internal frame when I clicked on a popup menu, which I'm also having some issues with, and it comes out like it's supposed to, but when I minimize it, my InternalFrameListener on the minimizing part isn't doing what it's supposed to. It isn't adding it back.
I had hoped to add it back where it was taken from (i.e. the spot) but it kept writing over other tabs and so I moved it (for now until I can find a method to add it with the stuff I want a special index but only insertTab() seems to work, and I can't get that to do what I wanted it to, and it now stops trying to add the JLabel for the addTab button and throwing a ClassCastException, it still won't add it back. It just minimizes the popup internal frame. (Ideally, I'd like it to keep the tab but just set another tab (or index -1 if necessary) to be selected. (Kinda like how JGrasp does its tabs.)
No, I cannot break this into a few lines. I could spend hours and hours working to whittle it down but there are many parts to this. And NO, I WON'T make it into a few lines stupid SSCCE. I tend to hate those but anyway, I can show the areas that are likely to affect it. Another reason I want to post all of it is that if I mistakenly remove something valid, somebody will whine "It won't compile." and I've had a lot of pain with that too and getting help in the past. A SSCCE won't really work in this case as there could be lots of areas that mess it up. I had an issue earlier that was glitching in an area I didn't even think would be affected by my code.
package gui; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JTabbedPane; import java.awt.BorderLayout; import java.awt.event.KeyEvent; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.KeyStroke; import java.util.TreeMap; import javax.swing.JScrollPane; import java.io.PrintWriter; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import javax.swing.JButton; import javax.swing.event.ChangeListener; import javax.swing.event.ChangeEvent; import javax.swing.JCheckBoxMenuItem; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.TransferHandler; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.UIManager; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import java.awt.Graphics; import javax.swing.BorderFactory; import java.awt.Color; import javax.swing.JToolBar; import javax.swing.JComboBox; import java.awt.Font; import java.awt.GraphicsEnvironment; import javax.swing.JColorChooser; import gui.utilities.WordCounter; import javax.swing.JPopupMenu; import javax.swing.JDesktopPane; import java.util.Calendar; import javax.swing.event.InternalFrameListener; import javax.swing.event.InternalFrameEvent; import javax.swing.JInternalFrame; public class NotePadFrame extends JFrame implements WindowListener { private JMenuBar menuBar; private JMenu file, edit, format, help; private JMenuItem newDocument, exit, save, saveAs, load, print, closeTab; private JMenuItem copy, paste, cut, clear, delete, selectAll, findReplace, undo, redo, dateTimeStamp; private JMenuItem font, pageSetup; private JMenuItem help2, about; private NotepadPanel notepadpanel; private int documentCount; private int selectedTab; private PasteTransferHandler pth; private JFileChooser openFileChooser; private components.DnDTabbedPane tabPane; private JMenu lines; private JMenuItem dashedLine, solidLine, starLine, dotLine, tildaLine; private JScrollPane jsp; private javax.swing.JTextArea preview; private JFileChooser saveFileChooser; private JMenuItem wordCount; private JPanel topPanel; private JToolBar toolBar; private JButton saveButton; private JButton loadButton; private JButton printButton; private boolean bold; private boolean italic; private JButton boldButton; private JButton italicButton; private String[] fontNames; private JComboBox<String> fontNameBox; private JComboBox<String> fontSizeBox; private JColorChooser fontColorChooser; private JComboBox<String> colorBox; private JButton helpButton; private JButton cutButton; private JButton pasteButton; private JButton copyButton; private JMenuItem textAreaColor; private JMenuItem textColor; private JButton undoButton; private JButton redoButton; private WordCounter wc; private boolean hf; private String header; private String footer; private JMenuItem newWindow; private JMenuItem saveAll; private PageSetup ps; private JPopupMenu tabPopupMenu; private JMenuItem restore, minimize, maximize, moveTabPane, openInNewWindow; private JDesktopPane popoutTabHolder; private JButton searchAndFindButton; public NotePadFrame() { super("Java Notepad"); tabPopupMenu = new JPopupMenu(); restore = new JMenuItem("Restore"); minimize = new JMenuItem("Minimize"); maximize = new JMenuItem("Maximize"); moveTabPane = new JMenuItem("Move Tab Bar To Bottom"); tabPopupMenu.add(restore); tabPopupMenu.addSeparator(); tabPopupMenu.add(minimize); tabPopupMenu.add(maximize); tabPopupMenu.addSeparator(); tabPopupMenu.add(moveTabPane); tabPopupMenu.addSeparator(); openInNewWindow = new JMenuItem("Open Tab In New Window"); tabPopupMenu.add(openInNewWindow); tabPopupMenu.addSeparator(); menuBar = new JMenuBar(); boldButton = new JButton("B"); boldButton.setFont(new java.awt.Font("Verdana", java.awt.Font.BOLD, 14)); italicButton = new JButton("I"); italicButton.setFont(new java.awt.Font("Verdana", java.awt.Font.ITALIC, 14)); pasteButton = new JButton(new javax.swing.ImageIcon("./paste.jpg")); pasteButton.setToolTipText("Paste"); copyButton = new JButton(new javax.swing.ImageIcon("./copy.jpg")); redoButton = new JButton(new javax.swing.ImageIcon("./redo.gif")); redoButton.setToolTipText("Redo"); copyButton.setToolTipText("Copy"); cutButton = new JButton(new javax.swing.ImageIcon("./cut.gif")); cutButton.setToolTipText("Cut"); italicButton.setToolTipText("Italic"); textColor = new JMenuItem("Set Text Color"); GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment(); Font[] fonts = e.getAllFonts(); // Get the fonts fontNames = new String[fonts.length]; undoButton = new JButton(new javax.swing.ImageIcon("./undo.gif")); for (int i=0; i < fonts.length; i++) { fontNames[i] = fonts[i].getName(); } fontNameBox = new JComboBox<String>(fontNames); fontNameBox.setToolTipText("Choose a font name"); bold = false; italic = false; fontNameBox.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { String fontName = (String)(fontNameBox.getSelectedItem()); javax.swing.JTextArea temp = getContentAt(getSelectedTab()).getTextArea(); int type; int bold2; int italic2; if (bold == true) bold2 = Font.BOLD; else bold2 = 0; if (italic == true) italic2 = Font.ITALIC; else italic2 = 0; type = bold2 + italic2; temp.setFont(new Font(fontName, type, temp.getFont().getSize() )); }}); String[] sizes = new String[16]; sizes[0] = "8"; sizes[1] = "9"; sizes[2] = "10"; sizes[3] = "11"; sizes[4] = "12"; sizes[5] = "14"; sizes[6] = "16"; sizes[7] = "18"; sizes[8] = "20"; sizes[9] = "22"; sizes[10] = "24"; sizes[11] = "26"; sizes[12] = "28"; sizes[13] = "36"; sizes[14] = "48"; sizes[15] = "72"; fontSizeBox = new JComboBox<String>(sizes); fontSizeBox.setToolTipText("Choose a font size"); fontSizeBox.setEditable(true); fontSizeBox.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { String fontSize = (String)(fontSizeBox.getSelectedItem()); javax.swing.JTextArea temp = getContentAt(getSelectedTab()).getTextArea(); int type; int bold2; int italic2; if (bold == true) bold2 = Font.BOLD; else bold2 = 0; if (italic == true) italic2 = Font.ITALIC; else italic2 = 0; type = bold2 + italic2; int fontSize2 = -10; try { fontSize2 = Integer.parseInt(fontSize); } catch(ClassCastException cce) { return; } catch(NumberFormatException nfe) { return; } if (fontSize2 <=0) return; temp.setFont(new Font(temp.getFont().getName(), type, fontSize2)); }}); preview = new javax.swing.JTextArea(15, 15); saveFileChooser = new JFileChooser("./"); jsp = new JScrollPane(preview, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); preview.setEditable(false); documentCount = 1; String[] colors = new String[15]; colors[0] = "Black"; colors[1] = "White"; colors[2] = "Red"; colors[3] = "Green"; colors[4] = "Blue"; colors[5] = "Yellow"; colors[6] = "Orange"; colors[7] = "Pink"; colors[8] = "Light Gray"; colors[9] = "Dark Gray"; colors[10] = "Cyan"; colors[11] = "Purple"; colors[12] = "Brown"; colors[13] = "Dark Blue"; colors[14] = "More Colors"; colorBox = new JComboBox<String>(colors); colorBox.setMaximumSize(new java.awt.Dimension(100, 100)); colorBox.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { String color = (String)(colorBox.getSelectedItem()); javax.swing.JTextArea temp = getContentAt(getSelectedTab()).getTextArea(); if (color.equals("Black")) temp.setForeground(Color.BLACK); else if (color.equals("White")) temp.setForeground(Color.WHITE); else if (color.equals("Red")) temp.setForeground(Color.RED); else if (color.equals("Green")) temp.setForeground(Color.GREEN); else if (color.equals("Blue")) temp.setForeground(Color.BLUE); else if (color.equals("Yellow")) temp.setForeground(Color.YELLOW); else if (color.equals("Orange")) temp.setForeground(Color.ORANGE); else if (color.equals("Pink")) temp.setForeground(Color.PINK); }}); saveButton = new JButton( new javax.swing.ImageIcon("./save_icon.gif")); loadButton = new JButton( new javax.swing.ImageIcon("./load.jpg")); printButton = new JButton( new javax.swing.ImageIcon("./print.gif")); setJMenuBar(menuBar); file = new JMenu("File"); menuBar.add(file); newDocument = new JMenuItem("New Document"); newDocument.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK)); file.add(newDocument); newWindow = new JMenuItem("New Window"); file.add(newWindow); newWindow.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { new NotePadFrame(); }}); file.addSeparator(); save = new JMenuItem("Save", new javax.swing.ImageIcon("./save_icon.gif")); file.add(save); save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK)); saveAs = new JMenuItem("Save As"); file.add(saveAs); saveAll = new JMenuItem("Save All"); file.add(saveAll); file.addSeparator(); load = new JMenuItem("Open", KeyEvent.VK_O); load.setIcon(new javax.swing.ImageIcon("./load.jpg")); load.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK)); file.add(load); file.addSeparator(); print = new JMenuItem("Print", KeyEvent.VK_P); print.setIcon(new javax.swing.ImageIcon("./print.gif")); print.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK)); file.add(print); file.addSeparator(); pageSetup = new JMenuItem("Page Setup"); file.add(pageSetup); file.addSeparator(); ps = PageSetup.getInstance(); pageSetup.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { ps.setVisible(true); }}); exit = new JMenuItem("Exit", KeyEvent.VK_Q); exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK)); closeTab = new JMenuItem("Close Tab", KeyEvent.VK_Q); closeTab.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.ALT_MASK)); wordCount = new JMenuItem("Word Count"); file.add(wordCount); file.addSeparator(); file.add(closeTab); file.add(exit); file.addSeparator(); edit = new JMenu("Edit"); menuBar.add(edit); setVisible(true); undo = new JMenuItem("Undo", KeyEvent.VK_Z); undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK)); edit.add(undo); redo = new JMenuItem("Redo", KeyEvent.VK_Y); redo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK)); edit.add(redo); edit.addSeparator(); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(this); JPanel contentPane = new JPanel(); UIManager.put("TabbedPane.selected", new javax.swing.plaf.ColorUIResource(new java.awt.Color(0, 180, 255))); UIManager.put("TabbedPane.unselectedBackground", new javax.swing.plaf.ColorUIResource(java.awt.Color.GREEN)); //UIManager.put("TabbedPane.contentAreaColor", new javax.swing.plaf.ColorUIResource(java.awt.Color.YELLOW)); tabPane = new components.DnDTabbedPane(JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT); tabPane.setComponentPopupMenu(tabPopupMenu); openInNewWindow.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { if (tabPane.getComponentAt(getSelectedTab()) instanceof NotepadPanel) { NotepadPanel npp = getContentAt(getSelectedTab()); tabPane.removeTabAt(getSelectedTab()); new NotePadFrame(npp); } }}); helpButton = new JButton(new javax.swing.ImageIcon("./help.jpg")); helpButton.setToolTipText("Help"); tabPane.setUI( new javax.swing.plaf.basic.BasicTabbedPaneUI() { @Override protected void installDefaults() { super.installDefaults(); highlight = Color.pink; lightHighlight = Color.black; shadow = Color.red; darkShadow = Color.cyan; focus = Color.yellow; } }); notepadpanel = new NotepadPanel(); contentPane.setLayout(new java.awt.BorderLayout()); topPanel = new JPanel(); toolBar = new JToolBar("Tool Bar", JToolBar.HORIZONTAL); boldButton.setToolTipText("Bold"); toolBar.add(saveButton); toolBar.add(loadButton); toolBar.addSeparator(); toolBar.add(printButton); toolBar.addSeparator(); toolBar.add(cutButton); toolBar.add(pasteButton); toolBar.add(copyButton); toolBar.addSeparator(); toolBar.add(undoButton); toolBar.add(redoButton); toolBar.addSeparator(); toolBar.add(colorBox); toolBar.add(fontNameBox); toolBar.add(fontSizeBox); fontNameBox.setMaximumSize(new java.awt.Dimension(220, 150)); fontSizeBox.setMaximumSize(new java.awt.Dimension(50, 50)); toolBar.add(boldButton); toolBar.add(italicButton); toolBar.addSeparator(); searchAndFindButton = new JButton(); toolBar.add(searchAndFindButton); toolBar.add(helpButton); undoButton.setToolTipText("Undo"); topPanel.setLayout(new BorderLayout()); topPanel.add(toolBar, BorderLayout.NORTH); topPanel.add(tabPane, BorderLayout.SOUTH); contentPane.add(topPanel, BorderLayout.PAGE_START); contentPane.add(notepadpanel, BorderLayout.CENTER); moveTabPane.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { if (tabPane.getTabPlacement() == JTabbedPane.TOP) { tabPane.setTabPlacement(JTabbedPane.BOTTOM); moveTabPane.setText("Move Tab Bar To Top"); } else { tabPane.setTabPlacement(JTabbedPane.TOP); moveTabPane.setText("Move Tab Bar To Bottom"); } }}); cut = new JMenuItem("Cut", KeyEvent.VK_X); edit.add(cut); edit.addSeparator(); cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK)); cut.setIcon(new javax.swing.ImageIcon("./cut.gif")); copy = new JMenuItem("Copy", KeyEvent.VK_C); edit.add(copy); edit.addSeparator(); copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK)); paste = new JMenuItem("Paste", KeyEvent.VK_V); paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK)); edit.add(paste); edit.addSeparator(); selectAll = new JMenuItem("Select All", KeyEvent.VK_A); selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK)); edit.add(selectAll); edit.addSeparator(); // this sets the title of the tab as "Untitled Document" // and sets the content of the tab as the NotepadPanel notepadpanel tabPane.addTab("Untitled Document", notepadpanel); // this is the add tab button implementation tabPane.addTab("+", new javax.swing.JLabel()); tabPane.setToolTipTextAt(tabPane.getTabCount()-1, "Add New Tab"); tabPane.addMouseListener( new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent e) { if (tabPane.getSelectedComponent() instanceof javax.swing.JLabel) { tabPopupMenu.setVisible(false); tabPane.addTab("Untitled Document " + documentCount , new NotepadPanel()); tabPane.setBackgroundAt(tabPane.getTabCount() -1, Color.GREEN); tabPane.setTabComponentAt(tabPane.getTabCount() -1, new components.ButtonTabComponent(tabPane, new NotepadPanel())); documentCount++; int count = tabPane.getTabCount(); javax.swing.JLabel newTabLabel = new javax.swing.JLabel("tab" + count); for (int i=0; i < tabPane.getTabCount(); i++) { if (tabPane.getTitleAt(i).equals("+")) { tabPane.removeTabAt(i); break; } } tabPane.addTab("+", newTabLabel); tabPane.setToolTipTextAt(tabPane.getTabCount()-1, "Add New Tab"); } } }); tabPane.addMouseListener( new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent e) { if (! (tabPane.getSelectedComponent() instanceof javax.swing.JLabel)) { tabPopupMenu.setVisible(true); } else { if (tabPopupMenu.isVisible()) tabPopupMenu.setVisible(false); } } }); // this does the close out button tabPane.setTabComponentAt(0, new components.ButtonTabComponent(tabPane, notepadpanel)); tabPane.setBackgroundAt(0, java.awt.Color.GREEN); setSelectedTab(0); documentCount++; openFileChooser = new JFileChooser("./"); JPanel jp = new JPanel(); jp.setLayout(new BorderLayout()); javax.swing.JLabel prev = new javax.swing.JLabel("<html><B>Preview</B></html>", javax.swing.JLabel.CENTER); jp.add(prev, BorderLayout.NORTH); jp.add(jsp, BorderLayout.CENTER); //tabPane.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(new java.awt.Color(255, 242, 0)), BorderFactory.createLineBorder(java.awt.Color.YELLOW)), BorderFactory.createLineBorder(new java.awt.Color(255, 230, 15)) )); //tabPane.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(java.awt.Color.BLACK), BorderFactory.createLineBorder(java.awt.Color.BLACK))); tabPane.setBorder(BorderFactory.createLineBorder(java.awt.Color.BLACK)); openFileChooser.setAccessory(jp); openFileChooser.addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e2) { if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY .equals(e2.getPropertyName())) { JFileChooser chooser = (JFileChooser)e2.getSource(); File oldFile = (File)e2.getOldValue(); File newFile = (File)e2.getNewValue(); // The selected file should always be the same as newFile File curFile = chooser.getSelectedFile(); try { preview.setText(readTextFromFile(curFile)); } catch(NullPointerException npe) { } } } }); tabPane.addChangeListener( new ChangeListener() { public void stateChanged(ChangeEvent e) { setSelectedTab(tabPane.getSelectedIndex()); if (tabPane.getTabCount() == 0) { closeTab.setEnabled(false); copy.setEnabled(false); cut.setEnabled(false); paste.setEnabled(false); selectAll.setEnabled(false); save.setEnabled(false); saveAs.setEnabled(false); print.setEnabled(false); font.setEnabled(false); } else { if (tabPane.getTabCount() !=0 && closeTab.isEnabled() == false) { closeTab.setEnabled(true); copy.setEnabled(true); cut.setEnabled(true); paste.setEnabled(true); selectAll.setEnabled(true); save.setEnabled(true); saveAs.setEnabled(true); print.setEnabled(true); font.setEnabled(true); } } } }); closeTab.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { if (getSelectedTab() != -1) { if (((NotepadPanel) (tabPane.getComponentAt(getSelectedTab()))).isUntitledDocument()) { int option = JOptionPane.showConfirmDialog(null, "Document unsaved.", "Save before closing?", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (option == JOptionPane.YES_OPTION) { saveAs.doClick(); tabPane.removeTabAt(getSelectedTab()); } else if (option == JOptionPane.CANCEL_OPTION) { return; } else tabPane.removeTabAt(getSelectedTab()); } else tabPane.removeTabAt(getSelectedTab()); } }}); cut.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { if (getSelectedTab() != -1) { ((NotepadPanel) (tabPane.getComponentAt(getSelectedTab()))).getTextArea().cut(); } }}); copy.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { if (getSelectedTab() != -1) { ((NotepadPanel) (tabPane.getComponentAt(getSelectedTab()))).getTextArea().copy(); } }}); selectAll.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { ((NotepadPanel) (tabPane.getComponentAt(getSelectedTab()))).getTextArea().selectAll(); }}); /* UIManager.put("TabbedPane.selected",new java.awt.Color(150, 150, 255)); javax.swing.SwingUtilities.updateComponentTreeUI(tabPane); */ //pth = new PasteTransferHandler(); paste.addActionListener(( (NotepadPanel) (tabPane.getComponentAt(getSelectedTab()))).getTextArea().getTransferHandler().getPasteAction()); exit.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int option = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?", "Exit?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (option == JOptionPane.YES_OPTION) { dispose(); } }}); format = new JMenu("Format"); menuBar.add(format); font = new JMenuItem("Font"); format.add(font); format.addSeparator(); help = new JMenu("Help"); menuBar.add(help); help2 = new JMenuItem("Help", KeyEvent.VK_F1); help2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)); help.add(help2); help.addSeparator(); about = new JMenuItem("About"); help.add(about); help.addSeparator(); newDocument.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { NotepadPanel temp = new NotepadPanel(); tabPane.add(temp, tabPane.getTabCount()-2); tabPane.setTitleAt(tabPane.getTabCount()-2, "Untitled Document " + documentCount); tabPane.setTabComponentAt(tabPane.getTabCount()-2, new components.ButtonTabComponent(tabPane, temp)); documentCount++; tabPane.setBackgroundAt(tabPane.getTabCount()-2, java.awt.Color.GREEN); }}); load.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int option = openFileChooser.showOpenDialog(null); Scanner s = null; File f = openFileChooser.getSelectedFile(); if ( option == JFileChooser.APPROVE_OPTION) { try { s = new Scanner(f); } catch(NullPointerException npe) { return; } catch(FileNotFoundException fnfe) { JOptionPane.showMessageDialog(null, "File not found.", "Could not open file.", JOptionPane.ERROR_MESSAGE); return; } String readin = ""; while (s.hasNext()) { readin = readin + s.nextLine() + "\n"; } s.close(); NotepadPanel temp = new NotepadPanel(f); tabPane.addTab(f.getName(), temp); tabPane.setTabComponentAt(tabPane.getTabCount()-2, new components.ButtonTabComponent(tabPane, temp)); ((NotepadPanel) (tabPane.getComponentAt(tabPane.getTabCount() -2))).getTextArea().setText(readin); tabPane.setSelectedIndex(tabPane.getTabCount() -2); ((NotepadPanel) (tabPane.getComponentAt(tabPane.getTabCount() -2))).setDocumentFile(f); tabPane.setBackgroundAt(tabPane.getTabCount()-2, java.awt.Color.GREEN); } }}); findReplace = new JMenuItem("Find/Replace", KeyEvent.VK_F); findReplace.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK)); edit.add(findReplace); edit.addSeparator(); dateTimeStamp = new JMenuItem("Time/Date", KeyEvent.VK_F5); dateTimeStamp.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0)); edit.add(dateTimeStamp); edit.addSeparator(); lines = new JMenu("Insert Lines"); edit.add(lines); edit.addSeparator(); dashedLine = new JMenuItem("Dashed line"); dashedLine.setToolTipText("--------"); lines.add(dashedLine); lines.addSeparator(); dashedLine.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { }}); solidLine = new JMenuItem("Solid line"); solidLine.setToolTipText("__________"); solidLine.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { getContentAt(getSelectedTab()).getTextArea().insert("_______________________________________________________________________________________________________________________________________", getContentAt(getSelectedTab()).getTextArea().getCaretPosition()); }}); lines.add(solidLine); lines.addSeparator(); starLine = new JMenuItem("Starred line"); starLine.setToolTipText("************"); starLine.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { getContentAt(getSelectedTab()).getTextArea().insert("***************************************************************************************************************************************", getContentAt(getSelectedTab()).getTextArea().getCaretPosition()); }}); lines.add(starLine); lines.addSeparator(); dotLine = new JMenuItem("Dotted line"); dotLine.setToolTipText(".............."); dotLine.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { getContentAt(getSelectedTab()).getTextArea().insert(".......................................................................................................................................", getContentAt(getSelectedTab()).getTextArea().getCaretPosition()); }}); lines.add(dotLine); lines.addSeparator(); tildaLine = new JMenuItem("Tilda line"); tildaLine.setToolTipText("~~~~~~~~~~~~"); tildaLine.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { getContentAt(getSelectedTab()).getTextArea().insert("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", getContentAt(getSelectedTab()).getTextArea().getCaretPosition()); }}); lines.add(tildaLine); lines.addSeparator(); dashedLine.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { getContentAt(getSelectedTab()).getTextArea().insert("---------------------------------------------------------------------------------------------------------------------------------------", getContentAt(getSelectedTab()).getTextArea().getCaretPosition()); }}); print.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { try { ((NotepadPanel) (tabPane.getComponentAt(getSelectedTab()))).getTextArea().print(new java.text.MessageFormat("mongoose"), new java.text.MessageFormat("Cobra")); } catch(java.awt.print.PrinterException pe) { JOptionPane.showMessageDialog(null, "Could not print.", "There was an error in printing this file.", JOptionPane.ERROR_MESSAGE); } }}); saveAs.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int option = saveFileChooser.showSaveDialog(null); File f = saveFileChooser.getSelectedFile(); if (option == JFileChooser.APPROVE_OPTION) { if (f.exists()) { int option2 = JOptionPane.showConfirmDialog(null, "File " + f.getName() + " exists.", "Overwrite?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (option2 == JOptionPane.YES_OPTION) { } else { return; } } writeToFile( f, ((NotepadPanel) (tabPane.getComponentAt(getSelectedTab()))).getTextArea()); tabPane.setTitleAt(getSelectedTab(), f.getName()); ((NotepadPanel) (tabPane.getComponentAt(getSelectedTab()))).setDocumentFile(f); } }}); save.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { if (((NotepadPanel) (tabPane.getComponentAt(getSelectedTab()))).isUntitledDocument()) saveAs.doClick(); else { writeToFile( ((NotepadPanel) (tabPane.getComponentAt(getSelectedTab()))).getDocumentFile() , ((NotepadPanel) (tabPane.getComponentAt(getSelectedTab()))).getTextArea()); } }}); findReplace.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { FindAndReplace.getInstance( ((NotepadPanel) (tabPane.getComponentAt(getSelectedTab()))).getTextArea()).setVisible(true); }}); font.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { }}); saveButton.addActionListener(save.getActionListeners()[0]); loadButton.addActionListener(load.getActionListeners()[0]); printButton.addActionListener(print.getActionListeners()[0]); saveButton.setToolTipText("Save"); loadButton.setToolTipText("Open"); printButton.setToolTipText("Print"); boldButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int bold2 = 0; if (bold == true) { bold = false; boldButton.setBackground(new Color(238, 238, 238)); } else { bold = true; bold2 = Font.BOLD; boldButton.setBackground(new Color(225, 225, 0)); } int italic2 = 0; if (italic == true) italic2 = Font.ITALIC; int type = bold2 + italic2; javax.swing.JTextArea temp = getContentAt(getSelectedTab()).getTextArea(); temp.setFont(new Font(temp.getFont().getName(), type, temp.getFont().getSize())); }}); italicButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int bold2 = 0; int italic2 = 0; if (italic == true) { italic = false; italicButton.setBackground(new Color(238, 238, 238)); } else { italic = true; italic2 = Font.ITALIC; italicButton.setBackground(new Color(225, 225, 0)); } if (bold == true) bold2 = Font.BOLD; int type = bold2 + italic2; javax.swing.JTextArea temp = getContentAt(getSelectedTab()).getTextArea(); temp.setFont(new Font(temp.getFont().getName(), type, temp.getFont().getSize())); }}); cutButton.addActionListener(cut.getActionListeners()[0]); help2.setIcon(new javax.swing.ImageIcon("./help.jpg")); paste.setIcon(new javax.swing.ImageIcon("./paste.jpg")); pasteButton.addActionListener(paste.getActionListeners()[0]); copy.setIcon(new javax.swing.ImageIcon("./copy.jpg")); copyButton.addActionListener(copy.getActionListeners()[0]); textAreaColor = new JMenuItem("Set text area color"); format.add(textAreaColor); format.addSeparator(); format.add(textColor); textAreaColor.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { Color selected = null; selected = JColorChooser.showDialog(null, "Choose a color", Color.WHITE); if (selected == null) return; if (selected.getTransparency() > 0) selected = new Color(selected.getRed(), selected.getGreen(), selected.getBlue()); getContentAt(getSelectedTab()).getTextArea().setBackground(selected); }}); findReplace.setIcon(new javax.swing.ImageIcon("./search.gif")); newDocument.setIcon(new javax.swing.ImageIcon("./document.gif")); textColor.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { Color selected = null; selected = JColorChooser.showDialog(null, "Choose a color", Color.WHITE); if (selected == null) return; if (selected.getTransparency() > 0) selected = new Color(selected.getRed(), selected.getGreen(), selected.getBlue()); getContentAt(getSelectedTab()).getTextArea().setForeground(selected); }}); undo.setIcon(new javax.swing.ImageIcon("./undo.gif")); setIconImage(new javax.swing.ImageIcon("./notepad.gif").getImage()); toolBar.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1)); redo.setIcon(new javax.swing.ImageIcon("./redo.gif")); wordCount.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { wc = WordCounter.getInstance( getContentAt(getSelectedTab()).getTextArea().getText()); wc.showCountDialog(); }}); dateTimeStamp.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { Calendar cal = Calendar.getInstance(); int hour = cal.get(Calendar.HOUR); int amPM = cal.get(Calendar.AM_PM); String amPM2 = ""; if (amPM == Calendar.AM) amPM2 = "a.m."; else amPM2 = "p.m."; int minute = cal.get(Calendar.MINUTE); String minute2 = ""; if (minute < 10) minute2 = "0" + minute; else minute2 = new Integer(minute).toString(); int month = cal.get(Calendar.MONTH); String month2 = ""; if (month < 10) month2 = "0" + month; else month2 = new Integer(month).toString(); int day = cal.get(Calendar.DAY_OF_MONTH); String day2 = ""; if (day < 10) day2 = "0" + day; else day2 = new Integer(day).toString(); String timeStamp = hour + ":" + minute2 + " " + amPM2 + " " + month2 + "/" + day2 + "/" + cal.get(Calendar.YEAR); getContentAt(getSelectedTab()).getTextArea().insert(timeStamp, getContentAt(getSelectedTab()).getTextArea().getCaretPosition()); } }); saveAll.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int originalSelected = getSelectedTab(); for (int i =0; i < tabPane.getTabCount()-1; i++) { tabPane.setSelectedIndex(i); save.doClick(); } tabPane.setSelectedIndex(originalSelected); }}); tabPane.addContainerListener( new java.awt.event.ContainerListener() { public void componentRemoved(java.awt.event.ContainerEvent e) { } public void componentAdded(java.awt.event.ContainerEvent e) { if (tabPane.getTabCount() >=2) { if (! (tabPane.getComponentAt(tabPane.getTabCount()-1) instanceof javax.swing.JLabel)) { for (int i =0; i < tabPane.getTabCount(); i++) { if (tabPane.getComponentAt(i) instanceof javax.swing.JLabel) { tabPane.removeTabAt(i); tabPane.addTab("+", new javax.swing.JLabel("Tab 1")); tabPane.setToolTipTextAt(tabPane.getTabCount()-1, "Add New Tab"); break; } } } } for (int i = 0; i < tabPane.getTabCount()-1; i++) { tabPane.setSelectedIndex(i); tabPane.setTabComponentAt(i, new components.ButtonTabComponent(tabPane, getContentAt(getSelectedTab()))); tabPane.setBackgroundAt(i, java.awt.Color.GREEN); } } }); searchAndFindButton.setIcon(findReplace.getIcon()); searchAndFindButton.addActionListener(findReplace.getActionListeners()[0]); searchAndFindButton.setToolTipText("Find/Replace"); toolBar.setBackground(new Color(30, 40, 156)); //PopupJInternalFrame pjif = new PopupJInternalFrame(1); popoutTabHolder = new JDesktopPane(); setLayeredPane(popoutTabHolder); popoutTabHolder.add(menuBar); setContentPane(new JScrollPane(contentPane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)); //popoutTabHolder.add(pjif);pjif.setVisible(true); /* try { pjif.setSelected(true); } catch (java.beans.PropertyVetoException e2) {} pjif.setContentPane(new NotepadPanel()); */ restore.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { createNewPopupFrame(getSelectedTab()); }}); } NotePadFrame(NotepadPanel npp) { this(); tabPane.removeTabAt(0); tabPane.removeTabAt(0); if (npp.getDocumentFile() != null) { tabPane.addTab(npp.getDocumentFile().getName(), npp); } else tabPane.addTab("Untitled Document", npp); setDocumentCount(1); javax.swing.JLabel newTabLabel = new javax.swing.JLabel("tab 1"); tabPane.addTab("+", newTabLabel); tabPane.setToolTipTextAt(tabPane.getTabCount()-1, "Add New Tab"); } private void setDocumentCount(int documentCount) { this.documentCount = documentCount; } private int getDocumentCount() { return documentCount; } // private method that sets the value of the index of the selected tab into selectedTab private void setSelectedTab(int selectedTab) { this.selectedTab = selectedTab; } // returns the index of the selected tab. Useful for closing tabs and other actions // that would require the knowledge of the index of the currently selected tab private int getSelectedTab() { return selectedTab; } /* This was required because apparently TransferHandler has all of its constructors as "protected" */ private class PasteTransferHandler extends TransferHandler { public PasteTransferHandler() { super(); } } public void windowDeactivated(WindowEvent e) { } public void windowActivated(WindowEvent e) { } public void windowOpened(WindowEvent e) { } public void windowClosing(WindowEvent e) { int option = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?", "Exit?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); boolean killProgram = true; if (option == JOptionPane.YES_OPTION) { int k = tabPane.getTabCount(); for (int i =0; i < k; i++) { if (k >= tabPane.getTabCount()) { k = tabPane.getTabCount(); } if (((NotepadPanel) (tabPane.getComponentAt(i))).isUntitledDocument()) { System.out.println("Kill program here: " + killProgram); int option2 = JOptionPane.showConfirmDialog(null, "Document at tab " + (i+1) + " is unsaved.", "Do you want to save it?", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (option2 == JOptionPane.YES_OPTION) { tabPane.setSelectedIndex(i); saveAs.doClick(); tabPane.removeTabAt(i); } else if (option2 == JOptionPane.NO_OPTION) { tabPane.removeTabAt(i); } else { killProgram = false; } System.out.println(tabPane.getTabCount()); } System.out.println("Kill program: " + killProgram); } System.out.println("Tab count now: " + tabPane.getTabCount()); System.out.println("Kill program: " + killProgram); if (tabPane.getTabCount() == 0) killProgram = true; else killProgram = false; if (killProgram == true) System.exit(0); } } public void windowClosed(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowIconified(WindowEvent e) { } private String readTextFromFile(File f) { Scanner s = null; String readin = ""; try { s = new Scanner(f); } catch(NullPointerException npe) { } catch(FileNotFoundException fnfe) { //JOptionPane.showMessageDialog(null, "File not found.", "Could not open selected file.", JOptionPane.ERROR_MESSAGE); return null; } while (s.hasNext()) { readin = readin + s.nextLine() + "\n"; } s.close(); return readin; } private void writeToFile(File f, javax.swing.JTextArea area) { try ( java.io.BufferedWriter fileOut = new java.io.BufferedWriter(new java.io.FileWriter(f))) { area.write(fileOut); } catch (java.io.IOException ioe) { ioe.printStackTrace(); } } private NotepadPanel getContentAt(int index) { return (((NotepadPanel) (tabPane.getComponentAt(index)))); } private void addTab() { } private void exit() { } private void setHeader(String header) { this.header = header; } private String getHeader() { return header; } private void setFooter(String footer) { this.footer = footer; } private String getFooter() { return footer; } private class PopupJInternalFrame extends JInternalFrame implements InternalFrameListener { private JMenuBar mb; private JMenu file, edit, format; private JMenuItem save, saveAs, exit, print, pageSetup, wordCount; private int index; public PopupJInternalFrame ( int index) { super(tabPane.getTitleAt(index), true, true, true, true); this.index = index; setTitle(tabPane.getTitleAt(index)); addInternalFrameListener(this); setSize(300, 300); setLocation(100, 100); mb = new JMenuBar(); setJMenuBar(mb); file = new JMenu("File"); mb.add(file); edit = new JMenu("Edít"); format = new JMenu("Format"); mb.add(edit); mb.add(format); save = new JMenuItem("Save"); file.add(save); saveAs = new JMenuItem("Save As"); file.add(saveAs); file.addSeparator(); print = new JMenuItem("Print"); file.add(print); file.addSeparator(); pageSetup = new JMenuItem("Page Setup"); file.add(pageSetup); file.addSeparator(); wordCount = new JMenuItem("Word Count"); file.add(wordCount); file.addSeparator(); exit = new JMenuItem("Close"); file.add(exit); file.addSeparator(); setVisible(true); setContentPane((NotepadPanel) (tabPane.getComponentAt(index))); } public void internalFrameDeactivated(InternalFrameEvent e) { } public void internalFrameActivated(InternalFrameEvent e) { } public void internalFrameDeiconified(InternalFrameEvent e) { System.out.println("Maximized"); } public void internalFrameIconified(InternalFrameEvent e) { System.out.println("Minimized"); NotepadPanel npp = (NotepadPanel) (tabPane.getComponentAt(index)); tabPane.insertTab(getTitle(), null, npp, null, tabPane.getTabCount()-1); tabPane.setTabComponentAt(tabPane.getTabCount()-1, new components.ButtonTabComponent(tabPane, npp)); javax.swing.JLabel newTabLabel = new javax.swing.JLabel("tab" + 1); for (int i=0; i < tabPane.getTabCount(); i++) { if (tabPane.getTitleAt(i).equals("+")) { tabPane.removeTabAt(i); break; } } tabPane.addTab("+", newTabLabel); tabPane.setToolTipTextAt(tabPane.getTabCount()-1, "Add New Tab"); } public void internalFrameClosed(InternalFrameEvent e) { System.out.println("Closed"); } public void internalFrameClosing(InternalFrameEvent e) { } public void internalFrameOpened(InternalFrameEvent e) { } } private void closeTab(int tab) { } private void createNewPopupFrame(int index) { if (index != tabPane.getTabCount() -1) { PopupJInternalFrame pif = new PopupJInternalFrame(index); popoutTabHolder.add(pif); try { pif.setSelected(true); } catch(java.beans.PropertyVetoException pve) { } tabPane.setSelectedIndex(index-1); } } }
package gui; import javax.swing.JTextArea; import javax.swing.JScrollPane; import javax.swing.JPanel; import java.awt.BorderLayout; import javax.swing.event.CaretListener; import javax.swing.event.CaretEvent; import javax.swing.JLabel; import java.awt.PopupMenu; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import javax.swing.JMenuItem; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.MenuShortcut; import javax.swing.BorderFactory; import java.awt.Color; import javax.swing.TransferHandler; import javax.swing.text.DefaultStyledDocument; import javax.swing.JTabbedPane; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import java.awt.Graphics; import javax.swing.JButton; import java.io.File; import javax.swing.event.DocumentListener; import javax.swing.event.DocumentEvent; import javax.swing.event.UndoableEditListener; import javax.swing.event.UndoableEditEvent; import javax.swing.JCheckBoxMenuItem; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; import java.awt.Graphics; import java.awt.Graphics2D; import gui.utilities.WordCounter; public class NotepadPanel extends JPanel implements CaretListener, DocumentListener, UndoableEditListener { private JTextArea textArea; private JScrollPane textScrollPane; private File documentFile; private JPanel infoPanel; private JLabel lineCountLabel; private JLabel rowCaretNumLabel; private JLabel colCaretNumLabel; private boolean changed; private DefaultStyledDocument dsd; private PageSetup ps; private JCheckBoxMenuItem wrapLine, wrapWord; private WordCounter wc; public NotepadPanel() { super(new BorderLayout()); changed = false; textArea = new JTextArea(47,50); wc = WordCounter.getInstance(); textScrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); lineCountLabel = new JLabel("Line count: " + String.valueOf(textArea.getLineCount())); rowCaretNumLabel = new JLabel(); colCaretNumLabel = new JLabel(); lineCountLabel.setFont(new java.awt.Font("Verdana",java.awt.Font.BOLD + java.awt.Font.ITALIC, 12 )); rowCaretNumLabel.setFont(new java.awt.Font("Verdana",java.awt.Font.BOLD + java.awt.Font.ITALIC, 12)); colCaretNumLabel.setFont(new java.awt.Font("Verdana",java.awt.Font.BOLD + java.awt.Font.ITALIC, 12)); textArea.addCaretListener(this); dsd = new DefaultStyledDocument(); textArea.setDocument(dsd); textArea.getDocument().addDocumentListener(this); dsd.addUndoableEditListener(this); add(textScrollPane, BorderLayout.CENTER); infoPanel = new JPanel(new BorderLayout()); add(infoPanel, BorderLayout.SOUTH); infoPanel.add(lineCountLabel, BorderLayout.WEST); infoPanel.add(rowCaretNumLabel, BorderLayout.CENTER); infoPanel.add(colCaretNumLabel, BorderLayout.EAST); infoPanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(new Color(190, 205, 230), 2) , BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED, new Color(190, 210, 220), new Color(220, 210, 200)) )); textArea.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(new Color(190, 205, 230), 2) , BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED, new Color(190, 210, 240), new Color(220, 210, 200)) )); infoPanel.setBackground(new Color(180, 190, 205)); gui.utilities.ComponentFormatter.addPopupMenu(textArea); wrapWord = new JCheckBoxMenuItem("Word Wrap"); wrapWord.addItemListener( new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) textArea.setWrapStyleWord(true); else textArea.setWrapStyleWord(false); } }); textArea.getComponentPopupMenu().add(wrapWord); wrapLine = new JCheckBoxMenuItem("Line Wrap"); wrapLine.addItemListener( new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) textArea.setLineWrap(true); else textArea.setLineWrap(false); } }); textArea.getComponentPopupMenu().add(wrapLine); textArea.setVisible(true); textArea.setMargin(new java.awt.Insets(2, 2, 2, 2)); textArea.addMouseListener( new MouseListener() { public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) { // right click if (e.getButton() == MouseEvent.BUTTON3) textArea.getComponentPopupMenu().setVisible(true); } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mousePressed(MouseEvent e) { } }); textArea.setFont(textArea.getFont().deriveFont(20f)); ps = PageSetup.getInstance(); } public NotepadPanel(java.io.File file) { this(); java.util.Scanner s = null; String readin = ""; try { s = new java.util.Scanner(file); } catch(NullPointerException npe) { } catch(java.io.FileNotFoundException fnfe) { //JOptionPane.showMessageDialog(null, "File not found.", "Could not open selected file.", JOptionPane.ERROR_MESSAGE); return; } while (s.hasNext()) { readin = readin + s.nextLine() + "\n"; } s.close(); textArea.setText(readin); } /** returns the text area * <blockquote><pre> * returns - the JTextArea object of the notepad. * </pre></blockquote> **/ public JTextArea getTextArea() { return textArea; } /** Sets the file for the document.. * <blockquote><pre> * params - * file - the file for the document to be set. * </pre></blockquote> **/ public void setDocumentFile(File documentFile) { this.documentFile = documentFile; } /** Returns the document file. * returns - the document file **/ public File getDocumentFile() { return documentFile; } /** Checks to see if the document is untitled. * <blockquote><pre> * returns - true if documentFile is null, false otherwise. * </pre></blockquote> **/ public boolean isUntitledDocument() { return (documentFile == null); } public void caretUpdate(CaretEvent e) { try { rowCaretNumLabel.setText(" Row: " + String.valueOf((int) ( textArea.getCaret().getMagicCaretPosition().getX() ))); colCaretNumLabel.setText("Column: " + String.valueOf((int) ( textArea.getCaret().getMagicCaretPosition().getY() ) )); lineCountLabel.setText("Line count: " + String.valueOf(textArea.getLineCount())); } catch(NullPointerException npe) { //System.out.println("Caret not visible."); } } /** Checks to see if the document has been changed since created or since last saved. * <blockquote><pre> * returns - true if documentFile is document has been changed, false otherwise. * </pre></blockquote> **/ public boolean isChanged() { return changed; } /** Sets whether the document has been changed since last saved or since creation. * <blockquote><pre> * params * changed- whether or not the document has been changed since last saved or created. * </pre></blockquote> **/ public void setChanged(boolean changed) { this.changed = changed; } public void changedUpdate(DocumentEvent e) { changed = false; } public void removeUpdate(DocumentEvent e) { changed = false; } public void insertUpdate(DocumentEvent e) { changed = false; } public void undoableEditHappened(UndoableEditEvent e) { } /** Gets the page setup of this NotepadPanel * <blockquote><pre> * returns - The PageSetup object associated with this NotepadPanel * </pre></blockquote> **/ public PageSetup getPageSetup() { return ps; } /** Gets the word counter of this NotepadPanel * <blockquote><pre> * returns - The WordCounter object associated with this NotepadPanel * </pre></blockquote> **/ public WordCounter getWordCount() { return wc; } }
package gui.utilities; import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; public class WordCounter { private static long words; private static WordCounter instance; private WordCounter() { words = 0L; } public static WordCounter getInstance() { if (instance == null) instance = new WordCounter(); return instance; } public static WordCounter getInstance(String text) { if (instance == null) { instance = new WordCounter(); instance.setCount(count(text)); } return instance; } public static WordCounter getInstance(File f) { if (instance == null) { Scanner temp = null; try { temp = new Scanner(f); } catch(FileNotFoundException fnfe) { javax.swing.JOptionPane.showMessageDialog(null, fnfe.toString(), f.getName(), javax.swing.JOptionPane.ERROR_MESSAGE); } catch(NullPointerException npe) { } String temp2 = ""; while (temp.hasNext()) { String temp3 = temp.nextLine(); temp2 = temp2 + temp3; } instance = new WordCounter(); instance.setCount(count(temp2)); } return instance; } private void setCount(long words2) { words = words2; } public long getCount() { return words; } public void showCountDialog() { javax.swing.JOptionPane.showMessageDialog(null, "There are " + getCount() + " words in this document.", "Word Count", javax.swing.JOptionPane.INFORMATION_MESSAGE); } private static long count(String text) { Scanner temp = new Scanner(text); long temp3 = 0L; String temp2 = ""; while (temp.hasNext()) { temp2 = temp.next(); temp3++; } return temp3; } }
package gui.utilities; import javax.swing.JPopupMenu; import javax.swing.JMenuItem; import javax.swing.BorderFactory; import java.awt.Color; import javax.swing.text.JTextComponent; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class ComponentFormatter { public static void addPopupMenu(final JTextComponent textComponent) { JPopupMenu popup = new JPopupMenu(); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { textComponent.copy(); }}); JMenuItem cut = new JMenuItem("Cut"); cut.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { textComponent.cut(); }}); JMenuItem paste = new JMenuItem(new javax.swing.text.DefaultEditorKit.PasteAction()); paste.setText("Paste"); JMenuItem selectAll = new JMenuItem("Select all"); selectAll.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { textComponent.selectAll(); }}); popup.add(cut); popup.add(copy); popup.add(paste); popup.add(selectAll); textComponent.setComponentPopupMenu(popup); } }
/* * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle or the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package components; import javax.swing.*; import javax.swing.*; import javax.swing.plaf.basic.BasicButtonUI; import java.awt.*; import java.awt.event.*; import gui.NotepadPanel; /** * Component to be used as tabComponent; * Contains a JLabel to show the text and * a JButton to close the tab it belongs to */ public class ButtonTabComponent extends JPanel { private final DnDTabbedPane pane; private TabButton button; private final NotepadPanel panel; public ButtonTabComponent(final DnDTabbedPane pane, final NotepadPanel panel) { //unset default FlowLayout' gaps super(new FlowLayout(FlowLayout.LEFT, 0, 0)); if (pane == null) { throw new NullPointerException("TabbedPane is null"); } this.pane = pane; this.panel = panel; 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 button = new TabButton(); add(button); //add more space to the top of the component setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0)); } public TabButton getTabButton() { return button; } public 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) { if (panel.isUntitledDocument()) { int option = JOptionPane.showConfirmDialog(null, "Document unsaved.", "Save before closing?", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (option == JOptionPane.YES_OPTION) { javax.swing.JFileChooser saveFileChooser = new javax.swing.JFileChooser("./"); int option2 = saveFileChooser.showSaveDialog(null); java.io.File f = saveFileChooser.getSelectedFile(); if (option2 == javax.swing.JFileChooser.APPROVE_OPTION) { writeToFile( f, panel.getTextArea()); pane.removeTabAt(i); } else { return; } } else if (option == JOptionPane.CANCEL_OPTION) { return; } else pane.removeTabAt(i); } else pane.removeTabAt(i); } } //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); } } }; private void writeToFile(java.io.File f, javax.swing.JTextArea area) { try ( java.io.BufferedWriter fileOut = new java.io.BufferedWriter(new java.io.FileWriter(f))) { area.write(fileOut); } catch (java.io.IOException ioe) { ioe.printStackTrace(); } } }
package gui; import javax.swing.JTabbedPane; import javax.swing.JPanel; import javax.swing.JDialog; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.BorderLayout; import javax.swing.JLabel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JTextArea; import javax.swing.BorderFactory; import gui.utilities.ComponentFormatter; public class FindAndReplace extends JDialog { private JTabbedPane tabPane; private JPanel panel; private FindPanel fp; private ReplacePanel rp; private JTextArea ta; private static FindAndReplace instance; private FindAndReplace(JTextArea ta) { setTitle("Find"); this.ta = ta; panel = new JPanel(); fp = new FindPanel(); rp = new ReplacePanel(); setContentPane(panel); setVisible(true); tabPane = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT); tabPane.addTab("Find", fp); tabPane.addTab("Replace", rp); panel.setLayout(new BorderLayout()); panel.add(tabPane, BorderLayout.PAGE_START); //panel.add(fp, BorderLayout.NORTH); panel.setVisible(true); tabPane.setVisible(true); System.out.println(tabPane.isVisible()); setSize(300, 152); setResizable(false); } public static FindAndReplace getInstance(JTextArea ta) { if (instance == null) instance = new FindAndReplace(ta); return instance; } private class FindPanel extends JPanel { private javax.swing.JTextField findField; private JPanel topPanel; private JPanel bottomPanel; private JLabel findLabel; private JButton ok, findNext, cancel; public FindPanel() { setVisible(true); findLabel = new JLabel("<html><B> Find: </B></html>"); findField = new javax.swing.JTextField(20); ComponentFormatter.addPopupMenu(findField); topPanel = new JPanel(); setLayout(new BorderLayout()); topPanel.setLayout(new java.awt.FlowLayout()); topPanel. setBorder(BorderFactory.createLineBorder(java.awt.Color.BLACK, 1, true)); topPanel.add(findLabel); topPanel.add(findField); bottomPanel = new JPanel(); ok = new JButton("Ok"); findNext = new JButton("Find Next"); cancel = new JButton("Cancel"); bottomPanel.setLayout(new java.awt.FlowLayout()); bottomPanel. setBorder(BorderFactory.createLineBorder(java.awt.Color.BLACK, 1, true)); bottomPanel.add(ok); bottomPanel.add(findNext); bottomPanel.add(cancel); add(topPanel, BorderLayout.NORTH); add(bottomPanel, BorderLayout.CENTER); } } private class ReplacePanel extends JPanel { private javax.swing.JTextField findField; private JPanel topPanel; private JPanel bottomPanel; private JLabel findLabel; private JButton ok, findNext, cancel; private JLabel replaceLabel; private javax.swing.JTextField replaceField; private JPanel middlePanel; public ReplacePanel() { setVisible(true); findLabel = new JLabel("<html><B> Find: </B></html>"); findField = new javax.swing.JTextField(20); ComponentFormatter.addPopupMenu(findField); topPanel = new JPanel(); setLayout(new BorderLayout()); JPanel topPanel2 = new JPanel(); topPanel2.setLayout(new BorderLayout()); topPanel.setLayout(new java.awt.FlowLayout()); topPanel.add(findLabel); topPanel.add(findField); bottomPanel = new JPanel(); ok = new JButton("Ok"); findNext = new JButton("Find Next"); cancel = new JButton("Cancel"); bottomPanel.setLayout(new java.awt.FlowLayout()); bottomPanel. setBorder(BorderFactory.createLineBorder(java.awt.Color.BLACK, 1, true)); bottomPanel.add(ok); bottomPanel.add(findNext); bottomPanel.add(cancel); middlePanel = new JPanel(); middlePanel.setLayout(new java.awt.FlowLayout()); replaceField = new JTextField(20); ComponentFormatter.addPopupMenu(replaceField); replaceLabel = new JLabel("<html><B> Replace: </B></html>"); middlePanel.add(replaceLabel); middlePanel.add(replaceField); topPanel2.add(topPanel, BorderLayout.NORTH); topPanel2.add(middlePanel, BorderLayout.CENTER); add(topPanel2, BorderLayout.NORTH); topPanel2. setBorder(BorderFactory.createLineBorder(java.awt.Color.BLACK, 1, true)); add(bottomPanel, BorderLayout.CENTER); } } }
package components; import java.util.*; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.dnd.DropTargetListener; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.event.ActionEvent; import java.awt.dnd.DragSourceListener; import java.awt.dnd.DragSourceDragEvent; import java.awt.dnd.DragSourceEvent; import java.awt.dnd.DragSourceDropEvent; import java.awt.dnd.*; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.DataFlavor; public class DnDTabbedPane extends JTabbedPane { private static final int LINEWIDTH = 3; private static final String NAME = "test"; private final GhostGlassPane glassPane = new GhostGlassPane(); private final Rectangle lineRect = new Rectangle(); private final Color lineColor = new Color(0, 100, 255); private int dragTabIndex = -1; public DnDTabbedPane(int position, int layout) { this(); setTabPlacement(position); setTabLayoutPolicy(layout); } private void clickArrowButton(String actionKey) { ActionMap map = getActionMap(); if(map != null) { Action action = map.get(actionKey); if (action != null && action.isEnabled()) { action.actionPerformed(new ActionEvent( this, ActionEvent.ACTION_PERFORMED, null, 0, 0)); } } } private static Rectangle rBackward = new Rectangle(); private static Rectangle rForward = new Rectangle(); private static int rwh = 20; private static int buttonsize = 30;//XXX: magic number of scroll button size private void autoScrollTest(Point glassPt) { Rectangle r = getTabAreaBounds(); int tabPlacement = getTabPlacement(); if(tabPlacement==TOP || tabPlacement==BOTTOM) { rBackward.setBounds(r.x, r.y, rwh, r.height); rForward.setBounds( r.x+r.width-rwh-buttonsize, r.y, rwh+buttonsize, r.height); } else if(tabPlacement==LEFT || tabPlacement==RIGHT) { rBackward.setBounds(r.x, r.y, r.width, rwh); rForward.setBounds( r.x, r.y+r.height-rwh-buttonsize, r.width, rwh+buttonsize); } rBackward = SwingUtilities.convertRectangle( getParent(), rBackward, glassPane); rForward = SwingUtilities.convertRectangle( getParent(), rForward, glassPane); if(rBackward.contains(glassPt)) { //System.out.println(new java.util.Date() + "Backward"); clickArrowButton("scrollTabsBackwardAction"); } else if(rForward.contains(glassPt)) { //System.out.println(new java.util.Date() + "Forward"); clickArrowButton("scrollTabsForwardAction"); } } public DnDTabbedPane() { super(); final DragSourceListener dsl = new DragSourceListener() { @Override public void dragEnter(DragSourceDragEvent e) { e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop); } @Override public void dragExit(DragSourceEvent e) { e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop); lineRect.setRect(0,0,0,0); glassPane.setPoint(new Point(-1000,-1000)); glassPane.repaint(); } @Override public void dragOver(DragSourceDragEvent e) { Point glassPt = e.getLocation(); SwingUtilities.convertPointFromScreen(glassPt, glassPane); int targetIdx = getTargetTabIndex(glassPt); //if(getTabAreaBounds().contains(tabPt) && targetIdx>=0 && if(getTabAreaBounds().contains(glassPt) && targetIdx>=0 && targetIdx!=dragTabIndex && targetIdx!=dragTabIndex+1) { e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop); glassPane.setCursor(DragSource.DefaultMoveDrop); } else{ e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop); glassPane.setCursor(DragSource.DefaultMoveNoDrop); } } @Override public void dragDropEnd(DragSourceDropEvent e) { lineRect.setRect(0,0,0,0); dragTabIndex = -1; glassPane.setVisible(false); if(hasGhost()) { glassPane.setVisible(false); glassPane.setImage(null); } } @Override public void dropActionChanged(DragSourceDragEvent e) {} }; final Transferable t = new Transferable() { private final DataFlavor FLAVOR = new DataFlavor( DataFlavor.javaJVMLocalObjectMimeType, NAME); @Override public Object getTransferData(DataFlavor flavor) { return DnDTabbedPane.this; } @Override public DataFlavor[] getTransferDataFlavors() { DataFlavor[] f = new DataFlavor[1]; f[0] = this.FLAVOR; return f; } @Override public boolean isDataFlavorSupported(DataFlavor flavor) { return flavor.getHumanPresentableName().equals(NAME); } }; final DragGestureListener dgl = new DragGestureListener() { @Override public void dragGestureRecognized(DragGestureEvent e) { if(getTabCount() <= 1) return; Point tabPt = e.getDragOrigin(); dragTabIndex = indexAtLocation(tabPt.x, tabPt.y); //"disabled tab problem". if(dragTabIndex < 0 || !isEnabledAt(dragTabIndex)) return; initGlassPane(e.getComponent(), e.getDragOrigin()); try{ e.startDrag(DragSource.DefaultMoveDrop, t, dsl); } catch(InvalidDnDOperationException idoe) { idoe.printStackTrace(); } } }; new DropTarget(glassPane, DnDConstants.ACTION_COPY_OR_MOVE, new CDropTargetListener(), true); new DragSource().createDefaultDragGestureRecognizer( this, DnDConstants.ACTION_COPY_OR_MOVE, dgl); } class CDropTargetListener implements DropTargetListener{ @Override public void dragEnter(DropTargetDragEvent e) { if(isDragAcceptable(e)) e.acceptDrag(e.getDropAction()); else e.rejectDrag(); } @Override public void dragExit(DropTargetEvent e) {} @Override public void dropActionChanged(DropTargetDragEvent e) {} private Point _glassPt = new Point(); @Override public void dragOver(final DropTargetDragEvent e) { Point glassPt = e.getLocation(); if(getTabPlacement()==JTabbedPane.TOP || getTabPlacement()==JTabbedPane.BOTTOM) { initTargetLeftRightLine(getTargetTabIndex(glassPt)); } else{ initTargetTopBottomLine(getTargetTabIndex(glassPt)); } if(hasGhost()) { glassPane.setPoint(glassPt); } if(!_glassPt.equals(glassPt)) glassPane.repaint(); _glassPt = glassPt; autoScrollTest(glassPt); } @Override public void drop(DropTargetDropEvent e) { if(isDropAcceptable(e)) { convertTab(dragTabIndex, getTargetTabIndex(e.getLocation())); e.dropComplete(true); } else{ e.dropComplete(false); } repaint(); } private boolean isDragAcceptable(DropTargetDragEvent e) { Transferable t = e.getTransferable(); if(t==null) return false; DataFlavor[] f = e.getCurrentDataFlavors(); if(t.isDataFlavorSupported(f[0]) && dragTabIndex>=0) { return true; } return false; } private boolean isDropAcceptable(DropTargetDropEvent e) { Transferable t = e.getTransferable(); if(t==null) return false; DataFlavor[] f = t.getTransferDataFlavors(); if(t.isDataFlavorSupported(f[0]) && dragTabIndex>=0) { return true; } return false; } } private boolean hasGhost = true; public void setPaintGhost(boolean flag) { hasGhost = flag; } public boolean hasGhost() { return hasGhost; } private boolean isPaintScrollArea = true; public void setPaintScrollArea(boolean flag) { isPaintScrollArea = flag; } public boolean isPaintScrollArea() { return isPaintScrollArea; } private int getTargetTabIndex(Point glassPt) { Point tabPt = SwingUtilities.convertPoint( glassPane, glassPt, DnDTabbedPane.this); boolean isTB = getTabPlacement()==JTabbedPane.TOP || getTabPlacement()==JTabbedPane.BOTTOM; for(int i=0;i < getTabCount();i++) { Rectangle r = getBoundsAt(i); if(isTB) r.setRect(r.x-r.width/2, r.y, r.width, r.height); else r.setRect(r.x, r.y-r.height/2, r.width, r.height); if(r.contains(tabPt)) return i; } Rectangle r = getBoundsAt(getTabCount()-1); if(isTB) r.setRect(r.x+r.width/2, r.y, r.width, r.height); else r.setRect(r.x, r.y+r.height/2, r.width, r.height); return r.contains(tabPt)?getTabCount():-1; } private void convertTab(int prev, int next) { if(next < 0 || prev==next) { return; } Component cmp = getComponentAt(prev); Component tab = getTabComponentAt(prev); String str = getTitleAt(prev); Icon icon = getIconAt(prev); String tip = getToolTipTextAt(prev); boolean flg = isEnabledAt(prev); int tgtindex = prev>next ? next : next-1; remove(prev); insertTab(str, icon, cmp, tip, tgtindex); setEnabledAt(tgtindex, flg); //When you drag'n'drop a disabled tab, it finishes enabled and selected. //pointed out by dlorde if(flg) setSelectedIndex(tgtindex); //I have a component in all tabs (jlabel with an X to close the tab) //and when i move a tab the component disappear. //pointed out by Daniel Dario Morales Salas setTabComponentAt(tgtindex, tab); } private void initTargetLeftRightLine(int next) { if(next < 0 || dragTabIndex==next || next-dragTabIndex==1) { lineRect.setRect(0,0,0,0); } else if(next==0) { Rectangle r = SwingUtilities.convertRectangle( this, getBoundsAt(0), glassPane); lineRect.setRect(r.x-LINEWIDTH/2,r.y,LINEWIDTH,r.height); } else{ Rectangle r = SwingUtilities.convertRectangle( this, getBoundsAt(next-1), glassPane); lineRect.setRect(r.x+r.width-LINEWIDTH/2,r.y,LINEWIDTH,r.height); } } private void initTargetTopBottomLine(int next) { if(next < 0 || dragTabIndex==next || next-dragTabIndex==1) { lineRect.setRect(0,0,0,0); } else if(next==0) { Rectangle r = SwingUtilities.convertRectangle( this, getBoundsAt(0), glassPane); lineRect.setRect(r.x,r.y-LINEWIDTH/2,r.width,LINEWIDTH); } else{ Rectangle r = SwingUtilities.convertRectangle( this, getBoundsAt(next-1), glassPane); lineRect.setRect(r.x,r.y+r.height-LINEWIDTH/2,r.width,LINEWIDTH); } } private void initGlassPane(Component c, Point tabPt) { getRootPane().setGlassPane(glassPane); if(hasGhost()) { Rectangle rect = getBoundsAt(dragTabIndex); BufferedImage image = new BufferedImage( c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics g = image.getGraphics(); c.paint(g); rect.x = rect.x < 0?0:rect.x; rect.y = rect.y < 0?0:rect.y; image = image.getSubimage(rect.x,rect.y,rect.width,rect.height); glassPane.setImage(image); } Point glassPt = SwingUtilities.convertPoint(c, tabPt, glassPane); glassPane.setPoint(glassPt); glassPane.setVisible(true); } private Rectangle getTabAreaBounds() { Rectangle tabbedRect = getBounds(); //pointed out by daryl. NullPointerException: i.e. addTab("Tab",null) //Rectangle compRect = getSelectedComponent().getBounds(); Component comp = getSelectedComponent(); int idx = 0; while(comp==null && idx < getTabCount()) comp = getComponentAt(idx++); Rectangle compRect = (comp==null)?new Rectangle():comp.getBounds(); int tabPlacement = getTabPlacement(); if(tabPlacement==TOP) { tabbedRect.height = tabbedRect.height - compRect.height; } else if(tabPlacement==BOTTOM) { tabbedRect.y = tabbedRect.y + compRect.y + compRect.height; tabbedRect.height = tabbedRect.height - compRect.height; } else if(tabPlacement==LEFT) { tabbedRect.width = tabbedRect.width - compRect.width; } else if(tabPlacement==RIGHT) { tabbedRect.x = tabbedRect.x + compRect.x + compRect.width; tabbedRect.width = tabbedRect.width - compRect.width; } tabbedRect.grow(2, 2); return tabbedRect; } class GhostGlassPane extends JPanel { private final AlphaComposite composite; private Point location = new Point(0, 0); private BufferedImage draggingGhost = null; public GhostGlassPane() { setOpaque(false); composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f); //http://bugs.sun.com/view_bug.do?bug_id=6700748 //setCursor(null); } public void setImage(BufferedImage draggingGhost) { this.draggingGhost = draggingGhost; } public void setPoint(Point location) { this.location = location; } @Override public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setComposite(composite); if(isPaintScrollArea() && getTabLayoutPolicy()==SCROLL_TAB_LAYOUT) { g2.setPaint(Color.RED); g2.fill(rBackward); g2.fill(rForward); } if(draggingGhost != null) { double xx = location.getX() - (draggingGhost.getWidth(this) /2d); double yy = location.getY() - (draggingGhost.getHeight(this)/2d); g2.drawImage(draggingGhost, (int)xx, (int)yy , null); } if(dragTabIndex>=0) { g2.setPaint(lineColor); g2.fill(lineRect); } } } }
package gui; import javax.swing.JDialog; import javax.swing.JPanel; import java.awt.BorderLayout; import javax.swing.JTextField; import javax.swing.JSpinner; import javax.swing.JCheckBox; import java.awt.event.ItemListener; import java.awt.event.ItemListener; import javax.swing.JLabel; import javax.swing.event.ChangeListener; import javax.swing.event.ChangeEvent; import java.awt.Insets; import javax.swing.BorderFactory; import javax.swing.border.TitledBorder; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class PageSetup extends JDialog { private static PageSetup instance; private JSpinner leftSpin, rightSpin, topSpin, bottomSpin; private JSpinner tabSpin; private JButton ok, cancel; private Object[] settings; private PageSetup() { JPanel contentPane = new JPanel(); contentPane.setLayout(new BorderLayout()); setContentPane(contentPane); JPanel topPanel = new JPanel(); JPanel topTopPanel = new JPanel(); JPanel bottomTopPanel = new JPanel(); topPanel.add(topTopPanel, BorderLayout.NORTH); topPanel.add(bottomTopPanel, BorderLayout.CENTER); topPanel.setLayout(new BorderLayout()); JPanel leftPanel = new JPanel(); leftPanel.setLayout(new BorderLayout()); JLabel left = new JLabel("Left"); topTopPanel.setLayout(new BorderLayout()); JLabel right = new JLabel("Right"); JPanel rightPanel = new JPanel(); rightPanel.setLayout(new BorderLayout()); topTopPanel.add(leftPanel, BorderLayout.WEST); topTopPanel.add(rightPanel, BorderLayout.EAST); leftPanel.add(left, BorderLayout.WEST); leftSpin = new JSpinner(new javax.swing.SpinnerNumberModel(1, 0, 8, 1)); leftPanel.add(leftSpin, BorderLayout.EAST); rightPanel.add(right, BorderLayout.WEST); rightSpin = new JSpinner(new javax.swing.SpinnerNumberModel(1, 0, 8, 1)); rightPanel.add(rightSpin, BorderLayout.EAST); JPanel tPanel = new JPanel(); JLabel top = new JLabel("Top"); tPanel.setLayout(new BorderLayout()); tPanel.add(top, BorderLayout.WEST); topSpin = new JSpinner(new javax.swing.SpinnerNumberModel(1, 0, 8, 1)); tPanel.add(topSpin, BorderLayout.EAST); bottomTopPanel.setLayout(new BorderLayout()); bottomTopPanel.add(tPanel, BorderLayout.WEST); JPanel bPanel = new JPanel(); JLabel bottom = new JLabel("Bottom"); bottomTopPanel.add(bPanel, BorderLayout.EAST); bPanel.setLayout(new BorderLayout()); bPanel.add(bottom, BorderLayout.WEST); bottomSpin = new JSpinner(new javax.swing.SpinnerNumberModel(1, 0, 8, 1)); bPanel.add(bottomSpin, BorderLayout.EAST); contentPane.add(topPanel, BorderLayout.NORTH); setTitle("Page Setup"); topPanel.add(topTopPanel, BorderLayout.NORTH); topPanel.add(bottomTopPanel, BorderLayout.SOUTH); JPanel bottomPanel = new JPanel(); JPanel topBottomPanel = new JPanel(); bottomPanel.setLayout(new BorderLayout()); bottomPanel.add(topBottomPanel, BorderLayout.NORTH); contentPane.add(bottomPanel, BorderLayout.CENTER); topPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED), "Margins", TitledBorder.CENTER, TitledBorder.TOP, new java.awt.Font("Times New Roman", java.awt.Font.BOLD, 12))); topBottomPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED), "Tab", TitledBorder.CENTER, TitledBorder.TOP, new java.awt.Font("Times New Roman", java.awt.Font.BOLD, 12))); JLabel tabLabel = new JLabel("Tab Size"); topBottomPanel.setLayout(new BorderLayout()); topBottomPanel.add(tabLabel, BorderLayout.WEST); tabSpin = new JSpinner(new javax.swing.SpinnerNumberModel(1, 1, 20, 1)); topBottomPanel.add(tabSpin, BorderLayout.EAST); setModal(true); setModalityType(java.awt.Dialog.ModalityType.APPLICATION_MODAL); JPanel middleBottomPanel = new JPanel(); bottomPanel.add(middleBottomPanel, BorderLayout.CENTER); middleBottomPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED), "Header and Footer", TitledBorder.CENTER, TitledBorder.TOP, new java.awt.Font("Times New Roman", java.awt.Font.BOLD, 12))); setSize(300, 500); setResizable(false); } public static PageSetup getInstance() { if (instance == null) instance = new PageSetup(); return instance; } private void setSettings(Object[] settings) { this.settings = settings; } public Object[] getSettings() { return settings; } }
package gui; public class NotePadFrameTest { public static void main(String[] args) { new NotePadFrame(); } }
The parts that might be of issue are (They are all in the NotePadFrame class.)
private class PopupJInternalFrame extends JInternalFrame implements InternalFrameListener { private JMenuBar mb; private JMenu file, edit, format; private JMenuItem save, saveAs, exit, print, pageSetup, wordCount; private int index; public PopupJInternalFrame ( int index) { super(tabPane.getTitleAt(index), true, true, true, true); this.index = index; setTitle(tabPane.getTitleAt(index)); addInternalFrameListener(this); setSize(300, 300); setLocation(100, 100); mb = new JMenuBar(); setJMenuBar(mb); file = new JMenu("File"); mb.add(file); edit = new JMenu("Edít"); format = new JMenu("Format"); mb.add(edit); mb.add(format); save = new JMenuItem("Save"); file.add(save); saveAs = new JMenuItem("Save As"); file.add(saveAs); file.addSeparator(); print = new JMenuItem("Print"); file.add(print); file.addSeparator(); pageSetup = new JMenuItem("Page Setup"); file.add(pageSetup); file.addSeparator(); wordCount = new JMenuItem("Word Count"); file.add(wordCount); file.addSeparator(); exit = new JMenuItem("Close"); file.add(exit); file.addSeparator(); setVisible(true); setContentPane((NotepadPanel) (tabPane.getComponentAt(index))); } public void internalFrameDeactivated(InternalFrameEvent e) { } public void internalFrameActivated(InternalFrameEvent e) { } public void internalFrameDeiconified(InternalFrameEvent e) { System.out.println("Maximized"); } public void internalFrameIconified(InternalFrameEvent e) { System.out.println("Minimized"); NotepadPanel npp = (NotepadPanel) (tabPane.getComponentAt(index)); tabPane.insertTab(getTitle(), null, npp, null, tabPane.getTabCount()-1); tabPane.setTabComponentAt(tabPane.getTabCount()-1, new components.ButtonTabComponent(tabPane, npp)); javax.swing.JLabel newTabLabel = new javax.swing.JLabel("tab" + 1); for (int i=0; i < tabPane.getTabCount(); i++) { if (tabPane.getTitleAt(i).equals("+")) { tabPane.removeTabAt(i); break; } } tabPane.addTab("+", newTabLabel); tabPane.setToolTipTextAt(tabPane.getTabCount()-1, "Add New Tab"); } public void internalFrameClosed(InternalFrameEvent e) { System.out.println("Closed"); } public void internalFrameClosing(InternalFrameEvent e) { } public void internalFrameOpened(InternalFrameEvent e) { } }
tabPane.addMouseListener( new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent e) { if (tabPane.getSelectedComponent() instanceof javax.swing.JLabel) { tabPopupMenu.setVisible(false); tabPane.addTab("Untitled Document " + documentCount , new NotepadPanel()); tabPane.setBackgroundAt(tabPane.getTabCount() -1, Color.GREEN); tabPane.setTabComponentAt(tabPane.getTabCount() -1, new components.ButtonTabComponent(tabPane, new NotepadPanel())); documentCount++; int count = tabPane.getTabCount(); javax.swing.JLabel newTabLabel = new javax.swing.JLabel("tab" + count); for (int i=0; i < tabPane.getTabCount(); i++) { if (tabPane.getTitleAt(i).equals("+")) { tabPane.removeTabAt(i); break; } } tabPane.addTab("+", newTabLabel); tabPane.setToolTipTextAt(tabPane.getTabCount()-1, "Add New Tab"); } } }); tabPane.addMouseListener( new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent e) { if (! (tabPane.getSelectedComponent() instanceof javax.swing.JLabel)) { tabPopupMenu.setVisible(true); } else { if (tabPopupMenu.isVisible()) tabPopupMenu.setVisible(false); } } });
private void createNewPopupFrame(int index) { if (index != tabPane.getTabCount() -1) { PopupJInternalFrame pif = new PopupJInternalFrame(index); popoutTabHolder.add(pif); try { pif.setSelected(true); } catch(java.beans.PropertyVetoException pve) { } tabPane.setSelectedIndex(index-1); } }
Also, this is another issue, how to stop the popupMenu from "sticking" the first time it comes up. (Also how to make sure it doesn't come up if you click the "+" button. I also would like it not to even show the background component if the "+" button is selected with the left click.)
tabPane.setComponentPopupMenu(tabPopupMenu);
Was I supposed to make it the component popup menu or was that a bad move and the reason it's sometimes sticking and not going away when released.
There's tons of areas.