Chuyên mục lưu trữ: LẬP TRÌNH

Creating Advanced Tabbed Notepad In Java

bắt đầu với code dưới

Introduction 
As you all know Java is the world’s most popular & powerful programming language which is plateform independant. There are many editors developed using Java that we use like Eclipse,NetBeans,Intelli-J,JEdit etc.These editors are same as notepad but with added and developed extended features.
In this article we will cover only main functions such as open, save, close, run etc but will not see how to create syntax highlighting in java.

Well, it is easy to create syntax highlighting in java using StyledDocument. You can easily find source code to create syntax highlighting in java on the internet.

We will also change the icon of tabs when document text is changed or saved, like Notepad++ provides. First design your notepad with Menus,Menu Items,ToolBars etc. Download the source code to view complete code of advanced tabbed notepad and also created jar application.

I am using JTextPane object instead of JTextArea.

It is easy to perform New & Open operations. But to perform save or edit operations first you need to get the current textpane control from the JTabbedPane after performing New or Open operations for use/perform other operations.

Let’s Start

Create the object of JList,JTabbedPane,JSplit.Add JList object & JTabbedPane object to JSplit.

Add JSplit object to the Container of the Frame.
Getting JTextPane Control from Current Tab(Selected Tab) in JTabbedPane,
  1. Get the selected index from the added JTabbedPane.
  2. Cast the component of selected index of JTabbedPane with JScrollPane(if JScrollPane added).
  3. Get the Viewport from the casted JScrollPane.
  4. Finally Cast the component of index 0 with JTextPane.
Here’s the code to get added JTextPane component from the added current Tab.
  1. int sel = _tabbedPane.getSelectedIndex();
  2. JScrollPane jscroll=(JScrollPane)_tabbedPane.getComponentAt(sel);
  3. JViewport jview=jscroll.getViewport();
  4. JTextPane textpane=(JTextPane)jview.getComponent(0);
It’s a four line of code. But you can do this only in one/two lines like this.
  1. int sel = _tabbedPane.getSelectedIndex();
  2. JTextPane textPane = (JTextPane)(((JScrollPane)_tabbedPane.getComponentAt(sel)).getViewport()).getComponent(0);
Ok Now let’s see the functions that are important. Add ActionListener to that menu item according to the actions you want.

New

This function is easy to implement just by adding new Tab & textPane to JTabbedPane.Here i am also checking if dark theme is enabled or not,if it is then set background color to components.

Here’s the code.

  1. public void File_New_Action()
  2. {
  3.     //crerate textpane object
  4.      JTextPane _textPane=new JTextPane();
  5.      _textPane.setFont(new Font(“Calibri”,Font.PLAIN,14));
  6.      if(isDarkTheme){
  7.          _textPane.setBackground(new Color(101020));
  8.          _textPane.setForeground(new Color(250250250));
  9.      }
  10.      JScrollPane jsp=new JScrollPane(_textPane);
  11.      // add key listener & Undoable edit listener to text pane
  12.      _textPane.addKeyListener(new KeyTypedAction());
  13.      _textPane.getDocument().addUndoableEditListener(_undoManager);
  14.      //add tab to _tabbedPane with control textpane
  15.      _tabbedPane.addTab(“Document “+count+” “,jsp);
  16.      //add caret listener & mouse listener to text pane
  17.      _textPane.addCaretListener(new CaretAction());
  18.      _textPane.addMouseListener(new TextPane_MouseAction());
  19.      int index=_tabbedPane.getTabCount()-1;
  20.      _tabbedPane.setSelectedIndex(index);
  21.      // set save icon to added tab
  22.      _tabbedPane.setIconAt(index, new ImageIcon(this.getClass().getResource(“resources/save.png”)));
  23.      listModel.addElement(“Document “+count+” “);
  24.     _list.setSelectedIndex(index);
  25.     //change the title
  26.      setTitle(“Tabbed Notepad in Java – [ Document “+count+” ]”);
  27.      filenameLabel.setText(“Document “+count);
  28.      count++;
  29. }
Open

This function is  the same as New function only just needs to read files. Here I am using FileDialog by setting setMultipleMode to true for getting multiple files.  Adding tab to tabbedpane as selected file name,changing title of frame etc. Once object of textPane is created then add KeyListener & UndoableListener to it.Here’s the code for open function.

  1. public void File_Open_Action()
  2. {
  3.      FileDialog fd = new FileDialog(new JFrame(), “Select File”,FileDialog.LOAD);
  4.      fd.setMultipleMode(true);
  5.      fd.show();
  6.      if (fd.getFiles()!=null)
  7.      {
  8.         File[] files=fd.getFiles();
  9.         for(File item : files)
  10.         {
  11.            String  filename = item.toString();
  12.            String file=filename;
  13.            if(filename.contains(“\\”)){
  14.                file = filename.substring(filename.lastIndexOf(“\\”) + 1);
  15.            }
  16.            else if(filename.contains(“/”)){
  17.                file = filename.substring(filename.lastIndexOf(“/”) + 1);
  18.            }
  19.            int count=_tabbedPane.getTabCount();
  20.            JTextPane _textPane=new JTextPane();
  21.            _textPane.setFont(new Font(“Calibri”,Font.PLAIN,14));
  22.            if (isDarkTheme) {
  23.                 _textPane.setBackground(new Color(101020));
  24.                 _textPane.setForeground(new Color(250250250));
  25.             }
  26.            JScrollPane jsp=new JScrollPane(_textPane);
  27.            _textPane.addKeyListener(new KeyTypedAction());
  28.             _textPane.getDocument().addUndoableEditListener(_undoManager);
  29.             _textPane.addCaretListener(new CaretAction());
  30.             _textPane.addMouseListener(new TextPane_MouseAction());
  31.            _tabbedPane.addTab(file,jsp);
  32.            _tabbedPane.setSelectedIndex(count);
  33.            _tabbedPane.setIconAt(count, new ImageIcon(this.getClass().getResource(“resources/save.png”)));
  34.            listModel.addElement(file);
  35.            _list.setSelectedIndex(count);
  36.            setTitle(“Tabbed Notepad in Java – [ “+file+” ]”);
  37.            filenameLabel.setText(filename);
  38.            filesHoldListModel.addElement(filename);
  39.            BufferedReader d;
  40.            StringBuffer sb = new StringBuffer();
  41.            try
  42.             {
  43.               d = new BufferedReader(new FileReader(filename));
  44.               String line;
  45.               while((line=d.readLine())!=null)
  46.                        sb.append(line + “\n”);
  47.                        _textPane.setText(sb.toString());
  48.               d.close();
  49.             }
  50.            catch(FileNotFoundException fe)
  51.             {
  52.                System.out.println(“File not Found”);
  53.             }
  54.              catch(IOException ioe){}
  55.               _textPane.requestFocus();
  56.            }
  57.        }
  58. }

Save All

Well it is easy to implement Save As & Save function.Here we will see save all function. It is easy to implement this function. Use for loop from 0 to the maximimum index of tabbedpane & set that to the selected index of tabbedpane. Get the filename from added filenameLabel & save that file by getting the current textpane from current tab. To identitfy the full filename path, I have created the list filesHoldList and set the fullfilename path to the filenameLabel which is added to the statusStrip for saving the document.

Here’s the code.

  1. public void File_SaveAll_Action()
  2. {
  3.     if (_tabbedPane.getTabCount() > 0)
  4.     {
  5.         int maxindex = _tabbedPane.getTabCount() – 1;
  6.         for (int i = 0; i <= maxindex; i++)
  7.         {
  8.             _tabbedPane.setSelectedIndex(i);
  9.             String filename = filenameLabel.getText();
  10.             int sel = _tabbedPane.getSelectedIndex();
  11.             JTextPane textPane = (JTextPane) (((JScrollPane) _tabbedPane.getComponentAt(sel)).getViewport()).getComponent(0);
  12.             if (filename.contains(“\\”)||filename.contains(“/”))
  13.             {
  14.                 File f = new File(filename);
  15.                 if (f.exists())
  16.                 {
  17.                     try
  18.                     {
  19.                         DataOutputStream d = new DataOutputStream(new FileOutputStream(filename));
  20.                         String line = textPane.getText();
  21.                         d.writeBytes(line);
  22.                         d.close();
  23.                         String tabtext = _tabbedPane.getTitleAt(sel);
  24.                         if (tabtext.contains(“*”)) {
  25.                             tabtext = tabtext.replace(“*”“”);
  26.                             _tabbedPane.setTitleAt(sel, tabtext);
  27.                             setTitle(“Tabbed Notepad in Java – [ “ + tabtext + ” ]”);
  28.                             _tabbedPane.setIconAt(sel, new ImageIcon(this.getClass().getResource(“resources/save.png”)));
  29.                         }
  30.                     }
  31.                     catch (Exception ex)
  32.                     {
  33.                         System.out.println(“File not found”);
  34.                     }
  35.                     textPane.requestFocus();
  36.                 }
  37.             }
  38.         }
  39.     }
  40. }

Close

This function is nothing but removing selected tab from tabbedpane. But before removing tab you must display a dialog box for saving modified changes before closing. If none of the document is modified then remove that tab otherwise show dialog for saving. Download the source code to view CloseAll function code.

Here’s the code.

  1. public void File_Close_Action()
  2. {
  3.     if (_tabbedPane.getTabCount() > 0)
  4.     {
  5.         int sel = _tabbedPane.getSelectedIndex();
  6.         String tabtext = _tabbedPane.getTitleAt(sel);
  7.         if (tabtext.contains(“*”))
  8.         {
  9.             int n = JOptionPane.showConfirmDialog(null“Do you want to save “ + tabtext + ” before close ?”,
  10.                     “Save or Not”, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
  11.             tabtext.replace(“*”“”);
  12.             if (n == 0)
  13.             {
  14.                 String filename = filenameLabel.getText();
  15.                 JTextPane textPane = (JTextPane) (((JScrollPane) _tabbedPane.getComponentAt(sel)).getViewport()).getComponent(0);
  16.                 if (filename.contains(“\\”)||filename.contains(“/”))
  17.                 {
  18.                     File_Save_Action();
  19.                     _tabbedPane.remove(sel);
  20.                     listModel.removeAllElements();
  21.                     //adding all elements to list after removing the tab
  22.                     for (int i = 0; i < _tabbedPane.getTabCount(); i++)
  23.                     {
  24.                         String item = _tabbedPane.getTitleAt(i);
  25.                         if (item.contains(“*”))
  26.                         {
  27.                             item = item.replace(“*”“”).trim();
  28.                         }
  29.                         listModel.addElement(item);
  30.                     }
  31.                     _list.setSelectedIndex(_tabbedPane.getTabCount()-1);
  32.                     rowLabel.setText(“Row :”);
  33.                     colLabel.setText(“Col :”);
  34.                     if(_tabbedPane.getTabCount()==0)
  35.                     {
  36.                         setTitle(“Tabbed Notepad in Java”);
  37.                         filenameLabel.setText(“”);
  38.                         rowLabel.setText(“Row :”);
  39.                         colLabel.setText(“Col :”);
  40.                     }
  41.                 }
  42.                 else if (filename.contains(“Document “))
  43.                 {
  44.                     File_SaveAs_Action();
  45.                     _tabbedPane.remove(sel);
  46.                     listModel.removeAllElements();
  47.                     //adding all elements to list after removing the tab
  48.                     for (int i = 0; i < _tabbedPane.getTabCount(); i++)
  49.                     {
  50.                         String item = _tabbedPane.getTitleAt(i);
  51.                         if (item.contains(“*”))
  52.                         {
  53.                             item = item.replace(“*”“”).trim();
  54.                         }
  55.                         listModel.addElement(item);
  56.                     }
  57.                     _list.setSelectedIndex(_tabbedPane.getTabCount() – 1);
  58.                     rowLabel.setText(“Row :”);
  59.                     colLabel.setText(“Col :”);
  60.                     if (_tabbedPane.getTabCount() == 0)
  61.                     {
  62.                         setTitle(“Tabbed Notepad in Java”);
  63.                         filenameLabel.setText(“”);
  64.                         rowLabel.setText(“Row :”);
  65.                         colLabel.setText(“Col :”);
  66.                     }
  67.                 }
  68.             }
  69.             if (n == 1)
  70.             {
  71.                 _tabbedPane.remove(sel);
  72.                 listModel.removeAllElements();
  73.                 //adding all elements to list after removing the tab
  74.                 for (int i = 0; i < _tabbedPane.getTabCount(); i++)
  75.                 {
  76.                     String item = _tabbedPane.getTitleAt(i);
  77.                     if (item.contains(“*”))
  78.                     {
  79.                         item = item.replace(“*”“”).trim();
  80.                     }
  81.                     listModel.addElement(item);
  82.                 }
  83.                 _list.setSelectedIndex(_tabbedPane.getTabCount() – 1);
  84.                 rowLabel.setText(“Row :”);
  85.                 colLabel.setText(“Col :”);
  86.                 if (_tabbedPane.getTabCount() == 0)
  87.                 {
  88.                     setTitle(“Tabbed Notepad in Java”);
  89.                     filenameLabel.setText(“”);
  90.                     rowLabel.setText(“Row :”);
  91.                     colLabel.setText(“Col :”);
  92.                 }
  93.             }
  94.         }
  95.         else
  96.         {
  97.             _tabbedPane.remove(sel);
  98.             listModel.removeAllElements();
  99.             //adding all elements to list after removing the tab
  100.             for (int i = 0; i < _tabbedPane.getTabCount(); i++)
  101.             {
  102.                 String item = _tabbedPane.getTitleAt(i);
  103.                 if (item.contains(“*”))
  104.                 {
  105.                     item = item.replace(“*”“”).trim();
  106.                 }
  107.                 listModel.addElement(item);
  108.             }
  109.             _list.setSelectedIndex(_tabbedPane.getTabCount() – 1);
  110.             rowLabel.setText(“Row :”);
  111.             colLabel.setText(“Col :”);
  112.             if (_tabbedPane.getTabCount() == 0)
  113.             {
  114.                 setTitle(“Tabbed Notepad in Java”);
  115.                 filenameLabel.setText(“”);
  116.                 rowLabel.setText(“Row :”);
  117.                 colLabel.setText(“Col :”);
  118.             }
  119.         }
  120.     }
  121.     else
  122.     {
  123.         setTitle(“Tabbed Notepad in Java”);
  124.         filenameLabel.setText(“”);
  125.         rowLabel.setText(“Row :”);
  126.         colLabel.setText(“Col :”);
  127.     }
  128. }
Window Menu :
We will also create Window menu on menubar for select tabs when clicking/selecting them(see image 3).
First create Window menu,add it to menubar and add MenuListener event to it.
For action when window menu is selected, we will create JCheckBoxMenuItems with texts same as tabs text read from tabbedpane and will add action events to that menu items for select that tab.
  1. class WindowMenuAction implements MenuListener
  2. {
  3.     @Override
  4.     public void menuSelected(MenuEvent me) {
  5.         if (_tabbedPane.getTabCount() > 0) {
  6.             windowMenu.removeAll();
  7.             JMenuItem window_restart=new JMenuItem(” Restart                       “);
  8.             window_restart.addActionListener(new WindowRestartAction());
  9.             windowMenu.add(window_restart);
  10.             windowMenu.addSeparator();
  11.             int tabcount = _tabbedPane.getTabCount();
  12.             String tabtext=_tabbedPane.getTitleAt(_tabbedPane.getSelectedIndex());
  13.             for (int i = 0; i < tabcount; i++) {
  14.                 String title = _tabbedPane.getTitleAt(i);
  15.                 JCheckBoxMenuItem witem=new JCheckBoxMenuItem(title);
  16.                 witem.addActionListener(new Window_MenuItemsAction());
  17.                 if(tabtext.equals(title)){
  18.                     witem.setSelected(true);
  19.                 }
  20.                 windowMenu.add(witem);
  21.             }
  22.         }
  23.   }
  24.     @Override
  25.     public void menuDeselected(MenuEvent me) {
  26.       }
  27.     @Override
  28.     public void menuCanceled(MenuEvent me) {
  29.     }
  30. }
  31. //Window Restart action class
  32. class WindowRestartAction implements ActionListener
  33. {
  34.         @Override
  35.         public void actionPerformed(ActionEvent ae) {
  36.             File_CloseAll_Action();
  37.             dispose();
  38.             count = 1;
  39.             LookAndFeelAction.setBasicLookAndFeel();
  40.         }
  41. }
  42. //******************************************************
  43. // Window menu item action
  44. //******************************************************
  45. class Window_MenuItemsAction implements ActionListener
  46. {
  47.         @Override
  48.         public void actionPerformed(ActionEvent ae) {
  49.             String menutext=ae.getActionCommand().trim();
  50.             if (_tabbedPane.getTabCount() > 0) {
  51.                 int tabcount = _tabbedPane.getTabCount();
  52.                 for (int i = 0; i < tabcount; i++) {
  53.                     String title = _tabbedPane.getTitleAt(i).trim();
  54.                     if (title.contains(“*”)) {
  55.                         title = title.replace(“*”“”).trim();
  56.                     }
  57.                     if (title.equals(menutext)) {
  58.                         _tabbedPane.setSelectedIndex(i);
  59.                         setTitle(“Tabbed Notepad in Java – [ “ + _tabbedPane.getTitleAt(_tabbedPane.getSelectedIndex()) + ” ]”);
  60.                     }
  61.                 }
  62.             }
  63.         }
  64. }
It is easy to implement Edit operations in java like Cut,Copy,Paste,Undo,Redo etc.
Java does not provide the pre created font dialog. you have to create your own font dialog box. Here’s my created font dialog box code that set the font to the current textpane in current selected tab in tabbedpane.

Here’s the code,
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import javax.swing.*;
  6. import javax.swing.event.*;
  7. import javax.xml.parsers.DocumentBuilder;
  8. import javax.xml.parsers.DocumentBuilderFactory;
  9. import javax.xml.parsers.ParserConfigurationException;
  10. import org.w3c.dom.DOMException;
  11. import org.w3c.dom.Document;
  12. import org.w3c.dom.Element;
  13. import org.w3c.dom.Node;
  14. import org.w3c.dom.NodeList;
  15. import org.xml.sax.SAXException;
  16. public final class FontAction extends JDialog implements ListSelectionListener,ActionListener
  17. {
  18.     String[] fontNames=GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
  19.     String[] fontStyles={
  20.          ”  Plain  “,
  21.          ”  Bold  “,
  22.          ”  Italic  “,
  23.          ”  Plain+Bold  “,
  24.          ”  Plain+Italic  “,
  25.          ”  Bold+Italic  “,
  26.          ”  Plain+Bold+Italic  “
  27.                                  };
  28.     List lst=new List();
  29.     JList fontsList;
  30.     JList fontStyleList;
  31.     JList fontSizeList;
  32.     JPanel jp1,jp2;
  33.     DefaultListModel model;
  34.     JLabel displayLabel;
  35.     JButton ok,cancel;
  36.     JTextPane textPane;
  37.     static boolean isDarkTheme = false;
  38.     public FontAction(JTextPane tx)
  39.     {
  40.         textPane=tx;
  41.         Container cp=getContentPane();
  42.         isDarkTheme = getNodeTextContent(“lookAndFeel”).equals(“GlobalDark”);
  43.         fontsList=new JList(fontNames);
  44.         fontStyleList=new JList(fontStyles);
  45.         fontsList.setFont(new Font(“Calibri”,Font.PLAIN,14));
  46.         fontStyleList.setFont(new Font(“Calibri”,Font.PLAIN,14));
  47.         model=new DefaultListModel();
  48.         fontSizeList = new JList(model);
  49.         fontSizeList.setFont(new Font(“Calibri”, Font.PLAIN, 14));
  50.         for(int i=1;i<=160;i++)
  51.         {
  52.             model.addElement(”  “+i+”        “);
  53.         }
  54.         fontsList.setSelectedIndex(8);
  55.         fontStyleList.setSelectedIndex(0);
  56.         fontSizeList.setSelectedIndex(21);
  57.         fontsList.addListSelectionListener(this);
  58.         fontStyleList.addListSelectionListener(this);
  59.         fontSizeList.addListSelectionListener(this);
  60.         jp1=new JPanel();
  61.         jp2=new JPanel();
  62.         JPanel jp3=new JPanel();
  63.         jp3.add(new JScrollPane(fontsList));
  64.         JPanel jp4=new JPanel();
  65.         jp4.setLayout(new GridLayout(0,2));
  66.         jp4.add(new JScrollPane(fontStyleList));
  67.         jp4.add(new JScrollPane(fontSizeList));
  68.         jp1.add(jp3,BorderLayout.WEST);
  69.         jp1.add(jp4,BorderLayout.EAST);
  70.         displayLabel=new JLabel(“Java Programming”,JLabel.CENTER);
  71.         displayLabel.setFont(new Font(“Arial”,Font.PLAIN,21));
  72.         jp1.add(displayLabel);
  73.         ok=new JButton(”  OK  “);
  74.         cancel=new JButton(”  Cancel  “);
  75.         if (isDarkTheme) {
  76.             fontsList.setBackground(new Color(404040));
  77.             fontStyleList.setBackground(new Color(404040));
  78.             fontSizeList.setBackground(new Color(404040));
  79.             displayLabel.setForeground(new Color(240240240));
  80.         }
  81.         ok.addActionListener(this);
  82.         cancel.addActionListener(this);
  83.         jp2.add(ok);
  84.         jp2.add(cancel);
  85.         cp.add(jp1,BorderLayout.CENTER);
  86.         cp.add(jp2,BorderLayout.SOUTH);
  87.     }
  88.     @Override
  89.     public void valueChanged(ListSelectionEvent evt)
  90.     {
  91.         String fontname=fontsList.getSelectedValue().toString();
  92.         String fontstyle=fontStyleList.getSelectedValue().toString().trim();
  93.         int fontsize=Integer.parseInt(fontSizeList.getSelectedValue().toString().trim());
  94.         switch(fontstyle)
  95.         {
  96.             case “Plain”:
  97.                 displayLabel.setFont(new Font(fontname, Font.PLAIN, fontsize));
  98.                 break;
  99.             case “Bold”:
  100.                 displayLabel.setFont(new Font(fontname, Font.BOLD, fontsize));
  101.                 break;
  102.             case “Italic”:
  103.                 displayLabel.setFont(new Font(fontname, Font.ITALIC, fontsize));
  104.                 break;
  105.             case “Plain+Bold”:
  106.                 displayLabel.setFont(new Font(fontname, Font.PLAIN + Font.BOLD, fontsize));
  107.                 break;
  108.             case “Plain+Italic”:
  109.                 displayLabel.setFont(new Font(fontname, Font.PLAIN + Font.ITALIC, fontsize));
  110.                 break;
  111.             case “Bold+Italic”:
  112.                 displayLabel.setFont(new Font(fontname, Font.BOLD + Font.ITALIC, fontsize));
  113.                 break;
  114.             case “Plain+Bold+Italic”:
  115.                 displayLabel.setFont(new Font(fontname, Font.PLAIN + Font.BOLD + Font.ITALIC, fontsize));
  116.                 break;
  117.         }
  118.     }
  119.     @Override
  120.     public void actionPerformed(ActionEvent evt)
  121.     {
  122.         Object source=evt.getSource();
  123.         if(source==ok)
  124.         {
  125.             String fontname = fontsList.getSelectedValue().toString();
  126.             String fontstyle = fontStyleList.getSelectedValue().toString().trim();
  127.             int fontsize = Integer.parseInt(fontSizeList.getSelectedValue().toString().trim());
  128.             switch (fontstyle)
  129.             {
  130.                 case “Plain”:
  131.                     textPane.setFont(new Font(fontname, Font.PLAIN, fontsize));
  132.                     break;
  133.                 case “Bold”:
  134.                     textPane.setFont(new Font(fontname, Font.BOLD, fontsize));
  135.                     break;
  136.                 case “Italic”:
  137.                     textPane.setFont(new Font(fontname, Font.ITALIC, fontsize));
  138.                     break;
  139.                 case “Plain+Bold”:
  140.                     textPane.setFont(new Font(fontname, Font.PLAIN + Font.BOLD, fontsize));
  141.                     break;
  142.                 case “Plain+Italic”:
  143.                     textPane.setFont(new Font(fontname, Font.PLAIN + Font.ITALIC, fontsize));
  144.                     break;
  145.                 case “Bold+Italic”:
  146.                     textPane.setFont(new Font(fontname, Font.BOLD + Font.ITALIC, fontsize));
  147.                     break;
  148.                 case “Plain+Bold+Italic”:
  149.                     textPane.setFont(new Font(fontname, Font.PLAIN + Font.BOLD + Font.ITALIC, fontsize));
  150.                     break;
  151.             }
  152.             this.dispose();
  153.         }
  154.         else if(source==cancel)
  155.         {
  156.             this.dispose();
  157.         }
  158.     }
  159.     //**************************************************
  160.     // returns content of node
  161.     //**************************************************
  162.     public String getNodeTextContent(String nodetag) {
  163.         String content = “”;
  164.         try {
  165.             File fXmlFile = new File(“files/viewsfile.xml”);
  166.             DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  167.             DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  168.             Document doc = dBuilder.parse(fXmlFile);
  169.             doc.getDocumentElement().normalize();
  170.             NodeList nList = doc.getElementsByTagName(“views”);
  171.             for (int temp = 0; temp < nList.getLength(); temp++) {
  172.                 Node nNode = nList.item(temp);
  173.                 Element eElement = (Element) nNode;
  174.                 content = eElement.getElementsByTagName(nodetag).item(0).getTextContent();
  175.             }
  176.         } catch (ParserConfigurationException | SAXException | IOException | DOMException e) {
  177.         }
  178.         return content;
  179.     }
  180. }
Selecting Tab by clicking on Document Selector

As you know every advanced editor has this function,where you can click on the document name then that name of document tab is activated. Like Solution Explorer in Visual Studio. It is easy to implement this function by just creating a class that implement the interface ListSelectionListener and define the valueChanged() function. And add addListSelectionListener() to the document selector list with implemented ListSelectionListener class object. Get each tab title from tabbedpane,compare that value with selected item from the list & set that tab to selected.

Here’s the code.

  1. class SelectTabFromListItem implements ListSelectionListener
  2. {
  3.     public void valueChanged(ListSelectionEvent evt)
  4.     {
  5.         if(_list.getSelectedValue()!=null)
  6.         {
  7.             String list_item=_list.getSelectedValue().toString().trim();
  8.             if(_tabbedPane.getTabCount() >0)
  9.             {
  10.                 int tabcount=_tabbedPane.getTabCount();
  11.                for(int i=0;i<tabcount;i++)
  12.                 {
  13.                     String title=_tabbedPane.getTitleAt(i).trim();
  14.                     if (title.contains(“*”))
  15.                     {
  16.                         title = title.replace(“*”“”).trim();
  17.                     }
  18.                    if(title.equals(list_item))
  19.                     {
  20.                         _tabbedPane.setSelectedIndex(i);
  21.                         setTitle(“Tabbed Notepad in Java – [ “+_tabbedPane.getTitleAt(_tabbedPane.getSelectedIndex())+” ]”);
  22.                     }
  23.                 }
  24.             }
  25.         }
  26.     }
  27. }
Changing Title of frame,text of filenameLabel when Tab Changed

It is easy to implement this function by just creating a class that implements the interface ChangeListener and defines the stateChanged() function. And add addChangeListener() to the tabbedpane with implemented ChangeListener class object.

Here’s the code.

  1. class TabChanged implements ChangeListener
  2. {
  3.     @Override
  4.     public void stateChanged(ChangeEvent evt)
  5.     {
  6.         if(_tabbedPane.getTabCount()>0)
  7.         {
  8.             Object[] files=filesHoldListModel.toArray();
  9.             String tabtext=_tabbedPane.getTitleAt(_tabbedPane.getSelectedIndex()).trim();
  10.             if(tabtext.contains(“*”))
  11.              {
  12.                  tabtext=tabtext.replace(“*”“”);
  13.              }
  14.             for(Object filename : files)
  15.             {
  16.                 String file=filename.toString().substring(filename.toString().lastIndexOf(“\\”)+1);
  17.                 if(file.equals(tabtext))
  18.                 {
  19.                     filenameLabel.setText(filename.toString());
  20.                     setTitle(“Tabbed Notepad in Java – [ “+_tabbedPane.getTitleAt(_tabbedPane.getSelectedIndex())+” ]”);
  21.                 }
  22.             }
  23.             if(tabtext.contains(“Document “))
  24.             {
  25.                 filenameLabel.setText(tabtext);
  26.                 setTitle(“Tabbed Notepad in Java – [ “+_tabbedPane.getTitleAt(_tabbedPane.getSelectedIndex())+” ]”);
  27.             }
  28.         }
  29.     }
  30. }

To set dark theme we will set setDefaultLookAndFeelDecorated() to true and will call method MetalLookAndFeel.setCurrentTheme(). we will usejavax.swing.plaf.ColorUIResource class. see following link for many infomation about ColorUIResource.

I have created a class JavaGlobalDarkTheme in which i defined all these methods and calling them in setGlobalDarkLookAndFeel() method.

  1. class JavaGlobalDarkTheme {
  2.     DefaultMetalTheme darkTheme = new DefaultMetalTheme() {
  3.         @Override
  4.         public ColorUIResource getPrimary1() {
  5.             return new ColorUIResource(new Color(303030));
  6.         }
  7.         @Override
  8.         public ColorUIResource getPrimary2() {
  9.             return new ColorUIResource(new Color(202020));
  10.         }
  11.         @Override
  12.         public ColorUIResource getPrimary3() {
  13.             return new ColorUIResource(new Color(303030));
  14.         }
  15.         @Override
  16.         public ColorUIResource getBlack(){
  17.                     return new ColorUIResource(new Color(303030));
  18.                 }
  19.         @Override
  20.         public ColorUIResource getWhite() {
  21.             return new ColorUIResource(new Color(240240240));
  22.         }
  23.         @Override
  24.         public ColorUIResource getMenuForeground() {
  25.             return new ColorUIResource(new Color(200200200));
  26.         }
  27.         @Override
  28.         public ColorUIResource getMenuBackground() {
  29.             return new ColorUIResource(new Color(252525));
  30.         }
  31.          @Override
  32.         public ColorUIResource getMenuSelectedBackground(){
  33.             return new ColorUIResource(new Color(505050));
  34.         }
  35.         @Override
  36.         public ColorUIResource getMenuSelectedForeground() {
  37.             return new ColorUIResource(new Color(255255255));
  38.         }
  39.         @Override
  40.         public ColorUIResource getSeparatorBackground() {
  41.             return new ColorUIResource(new Color(151515));
  42.         }
  43.         @Override
  44.         public ColorUIResource getUserTextColor() {
  45.             return new ColorUIResource(new Color(240240240));
  46.         }
  47.         @Override
  48.         public ColorUIResource getTextHighlightColor() {
  49.             return new ColorUIResource(new Color(804080));
  50.         }
  51.         @Override
  52.         public ColorUIResource getAcceleratorForeground(){
  53.             return new ColorUIResource(new Color(3030,30));
  54.         }
  55.         @Override
  56.         public ColorUIResource getWindowTitleInactiveBackground() {
  57.             return new ColorUIResource(new Color(303030));
  58.         }
  59.         @Override
  60.         public ColorUIResource getWindowTitleBackground() {
  61.             return new ColorUIResource(new Color(303030));
  62.         }
  63.         @Override
  64.         public ColorUIResource getWindowTitleForeground() {
  65.             return new ColorUIResource(new Color(230230230));
  66.         }
  67.         @Override
  68.         public ColorUIResource getPrimaryControlHighlight() {
  69.             return new ColorUIResource(new Color(404040));
  70.         }
  71.         @Override
  72.         public ColorUIResource getPrimaryControlDarkShadow() {
  73.             return new ColorUIResource(new Color(404040));
  74.         }
  75.         @Override
  76.         public ColorUIResource getPrimaryControl() {
  77.             //color for minimize,maxi,and close
  78.             return new ColorUIResource(new Color(606060));
  79.         }
  80.         @Override
  81.         public ColorUIResource getControlHighlight() {
  82.             return new ColorUIResource(new Color(202020));
  83.         }
  84.         @Override
  85.         public ColorUIResource getControlDarkShadow() {
  86.             return new ColorUIResource(new Color(505050));
  87.         }
  88.         @Override
  89.         public ColorUIResource getControl() {
  90.             return new ColorUIResource(new Color(252525));
  91.         }
  92.         @Override
  93.         public ColorUIResource getControlTextColor() {
  94.             return new ColorUIResource(new Color(230230230));
  95.         }
  96.         @Override
  97.         public ColorUIResource getFocusColor() {
  98.             return new ColorUIResource(new Color(01000));
  99.         }
  100.         @Override
  101.         public ColorUIResource getHighlightedTextColor() {
  102.             return new ColorUIResource(new Color(250250250));
  103.         }
  104.     };
  105. }
  1. public static void setGlobalDarkLookAndFeel()
  2. {
  3.     MetalLookAndFeel.setCurrentTheme(new JavaGlobalDarkTheme().darkTheme);
  4.     try {
  5.         UIManager.setLookAndFeel(new MetalLookAndFeel());
  6.     } catch (Exception ev) {
  7.     }
  8.     JFrame.setDefaultLookAndFeelDecorated(true);
  9.     TabbedNotepad tb = new TabbedNotepad();
  10.     tb.setExtendedState(JFrame.MAXIMIZED_BOTH);
  11.     BufferedImage image = null;
  12.     try {
  13.         image = ImageIO.read(tb.getClass().getResource(“resources/myicon.png”));
  14.     } catch (IOException e) {
  15.     }
  16.     tb.setIconImage(image);
  17.     tb.setSize(800600);
  18.     tb.setLocation(10050);
  19.     tb.setVisible(true);
  20. }

Creating DropDownControl In C#

Creating DropDownControl In C# cách làm cực kì đơn giản anh em tham khảo nhé.

 


Introduction

Well, what is DropDownControl?

Actually, it is a form having BorderStyle: None, and which can be shown consisting of as many controls as needed for specific operations. Nowdays, all the popular software uses DropDownControl to improve their software quality. Take a look at the Paint application in Windows. Click on the File option. It drops the list of controls, like New,Open,Save,Print etc. Alternatively, open Microsoft Word. See the following image that shows text effects in DropDownControl.

In this article, we will create a DropDownControl for a click on a button.

So, how does it work?

Well, it’s so simple. Display a DropDownForm when clicking on Button. Once form is shown, invoke the Parent Form events, like Move, GotFocus, Activated, Click etc. When these events are generated, just close the DropDownForm.

Procedure 
Step 1 : Start Visual Studio and create a new Windows Forms Application in C#. The created form’s name could be Form1.
 
Step 2 : Add another form with the name DropDownForm and set the following properties to it.
 Name DropDownForm
ControlBox  false
FormBorderStyle  None
 ShowIcon  false
 ShowInTaskbar  false
 StartPosition  Manual
Now, Design your form. Add the components to DropDownForm that you wish. I have added Paint application like components. I have designed my form with many Panels and Buttons. You can add custom controls to design a form.

See the above images.

Download the source code.

Now, you have designed your form.

Step 3 : Add Form Load event to DropDownForm and set it to activate.
  1. protected override void OnLoad(EventArgs e)  
  2. {  
  3.     base.OnLoad(e);  
  4.   
  5.     this.Activate();  
Now, move to the Form1.
Step 4: Declare the DropDownForm object (I am using _dropDownForm) and Boolean variable for identifying if the DropDownForm is displayed or disposed.
  1. public Boolean isShown = false;  
  2.   
  3. DropDownForm _dropDownForm;  
Step 5 : Drag and drop the Button onto Form1. Add Click events to it.
  1.       private void button1_Click(object sender, EventArgs e)  
  2.       {  
  3.           if (isShown == true)  
  4.           {  
  5.               _dropDownForm.Close();  
  6.               isShown = false;  
  7.           }  
  8.           else if (isShown == false)  
  9.           {  
  10.               _dropDownForm = new DropDownForm(this);  
  11.               _dropDownForm.Location = new Point(this.Location.X + button1.Location.X + 8,  this.Location.Y + button1.Location.Y + 30);  
  12.               _dropDownForm.Show();  
  13.               isShown = true;  
  14.               _dropDownForm.LostFocus += new EventHandler(_dropDownForm_LostFocus);  
  15.           }  
  16.       }  
  17.   
  18. private void _dropDownForm_LostFocus(object sender, EventArgs e)  
  19.       {  
  20.           if (isShown)  
  21.           {  
  22.               _dropDownForm.Close();  
  23.               isShown = false;  
  24.           }  
  25.       } 
What’s this?
  • If isShown is equal to true, then close the DropDownForm.
  • If it is false, then initialize the object by calling its class name.
  • Set its location under your added button by adding Parent Form locations & button height.
  • Then, show the Form & set isShown to true.
  • Then, add LostFocus event to the object of DropDownForm.
  • If focus is lost, just close the displayed form and set isShown to false.
Step 6 : Now, add Move, GotFocus, Click, Activated events to the Form1 or Parent Form and add the following code to all these events.
  1. protected override void OnMove(EventArgs e)  
  2. {  
  3.     base.OnMove(e);  
  4.     if (isShown)  
  5.     {  
  6.         _dropDownForm.Close();  
  7.         isShown = false;  
  8.     }  
  9. }  
  10.   
  11. protected override void OnGotFocus(EventArgs e)  
  12. {  
  13.     base.OnGotFocus(e);  
  14.     if (isShown)  
  15.     {  
  16.         _dropDownForm.Close();  
  17.         isShown = false;  
  18.     }  
  19. }  
  20.   
  21. protected override void OnClick(EventArgs e)  
  22. {  
  23.     base.OnClick(e);  
  24.     if (isShown)  
  25.     {  
  26.         _dropDownForm.Close();  
  27.         isShown = false;  
  28.     }  
  29. }  
  30.   
  31.   
  32. protected override void OnActivated(EventArgs e)  
  33. {  
  34.     base.OnActivated(e);  
  35.     if (isShown)  
  36.     {  
  37.         _dropDownForm.Close();  
  38.         isShown = false;  
  39.     }  
  40. }  
Step 7 : Debug your project and make any changes to your DropDownForm for design.
DropDownControl with Tab 


Do you know what exactly is the RibbonBar?
Actually, it is a TabControl, we all know. You can see that old Microsoft Office packages, like 2007,2010 etc. provided the RibbonBar with DropDownControl. Here, we already created our own DropDownControl. Now, it’s the time to display DropDownControl with Tab. This can be achieved by setting first tab of TabControl (means index 0) to fixed for File option. Perform all the above actions except Step 5. Replace Step 5 to the following:
Step 8 : Add TabControl to Form1 and Add MouseDown event to it.
  1. private void tabControl1_MouseDown(object sender, MouseEventArgs e)  
  2. {  
  3.     Rectangle rect = tabControl1.GetTabRect(0);  
  4.   
  5.     if (rect.Contains(e.Location))  
  6.     {  
  7.         Size size = this.Size;  
  8.   
  9.         if (isShown == true)  
  10.         {  
  11.             _dropDownForm.Dispose();  
  12.             isShown = false;  
  13.   
  14.             tabControl1.SelectedIndex = OldSelTabIndex;  
  15.         }  
  16.         else if (isShown == false)  
  17.         {  
  18.             _dropDownForm = new TabDropDownForm(this);  
  19.             _dropDownForm.Location = new Point(this.Location.X + rect.X + 8, this.Location.Y + rect.Y + 30);  
  20.             tabControl1.SelectedIndex = OldSelTabIndex;  
  21.             _dropDownForm.Show();  
  22.             isShown = true;  
  23.             _dropDownForm.LostFocus += new EventHandler(_dropDownForm_LostFocus);  
  24.         }  
  25.     }  
  26.     else  
  27.     {  
  28.         OldSelTabIndex = tabControl1.SelectedIndex;  
  29.     }  
  30. }  
  31.   
  32.   
  33. private void _dropDownForm_LostFocus(object sender, EventArgs e)  
  34. {  
  35.     if (isShown)  
  36.     {  
  37.         _dropDownForm.Close();  
  38.         isShown = false;  
  39.     }  
Where OldSelTabIndex is the int type to hold the last selected index of tabControl, if the position of the mouse pressed button is within the first tab of tabControl, then it displays the DropDownForm; otherwise set OldSelTabIndex to tabControl SelectedIndex. Once DropDownForm is shown, set the isShown to true & set tabControl SelectedIndex to OldSelTabIndex. Download the source for better understanding.

Congratulations! You have created your own simple RibbonBar in C#.

You know, RibbonBar has a custom window. You can also create a customized window. By creating a customized window, you can add controls to the Top layer. Don’t know how to create Custom Windows Forms ? Go to :

DropDownControl_CSharp.zip

tác giả Lâm Văn Định(MR.DINH)