You are on page 1of 12
eer017 (Creating Advanced Tabbed Notepad In Java - CodeProject 12,105 355 members (30,447 online) Signin articles Q&A forums lounge Seach fo ates, uesons tos P Creating Advanced Tabbed Notepad In Java Re Pritam Zope, 10 May 2016 |cvo. Rate this FOIA IK 5:00 5 votes) In this article, we will reate a notepad in Java with features lice Mult Tabbed Documents, Document Selector, Openning/Saving/Closing Multiple ‘documents, Running External Programs, Viewing files in Browser, etc. Download source code - 601.1 KB etn de — a x fie tie os (is|[c [ea toe a ae oe ss te ‘gti OTDNe ta i sey ge pects “mc tan pe planar PITAMZOPE PTA 208 > Langa Wares unprtan dope Priam Zope. Cpe. Psyannng ees smmecnse fn 2a Cnpe See Pa rei choneVIF 8 hu tepequn~ agra corto casne= [et repeqn~ache cone a npcach> ing ttc hea tn pena Cintomsyetea Sper tese Weteyes oe Mesa a bay ocoorats5i6> toss gper mage» aaa inside iets co a es agin Menge - oo x BL est wun a co _| 2 oe ro} ovamen 268 ocimen.78]osomer 4 [osemer [Doane 68] owe cons fees Sieh [Mystere ein [Maries emia [_ mssesad @ see 72, fleshed | Mres2ren) [ Mricesamtll|Waeekia an enter | cont | above [ese en [mde ‘en nate Ear Drawer Arche 0,505 Drs, Corer ose date /2,y + heh + ot ridin ert 2L = na | rosrnne ae feist oe med ; " sd nasenprcontiabanein ? ean nt ‘enomenab ope ue meee i lensrxOnOropboun == fae i asset t ianedNetepsinive————inderaseszee SB nip. codeproject.com Articles 1099187/Creating Advanced-Tabbed-Netpa-In-Jave an eer017 (Creating Advanced Tabbed Notepad In Java - CodeProject Introduction [As you all know, Java i the worle’s popular & powerful programming language which i platform indepenclent. There are many ecitors developed using Java that we use like Fclipse, NetBeans, Intell), Edt, ete, These editors are the same as notepad but with added and developed extended features, In this article, we will cover only the main functions such as open, save, close, run ete. but will not se to create syntax highlighting in Java Well its easy to create syntax highlighting in Java using StyLedDocument. You can easly find the source code to create syntax highlighting in Java onthe internet, We wil also change the icon of tabs when document text is changed or saved, lke Notepad++ provides. First, design your Notepad with Menus, Menu Items, ToolBar, et. Download the source cade to view the complete cade of advanced tabbed notepad and also created ja application. | am using JTextPane object instead of JText/trea. Its easy to perform New & Open operations, But to perform save or edit operations, fst you need to get the current textpane contral from the JTabbedPane after performing New or Open operations for use/perform ather operations Let's Start + Create the object of JList, JTabbedPane, JSplit. + Add JList object & JTabbedPane object to ISplit. + Add ISpLit object to the Container of the Frame Using the Code Getting JTextPane Contro! from Current Tab(Selected Tab) in JTabbedPane 1. Get the selected index fom the added JTabbedPane, 2.Cast the component of selected index of JTabbedPane with IScrol Pane itScrol1Pane added), 23. Get the Viewportt fram the casted JScrol Pane, 4 Finally, cast the component of index @ with JTextPane. Here's the code to get added JTextPane component from the added curent Tab. Hide Copy code Ant sel = _tabbedPane. getselectedindex() 35crollpane Jscroll=(35croL1Pane) _tabbedPane.getComponentAt(sel); Biewport jview-jscroll.getViewort(); drextPane textpane=(ITextPane) jview.getConponent (8); It's four lines of code, But you can de this only in one/two lines lice this: Hide Copy Code Ant sel = _tabbedPane. getSelectecIndex(); BTextPane FextPane (aTextPane) (((3Sero1Pane)_tabbecPane. getConponentAt sel) .getViewport()) .getConponent (e); Now perform all actions on textPane abject, (Ok now let's see the functions that are important. Add ActionListener to that menu item according to the actions you want. 1) New This function is easy to implement. Just adding new Tab & textPane to JTabbedPane. Here's the code. Hide Shrink 4 Copy Code public vod File New action() 4 /fereate textpane object STextPane _textPane=new ITextPane(); _textPane, SetFont(new Font ("Calibri",Font.PLAIN,14)) 5, Jscro1ipane jsp=new 3scroliPane(_textPane); 1/ add key Listener & Undoable edit Listener to text pane “textPane.addkeyListener (new KeyTypedAction()); Ttextpane. getdocunent() adéUndoableeditListener(_undotanager); T/add tab’ to tabbedPane with control textpane “eabbedPane.adaTab("Docusent “+count+” ",35p) 3 nip. codeproject.com Articles/1099187/Creating Advanced-Tabbed-Netpad-In-Java an esr0t7 Cresting Advanced Tabbed Notepad in Java - CodeProjact V/odd coret Listener & mouse Listener to text pane “eextpane.addcaretiistener(new Caretaction()); TeextPane adahouse.istener(new TextPane MouseAction()); Int index+_tabbedPane. getTabcount ()-1; _tabbed?ane. setSelectecIndex(index) // set sove icon to added tab “eabbedPane.setTconat (index, Tien Inagetcon(this.getClass() .getResource( *resources/save.pag"))); ListModel.addélenent("bocunent."+count+” "); _List.setSelectedindex(index); //change the title SetTitle("Tabbed Notepad in Java - [ Document “scounte” ]"); #ilenareLabel.setText ("Document "scount) ; countess 2) Open ‘This function is the same a5 New function, only ust needs to read fles. Here, 1am using Fil eDialog by setting setMult ipleMode to ‘true for getting multiple files. Adding tab to tabbedpane as selected fle name, changing ttl of frame, ete. Once object of textPane is crested, then add KeyListener & UndoableListener tot. Here's the code for open function. Hide Shrink 4 Copy Code public vold File_open_Action() FaleDialog fa = new Filebialog(new IFrane(), "Select File”, FileDialog. LOAD); fd, setmultiplevode(true); fd. show(); Af (Fdrgetriles() « 1) File[] Filessfd.getriles(); for(File ites : files) 4 5 5 ring filename = sten.tostring() ; ning File=filenane. substring(fi lenane.lastIndexOF("\\")+1); nt caunt=_tabbecPane. getTabcount (); ITextPane _textPanesnew ITextPane(); _textPane.SetFont(new Font("Calibri" Font .PLAIN,14)) 5 JscrotiPane jspenew IScroliPane(_textPane) ; _textPane.adakeyListener (new KeyTypedaction()); “textPane. getDocusent () addUndoableEditListener(_undoManager); Thextpane addcaretListenen(new Caretaction()); ‘extPane.addhousel istener(new TextPane_Mouseaction()); ibbedPane.addTab(File, jsp); bbedPane, setSelectedindex(count) bbedPane. set cone (count, sageTcon(this.getClass().getResource("resources/save.png")))s Listwodel.addElement( File); “ist. setSelectecIndex(count); setTitle("Tabbed Notepad in Java ~ [ “+file+" 1"); filenaneLabel.setText(Filenane); ‘ilesdoldl istodel. addelenent(Filenane); BufferedReader d; Stringsuffer sb ~ new StringBuffer(); try t 4 = now BufferedReaden(now FileReader(filenare)); String Line; while((Line=d.readtine()) !=nul2) 'sb.append(line + "\n")3 _textPane. setText(sb.tostring()); 4.close()i cateh(FlewotFoundexception fe) { “catch(IoException ioe){} systen.out.printin("File not Found"); _textPane.requestFocus()s nip. codeproject.com Articles/1099187/Creating Advanced-Tabbed-Netpad-In-Java ana esr0t7 Cresting Advanced Tabbed Notepad in Java - CodeProjact 3) Save All ‘Well itis easy to implement Save As & Save function. Here, we will se save all function. Is easy to implement this function, Use For loop from © to the maximimum index of tabbedpane & set that tothe selected index of tabbedpane, Get the flename from added filenameLabel & save that lle by geting the current textpane from current tab ‘To identity the full lename path, | have crested the ist FilesHoldList and set the ful filename path to the filenameLabel which added to the statusStr ip for saving the document, Here's the code. Hide Shrink 4 Copy Code public void File_saveall_Action() Af (_tabbedPane.getTabcount() > ©) q int maxindex = _tabbedPane.getTabCount() - 15 for (int 1 = 6) 4 <= maxindex; i++) _tabbedPane. setSelectedIndex(1); String filenane = filenanelabel..getText()5 int sel = _tabbedPane. getselectedinéex(); TTextPane textPane = (oTextPane) (((2Serol3Pane) _tabbedPane. getConponentAt(sel)) .getViewport ()) .getComponent (6); 1 (Filename. contains("\\")) File f = now File(Filenane); # (Fexists()) « ty ¢ Dataoutputstrean d = new DataoutputStrean(new Fileoutputstrean(Filenane)); String Line = textPane.getText()s 4.writesytes(Line); dcclose(};, btext = _tabbedPane.getTitleat(sel); xt contains("*")) { abtext .repiace("*", ""); 3 -setTitleat (sel, tabtext); ZetTitle( "Tabbed Notepad in Java - [* + tabtext +" J"); “tabbedPane.seticonst(sel, 5H TABGETCON this BERETS) getResoure( "resources sve,png"))s y catch (Exception ex) € Systes.out.println("File not found"); > |, FextPane.requestFocus(); »? ,? 4) Close ‘This function nothing but to remove selected tab from tabbedpane. But before removing tab, you must display a dialog box to save modified changes before close. Ifnone of the documents is modified, then remove that tab, otherwise show dialog for save. Dovinload the source cade to view CloseA1 function code, Here's the code. Hide Shrine & Copy Code public void File Close Action() Af (_tabbedPane.getTabcount() > ©) { int sel = _tabbedPane.getselectedindex(); String tabtext = _tabbedPane.getTitleat (sel); Af (tabtext..contains(**")) itp. codeproject.com/Articles/1098187/Creating Advanced Tabbed Ntopac: Jove an esr0t7 Cresting Advanced Tabbed Notepad in Java - CodeProjact q int m= 30ptionPane. showConfirmbialog (pull, "Do you want to save " + tabtext +" before close 2", “save or Not", 3Opt ionPane.VES_NO_CANCEL_OPTION, OptionPane. QUESTION MESSAGE) ; tabtext replace: sf ‘ 2 String filename = filenaneLabel.getText(); JTextPane textPane = (ITextPane) (((JSerollPane) tabbedPane. getConponentAt(sel)).getViewport ()) .getConponent (8); AF (Filename. contains("\\")) { File Save Action(); __tabbedPane resove(sel); Tisthodel .renovesLlelenents()5 //odding all elements to List after removing the tab {for (int § = 0; 1 < _tabbedPane.getTabcount(); i++) { item = item-replace(*>", °").trim()3 x ListModel.addélenent (ites); > list. setselectedtndex(_tabbedPane.getTabCount()-1); rowtabel. se: ds coltabel. se’ oF Af(_tabbedPane get TabCount()==0) « setTitle("Tabbed Notepad in Java’ FilenareLabel.setText(""); rowtabel.setText("Row :")} colLabel.setText("col :"); y else LF (Filename. contains(“Docusent “)) { File_Savens_Action(); _tabbedPane.resove(seL) Tistmodel .renoveALlelenents()5 //odding alt elements to List after renoving the tab for (int £ = 0; 1 < _tabbedPane.getTabcount(); ++) £ item = item-replace("*", °").trim()3 x ListModel_.addélenent (ites); > List. setselectedtndex(_tabbedPane.getTabCount() - 1) Af (_tabbedPane. getTabcount() « setTitle("Tabbed Notepad in Java"); falenarelabel. setText(""); Fowlabel.setText("Row :")} colLabel. setText("Col :*); y itp. codeproject.com/Articles/1098187/Creating Advanced Tabbed Ntopac: Jove sn esr0t7 (Creating Advanced Tabbed Notepad In Java - CodeProject sen { ) _tabbedPane.renove(sel) ; Tistwodel .renoveal lElenents () 5 ‘/Jadding alt elements to List after renoving the tab ‘for (int {= @} 1 ¢ tabbedPane.getTabcount(); i++) { String item = _tabbedPane. getTitlert(s)5 Af (Stem. contains("*")) Atom = ites.replace(**", "").trim(); » Listodel .adéElenent(item); » _list.setselecteaindex(_tabbedPane.getTabCount() - 1) rowtabel.setText("Row ="); collabel -setText("Col Sf (tabbedPane.getTabcount() == @) t setTitle("Tabbed Notepad in Java"); Filenanetabel -setText(""); rowtabel.setText("Row 2"); collabel.setText ("Col 2°); y y ? else { _tabbecPane.renave(se1); Tistwocel .renoveal lenents(); //adding alt elements to List after renoving the tab for (int i = @; i < tabvedPane.getTabcount(); i++) { String iten = _tabbedPane. getTitleat(s); Sf (Sten. contains("*")) t item = ites.replace(” y Listhodel .addélenent(iten); » _list.setSelectedindex(_tabbedPane.getTabcount() - 1)3 romLabel.setText(“Row :")3 collasel.setText("Col :")} Af (_tabbedPane. getTabcount() == 6) { setTitle(“Tabbed Notepad in Java"); Filenanetabel -setText(""); PowLabel.setText("Row = calLabel.setText("Col. > ,? else q setTitle("Tabbed Notepad in Java"); Filenanelabel. setText(""); owl abel.setText("Row :")} colLabel. set Text ("Col oH , Itis easy to implement Edt operations in ava Tike Cut, Copy Paste, Undo, Redo, etc Java does not provide the pre created font dialog. You have to create your own font cialog box. Here's my cteated font dialog box code that sets ‘the fon to the current cexzpane in current selected tab in tabbedoane nip. codeproject.com Articles 1099187/Creating Advanced-Tabbed-Netpa-In-Jave ana esr0r7 (Creating Advanced Tabbed Notepad In Java - CodeProject Set Font Pain v7 Bod 18 aie is PlaineBold 20 Painuitalc | 22 Boldsitalic |B PlaineBoldstalic | 23 larrowsi el 24 Java Programming OK Here's the code port Java.awt.*; import java.awt.event.*; import Javax.swing.*5 sport Javax.swing.event.*; public class FontAction extends IDialog inplenents ListselectionListener, ActionListener 4 Hide Shin String{] fontNanes=GraphicsEnvironnent.getLocalGraphicsénvironnent().getavailableFontFasilyvanes() Stringf] fontstylese( Plain“, 201d Italic “*, PlainsBold PlainsItalic “*, BoldsItalic ", " Plainsoldertalic ” h List Istenew List()s Bist FontsLists DList FontstyleList; BList fontsizeList; 3Panel pt, jp25 Defaultl istodel model; 3Label displaytabel; 3Button ok, cancel; drextPane textPane} public Fontaction(3TextPane tx) q ‘textPanestxs Container cp=getContent?ane(); fontsListenew IList(fontNanes); fontstyleListenew IList(Fontstyles) fontsList.setFont(new Font("Calibri”,Font PLAIN, 14)); FontStyleList.setFont(new Fant("calibri” Fort PLAIN, 14); rnodel=new DefaultListMadel(); fontSizelist = new JList(edel) ; FontSizeList.setFont(new Font("Calibri", Font-PLAIN, 14))5 for(int Le1;4eo60;i+6) rnodel .addlenent(” "sis" > fontsList. setSelectedindex(8); FontstyleList.setselecteendex(@); FontSizelist. setSelectedIndex(21)} fontsList.addlistSelectionl istener(this); FontstyleList.addl istSelectionListener(this); FontSizeList addi istSelectionlistener (this); nip. codeproject.com Articles/1099187/Creating Advanced-Tabbed-Netpad-In-Java Copy Code me esr0t7 > Cresting Advanced Tabbed Notepad in Java - CodeProjact Jp2enew 3Panel(); Panel jp3-new 3Panel()3 Jp3. add(new 3ScrollPane(FontsList))s Panel jpa=new 3Panel(); pa. setLayout(new Gridlayout(@,2)); Jpa-aca(neu ScroliPane(fontstylelist)); ps.acd(new 2scrollPane(fontsizelist)); Jp1-2d4(p3,BorderLayout WEST); pt. add(jo4,BorderLayout EAST); displaytasel=new displayLavel.setFont(new Font("Arial”, Fo abel("Java Progranming” Label CENTER); LAIN, 23)) 5 Jpl-add(displayLabel); fokenew 3Button(” 0K "D3 ‘cancel-new JButton(" Cancel ok. addActionListener(this)s cancel .addactiont istenen(this) Jp2.ada(ox); 5p2-add(cancel); ep.add( jp, BorderLayout. CENTER) ; p_adeé(jp2,Bordertayout SOUTH); public void valueChanged(ListSelectiontvent evt) 4 ) String fontnane=fontsList.getSelectedvalue() .tostring(); String fontstylecfontstyleList.getSelectedValue().tostring().trin(); int fontsize-Integer. parsernt (Fantsizel ist.getSelectedValue().tostring()-trim()); switch fontstyle) { case "Plain’ displayLabel. se’ breaks nt (new Font(Fontnane, Font.PLAIN, fontsize)); case "Bold displayLabel.setFont(new Font(Fontnane, break; BOLD, fontsize): case "Italic": display.abel.. breaks nt(new Font(fontnane, Font. ITALIC, fontsize)); case "Plains6ole": displayLabel.se' break; ont(new Font (fontnane, PLAIN + Font.B0L9, fontsize)); case "Plainsitalic™ Aisplaylabel.setFont(nen Font(fontname, Font.PLAIN + Font.ITALIC, fontsize)); breaky case “Boldsrtalic": displayLabel. se’ breaks ‘ont(new Font(fontnane, Font.B0LD + Font.LTALIC, Fontsize)); case “Plainstolesttalic displaylabel-setFont(new Font(fontname, Font.PLAIN + Font-BOLD + Font.ITALIC, fontsize)); breaks public void actionPerformed(Aactiontvent evt) q Object source-evt.getSource(); String fontnane = fontsList.getSelectedvalue() toString); String fontstyle = fontStyleList.getSelectedVaiue() toString()-trim(); int fontsize = Integer.parseint (fontsizel ist, getselectedvalue() .tostring() .t switch (fontstyle) case "Plain" textPane.setFont(new Font(fontname, Font.PLAIN, fontsize)); nip. codeproject.com Articles/1099187/Creating Advanced-Tabbed-Netpad-In-Java an esr0t7 (Creating Advanced Tabbed Notepad In Java - CodeProject breaks case "Bold": ‘textPane.setFont(new Font(fontname, Font BOLD, fontsize)_ break; case "Italic": textPane.setFont(new Font(fontname, Font. ITALIC, fontsize)); break; case "PlaintBold": textPane.setFont(nex Font(fontname, Font.PLAIN + Font.B0LD, fontsize)); breaks case "PlaintTtalic™: textPane.setFont(new Font(fontname, Font.PLAIN + Font.ITALIC, fontsize)); break; case "“Boldsrtalic"t ‘textPane. setFont(new Font(fontname, Font BOLD + Font.ITALIC, fontsize)); breaks case “PlainsBoldsTtalic ‘textPane.setFont (new Font(Fontnane, Font.PLAIN + Fort 80.0 + Font ITALIC, fontsize)); breaks ) this dispose); ‘this dispose); Selecting Tab by Clicking on Document Selector ‘As you know, every advanced editor has ths function, where you can click on the document name, then that name of document tab is activated Te Solution Explorer in Visual Studio. Its easy to implement ths function by just creating a class that implements the interface ListSelectionListener and define the valueChanged() function. And add addListSelectionListener() tothe document selector list with implemented ListSelectionListener class object, Get each tab title from tabbedpane, compare that value ith selected item from the ist & set that tab to selected, Here's the code: Hide Shrine 4 Copy Code class SelectTabrromistrten inplenents ListSelectiontistener « public void valuechanged(ListSelectiontvent evt) AF(_List.getselectedvalue() |=null) q String List_iten=_list. getselectedvalue().tostring().trim(); A (_tabbedPane.getTabcount() >) { int tabcount=_tabbedPane.getTabcount (); for(int 1=8;ictabcount; i++) { String tities_tabbedPane.getTitlett(i).tria(); Af (tisle.contains("*")) « title = title.replace("*", ").teim(); » Af (tite, equals(List_ites)) € _tabbedPane. setSelectedtndex(4); Feeritle("raobed Notepad in Java - [ "t_tabbedPane,getTitleat(_tabsedPane. getselectedindex())+" J"); ? y » ? ? ) nip. codeproject.com Articles 1099187/Creating Advanced-Tabbed-Netpa-In-Jave on eer017 (Creating Advanced Tabbed Notepad In Java - CodeProject Changing Title of frame, text of filenameLabel when Tab Changed Itis easy to implement this function by just creating 2 class that implement the interface ChangeListener and define the stateChanged() function. And add addChangeListener() to the tabbedpane with implemented ChangeListener class object. Here's the code: Hide Shrink class Tabchanged inplenents changeListener ¢ public void statechangee(changetvent evt) if(_tabbedPane.getTabCount()>@) { anject{] files-Filestoldtisthodel toArray()s String tabtexts,tabbedPane.getTitieat(_tabbedPane. getSelectedindex()) -tein(); ‘if(tabtext.contains("*")) < tobtextetabtext.replace("**, y for(Object fSlenane + files) String filesfilenane.tostring(). substring (#itenane.t0String():lastlndexOFC\V)HD5 Af (File. equals(tabtext)) ‘tenaneLabel set Texe(FSlenane. tostring())s SetTitle(- Tabbed Notepad in Java = ['"s_tabbedPane, getTitleAt(_tabbedPane.getSelectedtndex())+" J"); ? , ‘if(tabtext.contains("Document ")) ‘enaneLabel.setText(tabeext); SetTitle( Tabbed votepad in Java - ("1 tabbedPane.getTitlent(_tabbedPane getSelectedindex())¢" 1")s , + y ) License ‘This article, along with any associated source code and files, i censed under The Code Project Open License (CPOL) Share About the Author Pritam Zope Software Developer Indio Hi, Lam a C# developer’ have experience about 3 years in C& also do coding in C.C+ + Visual C+ +,C ‘Windows,Java,OpenGl, HTML,PHP,CSS JavaScript Python, ASP.Net But mostly do programming in C/C-++,C# and Java nip. codeproject.com Articles 1099187/Creating Advanced-Tabbed-Netpa-In-Jave copy Code ron eer017 You may also be interested in Getting the Most out of Your Infrastructure: Dev and Test Best Practices Notepad RE (Regular Expressions) Creating Advanced Notepad in Cit Comments and Discussions ‘You must Sign Into use this message board, (Creating Advanced Tabbed Notepad In Java - CodeProject Mobile App Playbook Intel® Quark™ SE Microcontroller C1000 Developer Kit - Accelerometer Tutori Visual COBOL New Release: Small point. Big deal Search Comments co For coming version = can help2ray 12-May-16 5:27 Re: For coming version. can Pritam Zope 13-May-16 005 User can anchor notepad position o help2ray 12-May-16 5:25, Can user defined notepad position size? help2ray 11-May-16 3:24 Re: Can user defied notepad position & size ? Pritam Zope 11-May-16 657 First. Prev Next Refresh [P General News Suggestion @uestion We oug [Answer Gioke BePraise [Bran GAdmin Use Ctrl+LefyRight to switch messages, Ctl+Up/Down to switch threads, Cul+ShitLeft/Right to switch pages. Permalink | Advertise |Privacy [Terms of Use | Mobile ‘webd2 | 28.170118.1 |Last Updated 10 May 2016 Select Language | ¥ ‘Arte Copyright 2016 by Pritam Zope Everything else Copyright © CodeProject, 1999-2017 Layout fixed [thie nip. codeproject.com Articles 1099187/Creating Advanced-Tabbed-Netpa-In-Jave nn eer017 Cresting Advanced Tabbed Notepad in Java - CodeProjact nip. codeproject.com Articles 1099187/Creating Advanced-Tabbed-Netpa-In-Jave ran

You might also like