Search in JTextarea

Hello,
If I have a JTextarea and I display a whole book in it, is it possible to implement a search function. Like for example a JTextfield, where I could type a word and the press a button and all the matches in the JTextarea are highlited and the JTextarea goes to the first match.
Also, would it be possible to have a JComboBox with the chapters of the book, and then when I choose one, the JTextArea goes down to that chapter ?
If anybody can tell me if this is possible, and maybe give a few pointers or links, where I can read about this, I would be very thankful.

mollet wrote:
Hello,
If I have a JTextarea and I display a whole book in it, is it possible to implement a search function. Like for example a JTextfield, where I could type a word and the press a button and all the matches in the JTextarea are highlited and the JTextarea goes to the first match.Yes, this is certainly doable. For the highlighting of all matches, check out the javax.swing.text.Highlighter class. Use it to simply add a highlight around each matched word.
As far as actually finding all matches, a poor man's way of doing this would be to read the Document into a String, and do repeated String#indexOf(toFind) calls until -1 is returned. This method works, but is horribly inefficient for large documents, and runs the risk of OutOfMemoryErrors. You can use this method as a starting point and replace it with an improved algorithm later, if you want to keep working.
There are many ways of improving the efficiency of your search algorithm. For example, if you don't allow embedded newlines in your search text, you can scan for it by reading/scanning 1 line from the document at a time, as opposed to the entire document, thus quite probably eliminating your chance for OOME's. If you allow embedded newlines, or regex searches, things get more complicated.
Also, would it be possible to have a JComboBox with the chapters of the book, and then when I choose one, the JTextArea goes down to that chapter ?Certainly. Check out the Javadoc for the Document#createPosition() method. Use it to create one javax.swing.text.Position at the beginning of each chapter. Then, whenever they select an item from the JComboBox, simply move the caret to the position for the proper chapter. In fact, you really don't need to use Positions, you can just store the positions of the chapter starts in an array of ints if you want, for example. javax.swing.text.Positions area really useful if the document may change (text inserted or removed), but you want a relative location to be remembered.

Similar Messages

  • Search/find/replace in jTextArea

    I wish to add search/find/replace features in a jTextArea object.
    How do I implement it? Thanks!

    Use regex for a pattern match
    /or something like
    String []tfContents = myField.getText().split(" ").trim();
    OR (pre 1.4) jdk/sdk's
    StringTokenizer tkn = new StringTokenizer(myField.getText(), " ");
    String []tfContents = new String[tkn.countTokens()];
    int j=0;
    while(tkn.hasMoreTokens() ){
    tfContents [j] = tkn.nextToken().trim();
    j++;
    boolean isFound=false;
    for (int k=0; k<tfContents.length; k++)if(tfContents[k].equalsIgnoreCase("java"))isFound=true;

  • How to highlight Search string in JTextArea??

    I have a Search utility which search for a string in JTextArea. Search utility is able to locate the search string but it does not highlight it.
    Please let me know if you know what could be wrong
    Thanks
    Amit

    You have to highlight the string yourself. Try using:
    textArea.setSelectionStart( int );
    textArea.setSelectionEnd ( int );

  • Search LinkedList and display to JtextArea

    The user will type in a first name and hit the "go" button. If the name is in the list it should say the person's name is in the list in the JTextArea, if not it should say the person's name is not in the list in the JTextArea. I have the basic layout, but am lost on how to get what the user typed in the JTextField and the button click and display to textarea to all play together.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    public class FirstName extends JFrame {
         private static final String names[] = { "Joe", "Mark", "David", "Bryan","Amber","Abigail","Skyler","Melanie" };
         private javax.swing.JButton jButton1;
         private javax.swing.JTextArea jTextArea1;
         private javax.swing.JPanel jPanel1;
         private javax.swing.JTextField jTextField1;
         private java.awt.Label label1;
         public FirstName() {
              initComponents();
              List link = new LinkedList(Arrays.asList(names));     
              setSize( 400, 200 );
              show();
         private void initComponents() {
              jPanel1 = new JPanel();
             label1 = new Label();
              jTextField1 = new javax.swing.JTextField();
              jButton1 = new javax.swing.JButton();
              jTextArea1 = new javax.swing.JTextArea();
              label1.setText("Enter a Name to Search:");
              jPanel1.add(label1);
              jTextField1.setColumns(20);
              jPanel1.add(jTextField1);
              jButton1.setText("Go");
              jButton1.addMouseListener(new MouseAdapter() {
                   public void mouseClicked(MouseEvent evt) {
                        MouseClicked(evt);
              jPanel1.add(jButton1);
              jTextArea1.setColumns(30);
              jTextArea1.setRows(5);
              jPanel1.add(jTextArea1);
              getContentPane().add(jPanel1, BorderLayout.CENTER);
         private void MouseClicked(MouseEvent evt) {
         public static void main(String args[]) {
              FirstName application = new FirstName();
              application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    I'm getting a Syntax error on token "(",";"expected
    for actionPerformed, what is wrong?
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    public class FirstName extends JFrame {
         private String names[] =
                   "Joe",
                   "Mark",
                   "David",
                   "Bryan",
                   "Amber",
                   "Abigail",
                   "Skyler",
                   "Melanie" };
         private JButton jButton1;
         private JTextArea jTextArea1;
         private JPanel jPanel1;
         private JTextField jTextField1;
         private Label label1;
         public FirstName() {
              initComponents();
              List link = new LinkedList(Arrays.asList(names));
              setSize(400, 200);
              show();
         private void initComponents() {
              jPanel1 = new JPanel();
              label1 = new Label();
              jTextField1 = new javax.swing.JTextField();
              jButton1 = new javax.swing.JButton();
              jTextArea1 = new javax.swing.JTextArea();
              label1.setText("Enter a Name to Search:");
              jPanel1.add(label1);
              jTextField1.setColumns(20);
              jPanel1.add(jTextField1);
              JButton1 = new JButton1("  OK  ");
              jbutton1.addActionListener(new ActionListener(this));
              public void actionPerformed(ActionEvent e) {
                   String entered = jTextField1.getText();
                   // search for "entered" within the list    
                   if (found) {
                        jTextArea1.setText("found");
                   } else {
                        jTextArea1.setText("not found");
                   jPanel1.add(jButton1);
                   jTextArea1.setColumns(30);
                   jTextArea1.setRows(5);
                   jPanel1.add(jTextArea1);
                   getContentPane().add(jPanel1, BorderLayout.CENTER);
         public static void main(String args[]) {
              FirstName application = new FirstName();
              application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

  • How to Capture New Line in JTextArea?

    I apologize if this is easy, but I've been searching here and the web for a few hours with no results.
    I have a JTextArea on a form. I want to save the text to a database, including any newline characters - /n or /r/n - that were entered.
    If I just do a .getText for the component, I can do a System.println and see the carriage return. However, when I store and then retrieve from the database, I get the lines concatenated.
    How to I search for the newline character and then - for lack of a better idea - replace it with a \n or something similar?
    TIA!

    PerfectReign wrote:
    Okay, nevermind. I got it.
    I don't "see" the \n but it is there.
    I added a replaceAll function to the string to replace \n with
    and that saves to the database correctly.
    String tmpNotes = txtNotes.getText().replaceAll("\n", "<br />");Oh, you're viewing the text as HTML? That would have been good to know. ;)
    I'll have to find a Wintendo machine to try this as well.Be careful not to get a machine that that says "Nii!"

  • How to hide the Form Feed char in JTextArea

    We have reports (written in C) that are being displayed in a JTextArea.
    In our old app, the Form Feed character (ASCII 12) was invisible naturally without having to code around it. In a JTextArea, it appears as a "[]" character. Does anyone know how to make this character invisible to the JTextArea? Removing it is not an option, as it is needed for it's print routine.
    I've been searching these forums and the web all morning with no luck.

    Not sure how the Form Feed character worksIt lets the printer know that a new page is to be started at that point.
    Does it always appear with the New Line character?Usually but not always.
    Thanks for the reply. It's more involved than just printing standard lines of text, so perhaps I should have been more clear.
    The C report already has pagination built in from when it was run from our legacy GUI. In other words, each report knows how many chars wide and how many lines down each page will be. It is different for each report, but they all hover around 150 chars wide and 60 lines down per page, since they are all presented to the user (and printed) in landscape.
    In the C code: at the end of each report line a "\n" is appended. At the end of each page, an ASCII 12 character is appended. A header is at the top of each page (different for each report, but usually 2 or 3 lines) that shows the page # and other info.
    So, as you are viewing the report, you would see page 1 header, some report content, page 2 header, some more report content, page 3 header, etc. as you scroll down.
    So now if you view it in Java: if the user wishes to print, the report is sent to our ReportPrinter class, who tokenizes the report based on "\f" and makes a ReportPage object (implements Printable) for each token. Each ReportPage is then appened to a java.awt.print.Book object, who in turn is sent to the PrinterJob.
    Given that the report already has his pages figured out and has a form feed char at the end of each page, the report comes in to the JTextArea with [] chars preceding each page header (approximately every 60th line, depending on the report).
    I tried using a JTextPane, but no luck. It was also much slower reading in the report. I just want the textpane to not display the non-printable characters ("\f" in this case).

  • Keyevent used for setMnemonic show in editable jtextarea

    I don't know if this has been fix. I notice that if I used the setMnemonic to access a editable jtextarea, that the key I used is inserted into the jtextarea. After searching the web, I found nothing about this problem.
    So, I took the program from the java tutorial, MenuDemo.java and reproduct the same problem but setting the jtextarea to editable (output.setEditable(true). It happens everytime. Below is the MenuDemo.java with the change. By selecting t or b in the A Menu menu,then which ever t or b used will show up in the text area after the expected line displays. I am using 1.5 so this problem may have been fix.
    If anyone knows if it has or a work around, please let me know.
    Thanks
    Kevin
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.ButtonGroup;
    import javax.swing.JMenuBar;
    import javax.swing.KeyStroke;
    import javax.swing.ImageIcon;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    * This class adds event handling to MenuLookDemo.
    public class MenuDemo extends JFrame
    implements ActionListener, ItemListener {
    JTextArea output;
    JScrollPane scrollPane;
    String newline = "\n";
    public MenuDemo() {
    JMenuBar menuBar;
    JMenu menu, submenu;
    JMenuItem menuItem;
    JRadioButtonMenuItem rbMenuItem;
    JCheckBoxMenuItem cbMenuItem;
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    //Add regular components to the window, using the default BorderLayout.
    Container contentPane = getContentPane();
    output = new JTextArea(5, 30);
    output.setEditable(true);
    scrollPane = new JScrollPane(output);
    contentPane.add(scrollPane, BorderLayout.CENTER);
    //Create the menu bar.
    menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    //Build the first menu.
    menu = new JMenu("A Menu");
    menu.setMnemonic(KeyEvent.VK_A);
    menu.getAccessibleContext().setAccessibleDescription(
    "The only menu in this program that has menu items");
    menuBar.add(menu);
    //a group of JMenuItems
    menuItem = new JMenuItem("A text-only menu item",
    KeyEvent.VK_T);
    //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_1, ActionEvent.ALT_MASK));
    menuItem.getAccessibleContext().setAccessibleDescription(
    "This doesn't really do anything");
    menuItem.addActionListener(this);
    menu.add(menuItem);
    menuItem = new JMenuItem("Both text and icon",
    new ImageIcon("images/middle.gif"));
    menuItem.setMnemonic(KeyEvent.VK_B);
    menuItem.addActionListener(this);
    menu.add(menuItem);
    menuItem = new JMenuItem(new ImageIcon("images/middle.gif"));
    menuItem.setMnemonic(KeyEvent.VK_D);
    menuItem.addActionListener(this);
    menu.add(menuItem);
    //a group of radio button menu items
    menu.addSeparator();
    ButtonGroup group = new ButtonGroup();
    rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
    rbMenuItem.setSelected(true);
    rbMenuItem.setMnemonic(KeyEvent.VK_R);
    group.add(rbMenuItem);
    rbMenuItem.addActionListener(this);
    menu.add(rbMenuItem);
    rbMenuItem = new JRadioButtonMenuItem("Another one");
    rbMenuItem.setMnemonic(KeyEvent.VK_O);
    group.add(rbMenuItem);
    rbMenuItem.addActionListener(this);
    menu.add(rbMenuItem);
    //a group of check box menu items
    menu.addSeparator();
    cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
    cbMenuItem.setMnemonic(KeyEvent.VK_C);
    cbMenuItem.addItemListener(this);
    menu.add(cbMenuItem);
    cbMenuItem = new JCheckBoxMenuItem("Another one");
    cbMenuItem.setMnemonic(KeyEvent.VK_H);
    cbMenuItem.addItemListener(this);
    menu.add(cbMenuItem);
    //a submenu
    menu.addSeparator();
    submenu = new JMenu("A submenu");
    submenu.setMnemonic(KeyEvent.VK_S);
    menuItem = new JMenuItem("An item in the submenu");
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_2, ActionEvent.ALT_MASK));
    menuItem.addActionListener(this);
    submenu.add(menuItem);
    menuItem = new JMenuItem("Another item");
    menuItem.addActionListener(this);
    submenu.add(menuItem);
    menu.add(submenu);
    //Build second menu in the menu bar.
    menu = new JMenu("Another Menu");
    menu.setMnemonic(KeyEvent.VK_N);
    menu.getAccessibleContext().setAccessibleDescription(
    "This menu does nothing");
    menuBar.add(menu);
    public void actionPerformed(ActionEvent e) {
    JMenuItem source = (JMenuItem)(e.getSource());
    String s = "Action event detected."
    + newline
    + " Event source: " + source.getText()
    + " (an instance of " + getClassName(source) + ")";
    output.append(s + newline);
    public void itemStateChanged(ItemEvent e) {
    JMenuItem source = (JMenuItem)(e.getSource());
    String s = "Item event detected."
    + newline
    + " Event source: " + source.getText()
    + " (an instance of " + getClassName(source) + ")"
    + newline
    + " New state: "
    + ((e.getStateChange() == ItemEvent.SELECTED) ?
    "selected":"unselected");
    output.append(s + newline);
    // Returns just the class name -- no package info.
    protected String getClassName(Object o) {
    String classString = o.getClass().getName();
    int dotIndex = classString.lastIndexOf(".");
    return classString.substring(dotIndex+1);
    public static void main(String[] args) {
    MenuDemo window = new MenuDemo();
    window.setTitle("MenuDemo");
    window.setSize(450, 260);
    window.setVisible(true);

    Yes your are correct. I forgot why I went to 1.5 but until better time come along and I can get a new computer, I will have to live with 1.4.2._06. But, it did fit my problem.

  • Tokenizing a JTextArea(how do i make the JTextArea a string?)

    I am working on this text analyzer program which is kinda like a replica of what you find when you a do a word count in many office suites. It tells you stuff like number of sentences, longest sentence, shortest sentence and average length. Number of words, longest shortest and average word length. In addtion there is a word search to it.
    It took me a good 3 hours to realize that there was such a thing as a panel and I could impliment this to add more than one object to a borderlayout section.
    I think I have figured out everything with the StringTokenizer part, well except for how do add it to an array. Someone mentioned something to me about an
    islist.StringTokenizer or something, but I haven't been able to find anything else on this.
    Right now, however, my primary concern is how can I take input from a JTextArea and be able to parse it with the StringTokenizer, which to the best of my knowledge has to be a string. It this as simple as a getValue(); type thing or do i have to add some sort of action listener that finds out when it changes or something?
    thank you for your time

    I just figued out the JTextArea thing
    it is JTextArea.getText();
    im stupid :P

  • Too much data for JTextArea

    Howdy people, I've been stuck on this problem for a while now. I writing a povvy hex-editor, and it works (yay!), but when I open largish files (>= 20kB) it really chokes on it. Not on the conversion from bytes to hex string, but (you guessed it) displaying it in the JTextArea. I've tried a couple of things. Make it a Thread (so it can update a pretty progress bar), I tried appending the data in sections, instead of one giant setText().... No go.
    Here's what I have so far:
    import javax.swing.JTextArea;
    public class DisplayThread extends Thread
        private static final int BUFSIZE = 100000;
        private FileEditor parent;
        private JTextArea textArea;
        private StringBuffer data;
        private ProgressDialog pd;
        public DisplayThread(FileEditor p, JTextArea jta, StringBuffer s, ProgressDialog pr)
            parent = p;
            textArea = jta;
            data = s;
            pd = pr;
        public void run()
            System.out.println("starting DisplayThread");
            long time = System.currentTimeMillis();
            textArea.setText("");
            int len = data.length();
            for(int i=0;i<len;i+=BUFSIZE)
                int n = (i+BUFSIZE<len)?i+BUFSIZE:len;
                textArea.append(data.substring(i,n));
                pd.setProgress(i, len);
            System.out.println("It took " + (System.currentTimeMillis() - time) + "ms by buffering");
            time = System.currentTimeMillis();
            textArea.setText(data.toString());
            System.out.println("It took " + (System.currentTimeMillis() - time) + "ms directly");
            textArea.setEditable(true);
            pd.setVisible(false);
            System.out.println("finishing DisplayThread");
    }At the moment I've got both the "bit-by-bit" display method, and the "one-shot-setText()" methods going to compare times, but check out these times for a 900k file...
    It took 673439ms by buffering
    It took 137628ms directly
    For the first one, that's over 11 mins!!!!
    Anyway, I did searches on what to do in this scenario, one answer was Don't!, the other was "only display what's necessary".
    So...
    I've tried to create a "BufferedJTextArea", and only set the text according to what will be visible in the scrollpane/scrollbar, but it's not working (all sorts of complications with adding a scrollbar to a JTextArea, or adding a JTextArea to a scrollPane....)
    Also, even after it loads all the data into the JTextArea, it takes it's sweet time to repaint...
    Any ideas on how to make it faster? Continue with the "BufferedJTextArea" (if that's the case, that'll be the next question)?
    Or give up and warn ppl not to load files larger than about 15k?
    Thanks ppl,
    Radish21

    But with a JList, you can only have one column, right? That'd mean I have to break up the String with \n all over the place.
    I did look at JTable first, and even tried to use one, but I've never used them before, and now I know why. Too damn difficult.
    I'm getting closer now, but still having hiccups (or is it hiccoughs? :)
    I had to make the class a JPanel itself, that adds a BufferedTextArea to a JScrollPane... it works, so why fix it? ;)
    import javax.swing.JTextArea;
    import javax.swing.JScrollBar;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import java.awt.event.AdjustmentListener;
    import java.awt.event.AdjustmentEvent;
    public class BufferedJTextArea extends JPanel
        protected BJTextArea textArea;
        protected JScrollPane scrollPane;
        public BufferedJTextArea()
            textArea = new BJTextArea();
            scrollPane = new JScrollPane(textArea);
            scrollPane.getVerticalScrollBar().addAdjustmentListener(textArea);
            setVisible(true);
            setLayout(new java.awt.BorderLayout());
            add(scrollPane, "Center");
        public void setText(String s)
            textArea.setText(s);
        private class BJTextArea extends JTextArea implements AdjustmentListener
            protected static final int BUF_SIZE = 4096; // display 4kB at a time
            protected String data;
            protected int len, startIndex = 0, endIndex = 0;
            private java.awt.FontMetrics fontMetrics;
            private int val = 0;
            public BJTextArea()
                super();
                setLineWrap(true);
                setVisible(true);
                fontMetrics = getFontMetrics(getFont());
            public void adjustmentValueChanged(AdjustmentEvent e)
                val = e.getValue();
                adjustView();
            public void setText(String s)
                data = s;
                len = data.length();
                startIndex = 0;
                if(len <= BUF_SIZE)
                    endIndex = len;
                    super.setText(data);
                else
                    endIndex = -1;
                    val = 0;
                    adjustView();
            protected void adjustView()
                if(endIndex == -1 && startIndex == 0)
                    endIndex = java.lang.Math.min(len, BUF_SIZE);
                    super.setText(data.substring(startIndex, endIndex));
                    return;
                if(len <= BUF_SIZE)
                    return;
                int startLine = scrollPane.getVerticalScrollBar().getValue() / getRowHeight();
                int linesVisible = // haven't worked out what goes here yet
                // Some way to work out whether I need to adjust things.
    }Anyway, thanks for the tips, but I think you're right, I'll stick with the BufferedJTextArea....
    If you have any ideas about checking for if the view is about to get out of range, let me know. Also, I've tried setting the vertical scrollbar's maximum value, but it ignores me (because I need it to be reflect the entire data string, not just the segment displayed). If you have any ideas, they'd be greatly appreciated.
    Cheers,
    Radish21

  • JTextArea & Gridbag layout - max size of control

    Hello everyone:
    I am currnetly using a JTextArea with the Gridbag layout. I want to limit the size of the JTextArea. Found an article when I did a "search" that says the size is actually controlled by the layout manager. Have tried setMaximunSize(), no luck. It appears the layout manager ignores this. The problem I am having is that I can set the size I want, however if the user types a lot of text in to the JTextArea, the control expands and over and "pushes" the controls below it down. How do I keep the layout manager from allowing this to happen?
    Thanks in advance, Bart

    Hello everyone:
    I am currnetly using a JTextArea with the Gridbag
    layout. I want to limit the size of the JTextArea.
    Found an article when I did a "search" that says the
    size is actually controlled by the layout manager.
    Have tried setMaximunSize(), no luck. It appears the
    layout manager ignores this. The problem I am having
    is that I can set the size I want, however if the user
    types a lot of text in to the JTextArea, the control
    expands and over and "pushes" the controls below it
    down. How do I keep the layout manager from allowing
    this to happen?
    Thanks in advance, Bart Do you wish to allow the user to enter as much text as he or she likes? If so, wrap the JTextArea in a JScrollPane and set the preferred size of the JScrollPange to the area you'd like the pane to consume. It'll listen, no doubt. :)

  • Center TEXT in JTextArea?

    Is it possible to center text in a JTextArea?
    I searched it but nothing on the web ... Is there another way to do this?
    with JTextPane or JTextEditor?
    I want just to center some text ....
    Thanks

    Do you want editable centered text or do you just want to display centered text and thought that JTextArea/JEditorPane/JTextPane was the only way to do it?
    If you just need to display centered text, you can use JLabel with HTML tags:
    Example:
    String message = "<HTML><CENTER>Centered Text!!!<BR>With line breaks even!!!</CENTER><HTML>"
    JLabel centered = new JLabel(message);

  • Problems with Text&Catalog search Wizards for JDeveloperStudio10131

    Hi,
    <?xml version='1.0' encoding='windows-1252'?>
    <extensions xmlns="http://xmlns.oracle.com/jdeveloper/905/extensions">
    <feature>
    <group name="Text Search Extensions">
    <group name="Text Wizard">
    <description>Text Search Wizard</description>
    <extension>
    <addin>oracle.text.wizards.textsearch.WizardAddinTextSearch</addin>
    <gallery>
    <name>oracle.text.wizards.textsearch.WizardAddinTextSearch</name>
    <description>Text Wizard</description>
    <help>Text Wizard</help>
    <category>General</category>
    <folder>Oracle Text Wizards</folder>
    </gallery>
    </extension>
    </group>
    </group>
    <help>
    <helpURL>TextWizard10.1.0.3.0.1.jar!/help/TextWizard_help.hs</helpURL>
    </help>
    </feature>
    </extensions>
    ================= Extensions ==============
    Severe(2,388): No class def found for addin oracle.text.wizards.textsearch.WizardAddinTextSearch
    Severe(2,386): No class def found for addin oracle.text.wizards.catsearch.WizardAddinCatSearch
    ========================================
    Can anybody help me?
    Regards
    Boris

    Take the MyClass from the top of the page and the following actionPerformed and other class:
    public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
    String ae = actionEvent.getActionCommand();
    System.out.println(ae);
    if(ae.equals("Button")){
    String strArea = text.area.getText();
    String toFind = search.getText();
    begin = strArea.indexOf(toFind);
    end = toFind.length()+begin;
    text.highlight(begin,end);
    public class MyAreaClass extends javax.swing.JFrame implements MouseListener, ActionListener, ClipboardOwner {
    protected JPanel fullPanel;
    public JTextArea area;
    /** Creates new Full */
    public MyAreaClass() {
    fullPanel = new JPanel();
    fullPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    String content = "Here is some content....";
    area = new JTextArea(content);
    area.append(content2);
    area.setSelectionColor(Color.red);
    Font f = new Font("Arial",0,11);
    area.setFont(f);
    area.setEditable(true);
    int x=0,y=0,x2,y2;
    double xt,yt;
    Dimension d = new Dimension(x,y);
    d = Toolkit.getDefaultToolkit().getScreenSize();
    xt = d.getWidth();
    yt = d.getHeight();
    x2 = (int) xt;
    x2 = x2/50*49;
    y2 = (int) yt;
    y2 /= 3;
    Dimension d2 = new Dimension(x2,y2);
    area.setPreferredSize(d2);
    area.addMouseListener(this);
    fullPanel.add(new JScrollPane(area));
    }

  • How to select multiple substring in JTextarea at the same time?

    I want to select multiple substring in a jtextarea at the same time by select(start,end) method, turns out only the last substring is highlighted, how to implement my goal?

    jamesybaby wrote:
    What you got so far? A SCCEE would be nice?my aim is to search key words in jtextarea and highlight all matched result.
    package frame;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class FrmSelect extends JFrame {
        public FrmSelect() throws HeadlessException {
            setSize(800, 600);
            final JTextField tfKey = new JTextField();
            tfKey.setPreferredSize(new Dimension(200, 20));
            final JTextArea taContent = new JTextArea();
            JScrollPane jsp = new JScrollPane(taContent);
            tfKey.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    String key = tfKey.getText();
                    String content = taContent.getText();
                    String[] splited = content.split(key);
                    Pattern ptn = Pattern.compile(key, Pattern.CASE_INSENSITIVE + Pattern.MULTILINE);
                    Matcher matcher = ptn.matcher(content);
                    taContent.requestFocusInWindow();
                    while (matcher.find()) {
                        int start = matcher.start();
                        int end = matcher.end();
                        taContent.select(start, end);
            add(tfKey,BorderLayout.SOUTH);
            add(jsp,BorderLayout.CENTER);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
        public static void main(String[] args) {
             new FrmSelect();
    }please copy below into the jtextarea and type key 'prop' in the jtextfield, press return.
    prop1adsfasfd
    prop2adsfasdfadsf
    prop3asdfasdfasdf

  • Currently have JTextArea, but would like the output to be in a JTable...

    Hi there. I asked this question in the database section, but I ended up getting more questions and separating code, etc. Needless to say, my initial question went unanswered. So, for the purposes of this question, let me get this one thing out of the way:
    Yes, I know this is one big file, and that I should have the GUI and DB separated. However, this is for a small project that I'm working on, and for the moment, I'm not too worried about separating class files. As long as the program works as I want it too, so much the better for me.
    Now, on to the question at hand. Currently, I have a project that connects to a MySQL DB, and it displays the output from an SQL command in a JTextArea. It looks horribly ugly, as all the columns are not formatted properly. Take a look:
    http://img508.imageshack.us/img508/2193/testxe4.jpg
    Sure I can see columns, but I would love for the output to be displayed in a neat JTable, which is also much easier on the eyes.
    Here is the current code:
    package classes;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.sql.*;
    import java.util.*;
    public class SQLClient extends JApplet {
         private Connection connection;
         private Statement statement;
         private JTextArea jtasqlCommand = new JTextArea();
         private JTextArea jtaSQLResult = new JTextArea();
         JTextField jtfUsername = new JTextField();
         JPasswordField jpfPassword = new JPasswordField();
         JButton jbtExecuteSQL = new JButton("Execute SQL Command");
         JButton jbtClearSQLCommand = new JButton("Clear");
         JButton jbtConnectDB1 = new JButton("Connect to Database");
         JButton jbtClearSQLResult = new JButton("Clear Result");
         Border titledBorder1 = new TitledBorder("Enter a SQL Command");
         Border titledBorder2 = new TitledBorder("SQL Execution Result");
         Border titledBorder3 = new TitledBorder("Enter Database Information");
         JLabel jlblConnectionStatus1 = new JLabel("");
         JLabel jlblConnectionStatus2 = new JLabel("Not Connected");
         public void init() {
              JScrollPane jScrollPane1 = new JScrollPane(jtasqlCommand);
              jScrollPane1.setBorder(titledBorder1);
              JScrollPane jScrollPane2 = new JScrollPane(jtaSQLResult);
              jScrollPane2.setBorder(titledBorder2);
              JPanel jPanel1 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
              jPanel1.add(jbtClearSQLCommand);
              jPanel1.add(jbtExecuteSQL);
              JPanel jPanel2 = new JPanel();
              jPanel2.setLayout(new BorderLayout());
              jPanel2.add(jScrollPane1, BorderLayout.CENTER);
              jPanel2.add(jPanel1, BorderLayout.SOUTH);
              jPanel2.setPreferredSize(new Dimension(100, 100));
              JPanel jPanel3 = new JPanel();
              jPanel3.setLayout(new BorderLayout());
              jPanel3.add(jlblConnectionStatus1, BorderLayout.CENTER);
              jPanel3.add(jbtConnectDB1, BorderLayout.EAST);
              JPanel jPanel4 = new JPanel();
              jPanel4.setLayout(new GridLayout(4, 1, 10, 5));
              jPanel4.add(jtfUsername);
              jPanel4.add(jpfPassword);
              JPanel jPanel5 = new JPanel();
              jPanel5.setLayout(new GridLayout(4, 1));
              jPanel5.add(new JLabel("Username"));
              jPanel5.add(new JLabel("Password"));
              JPanel jPanel6 = new JPanel();
              jPanel6.setLayout(new BorderLayout());
              jPanel6.setBorder(titledBorder3);
              jPanel6.add(jPanel4, BorderLayout.CENTER);
              jPanel6.add(jPanel5, BorderLayout.WEST);
              JPanel jPanel7 = new JPanel();
              jPanel7.setLayout(new BorderLayout());
              jPanel7.add(jPanel3, BorderLayout.SOUTH);
              jPanel7.add(jPanel6, BorderLayout.CENTER);
              JPanel jPanel8 = new JPanel();
              jPanel8.setLayout(new BorderLayout());
              jPanel8.add(jPanel2, BorderLayout.CENTER);
              jPanel8.add(jPanel7, BorderLayout.WEST);
              JPanel jPanel9 = new JPanel();
              jPanel9.setLayout(new BorderLayout());
              jPanel9.add(jlblConnectionStatus2, BorderLayout.EAST);
              jPanel9.add(jbtClearSQLResult, BorderLayout.WEST);
              this.add(jPanel8, BorderLayout.NORTH);
              this.add(jScrollPane2, BorderLayout.CENTER);
              this.add(jPanel9, BorderLayout.SOUTH);
              jbtExecuteSQL.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
              executeSQL();
              jbtConnectDB1.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
              connectToDB();
              jbtClearSQLCommand.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
              jtasqlCommand.setText(null);
              jbtClearSQLResult.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
              jtaSQLResult.setText(null);
         private void connectToDB() {
              String driver = "com.mysql.jdbc.Driver";
              String url = "jdbc:mysql://localhost:3306/petstore2002";
              String username = jtfUsername.getText().trim();
              String password = new String(jpfPassword.getPassword());
              try {
                   Class.forName(driver);
                   connection = DriverManager.getConnection(url, username, password);
                   jlblConnectionStatus2.setText("Connected To Database");
              catch (java.lang.Exception ex) {
                   ex.printStackTrace();
         private void executeSQL() {
              if (connection == null) {
                   jtaSQLResult.setText("Please connect to a database first");
                   return;
              else {
                   String sqlCommands = jtasqlCommand.getText().trim();
                   String[] commands = sqlCommands.replace('\n', ' ').split(";");
                   for (String aCommand: commands) {
                        if (aCommand.trim().toUpperCase().startsWith("SELECT")) {
                             processSQLSelect(aCommand);
                        else {
                             processSQLNonSelect(aCommand);
         private void processSQLSelect(String sqlCommand) {
              try {
                   statement = connection.createStatement();
                   ResultSet resultSet = statement.executeQuery(sqlCommand);
                   int columnCount = resultSet.getMetaData().getColumnCount();
                   String row = "";
                   for (int i = 1; i <= columnCount; i++) {
                        row += resultSet.getMetaData().getColumnName(i) + "\t";
                   jtaSQLResult.append(row + '\n');
                   while (resultSet.next()) {
                        row = "";
                        for (int i = 1; i <= columnCount; i++) {
                             row += resultSet.getString(i) + "\t";
                        jtaSQLResult.append(row + '\n');
              catch (SQLException ex) {
                   jtaSQLResult.setText(ex.toString());
         private void processSQLNonSelect(String sqlCommand) {
              try {
                   statement = connection.createStatement();
                   statement.executeUpdate(sqlCommand);
                   jtaSQLResult.setText("SQL command executed");
              catch (SQLException ex) {
                   jtaSQLResult.setText(ex.toString());
         public static void main(String[] args) {
              SQLClient applet = new SQLClient();
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setTitle("Interactive SQL Client");
              frame.getContentPane().add(applet, BorderLayout.CENTER);
              applet.init();
              applet.start();
              frame.setSize(800, 600);
              Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
              frame.setLocation((d.width - frame.getSize().width) / 2,
              (d.height - frame.getSize().height) / 2);
              frame.setVisible(true);
    }Right now it works fine, and I am planning on using this as an initial prototype for the presentation. Can I get some help on getting the output displayed into a JTable? How would I go abouts doing the conversion? I'm fairly new to Java (taking a course on it), and I'm worried that if I change one line of code the whole thing will get ruined and I'll need to start from scratch.

    -> It sounds like you're getting annoyed with the amount of people asking perfectly legitimate questions
    Your expectations are not legitimate. We attempt to understand your problem and give you the resources to solve the problem. Many times those resources are in the form of a tutorial or a reference to the API. We are not here to write code for you.
    I pointed you in the right direction. Its up to you do to some learning on your own. You have not made the slightest effort to understand how to use a JTable. You have not made the slightest effort to search the forum to see if you question has been asked before (it has).
    Your attitude and effort determines how much effort we make. Frankly you have made no effort whatsoever to solve you problem so as far as I am concerned you are on you own. Apparently I am not the only one who thinks you should be making more of an effort based on all the other advice you have received.

  • InputVerifier for JTextArea problem

    Hello,
    I am having a problem with using an InputVerifier to check a max character limit on a JTextArea. It seems that occasionally after the verify of the JTextArea fails, I lose the next character I type into it! Here is the code, followed by a description of how to reproduce the problem. Note this code is copied from the Java 1.4.2 API documentation of the InputVerifier class, with the first JTextField changed to a JTextArea and the verify method modified:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Frame;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import javax.swing.InputVerifier;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    public class TestJTextArea  extends JFrame {
        public TestJTextArea () {
           JTextArea ta = new JTextArea ("");
           ta.setPreferredSize(new Dimension(100, 50));
           getContentPane().add (ta, BorderLayout.NORTH);
           ta.setInputVerifier(new PassVerifier());
           JTextField tf2 = new JTextField ("TextField2");
           getContentPane().add (tf2, BorderLayout.SOUTH);
           WindowListener l = new WindowAdapter() {
               public void windowClosing(WindowEvent e) {
                   System.exit(0);
           addWindowListener(l);
        class PassVerifier extends InputVerifier {
            public boolean verify(JComponent input) {
                JTextArea jText = (JTextArea)input;
                boolean retValue = jText.getText().length() < 5;
                if (!retValue) {
                    System.out.println("MAX CHARS");
                return retValue;
        public static void main(String[] args) {
            Frame f = new TestJTextArea ();
           f.pack();
           f.setVisible(true);
    }A way to reproduce the problem is type in the TextArea: "123455", then Ctrl+Tab and the verify will fail. Then backspace twice to delete the "55" and Ctrl+Tab to move to the TextField. Then Tab again to go back to the TextArea and type any charachter over than 5. About 80% of the time, the character that you type will be lost and not appear in the TextArea. It doesn't always happen, but if you try it a few times it will come up. Also, occasionally the backspace keystroke is also lost in the TextArea. Note this only happens when I use Tab. I am not able to reproduce it by using the mouse to change focus.
    I have searched for a bug report on this, but have found nothing. Am I doing something wrong? I am simply using the sample code from the InputVerifier JavaDoc, but with a JTextArea... This is on a WinXP Pro machine with Java Std. Ed. 1.4.2.
    Thank you for your help.
    Angel

    JTextField jtf = (JTextField)comboBox.getEditor().getEditorComponent();
    jtf.setInputVerifier(new YourInputVerifier());

Maybe you are looking for

  • I have a password protected site in iweb, but how do I get my users to "sign out" so there not always logged in

    I built a password protected site in iweb and its published through mobileme. How do I get users to "sign out" so there not always logged in

  • 'mount -n -o remount,ro / ' not working

    Hi, I need to run fsck on my ext3 root partition (mountpoint /) and upon dropping into single user mode, I am trying to mount the partition read-only using the command mount -n -o remount,ro / but I get an error saying that / is either already mounte

  • Cannot update ipod, unknown error (-208)

    Hello, For the past two months I've been using an 80GB iPod with my MacBook Pro, automatically syncing every few days, without a hitch. Suddenly, every time I try to update the iPod, I get an error to the effect of "iPod <foo> cannot be updated. Unkn

  • How to allow non domain users to map to print drivers?

    Greetings, We have a Windows Server 2008 (non R2) 32 bit server that acts as print server. It's also on a domain. Users who are on the domain can easily add the print driver simply by going to device and printers and clicking Add Printer and selectin

  • Wide table in two pages

    Hello! Can anyone help with this problem: There is a wide table, that can't fit in one page A4. I want to print it like this: *Page. 1* Material     Column-1    Column-2   Column-3 1.  table     0,0001         -------------   ------------- 2.  chair