java - How to switch between lines in JTextArea in swing -
am trying set goto line number switching between lines in swing application. got number of lines in jtextarea instance using getlinecount() don't know how switch between lines?
could 1 suggest me?
you can set caret position textarea.setcaretposition. work
textarea.setcaretposition(textarea.getdocument().getdefaultrootelement() .getelement(index).getstartoffset()); in example below, use jcombobox populate indexes using line numbers of jtextarea. when select on number in combo box, caret move line of jtextarea.
the program not great program though. want populate comboboxmodel dynamically addition , removal of lines. should give answer you're looking for.
disclaimer
i haven't added functionality bring scrollpane focus the current line. may want @ @balder comment below that.

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class testcaret { public testcaret() { jtextarea textarea = createtextarea(); jcombobox cbox = createcombobox(textarea); jframe frame = new jframe(); frame.add(new jscrollpane(textarea)); frame.add(cbox, borderlayout.south); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.pack(); frame.setlocationrelativeto(null); frame.setvisible(true); } private jcombobox createcombobox(final jtextarea textarea) { defaultcomboboxmodel<integer> model = new defaultcomboboxmodel<>(); int lines = textarea.getlinecount(); (int = 0; < lines; i++) { model.addelement(i); } final jcombobox cbox = new jcombobox(model); cbox.addactionlistener(new actionlistener(){ public void actionperformed(actionevent e) { int index = (integer)cbox.getselecteditem(); textarea.setcaretposition( textarea.getdocument().getdefaultrootelement().getelement(index).getstartoffset()); textarea.requestfocusinwindow(); } }); return cbox; } private jtextarea createtextarea() { jtextarea textarea = new jtextarea(10, 50); textarea.setmargin(new insets(15, 15, 15, 15)); textarea.setlinewrap(true); textarea.setwrapstyleword(true); string text = "0 hello world\n" + "1 hello world\n" + "2 hello world\n" + "3 hello world\n" + "4 hello world\n" + "5 hello world\n" + "6 hello world\n" + "7 hello world\n" + "8 hello world\n" + "9 hello world\n"; textarea.settext(text); return textarea; } public static void main(string[] args) { swingutilities.invokelater(new runnable(){ public void run() { new testcaret(); } }); } }
Comments
Post a Comment