Maxenboy
Maxenboy

Reputation: 63

How to select and retrieve a String of a whole line of text in a JtextArea?

I have a JFrame that displays the current movies that are stored on my computer. It displays the names of the files as Strings in a JTextArea.

What I want to do is to double-click a particular String (which represents an actual file on my computer) and that file would be opened.

The opening part and double-click part is already solved, but when I double-click on the String in my JTextArea only a part of that String will be selected. (I'm using JTextArea.getSelectedText()).

What I want is that the whole String is selected and that I can retrieve the String. I need to do this since some of my movie files have similar names and the wrong file would be opened.

Is there any already implemented method that can extend the selection to a whole line? I've tried to Google the problem but nothing will select the whole line of text.

An example: http://i47.tinypic.com/wvol6a.png


Thank you all for the input and I'm sorry that i was unclear regarding the JTextArea, the JTextArea was mandatory.

I have now a solution to my problem and I thank Hovercraft Full Of Eels for this.

Upvotes: 6

Views: 5759

Answers (5)

Sam
Sam

Reputation: 7868

Basically, you'd need to extract the line from that JTextArea. But I recommend you switch to a component, which is more appropriate for your use case: http://docs.oracle.com/javase/6/docs/api/javax/swing/JList.html

Anyway, you could try a quick and dirty hack like this:

public static String getLineOfSelectionStart(JTextArea textArea) {
    String contents = textArea.getText();
    int selStart = textArea.getSelectionStart();

    if (selStart >= 0) {
        int selEnd = selStart; // don't use getSelectionEnd(), since one
                                // could select multiple lines;

        while (selStart > 0) {
            switch (contents.charAt(selStart)) {
            case '\r':
            case '\n':
                break;
            default:
                --selStart;
                continue;
            }
            break;
        }
        while (selEnd < contents.length()) {
            switch (contents.charAt(selEnd)) {
            case '\r':
            case '\n':
                break;
            default:
                ++selEnd;
                continue;
            }
            break;
        }

        return contents.substring(selStart, selEnd);
    }
    return null;
}

But really, twiddling around with String when listing a large amount of files will not perform so well.

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

Your best bet is to use a JList as has been recommended by many above. If you have to use a JTextArea, then this can be done, but you will need to use JTextArea's viewToModel(Point p) method to translate the mouse press location's Point to the offset location in your text. You can then use the javax.swing.text.Utilities class's static utility methods, getRowStart(...) and getRowEnd(...) to find the start and end of the selected row. For example, my SSCCE:

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;
import javax.swing.text.Utilities;

public class GetLineFromTextArea {
   private static final int MIN_CHARS = 4;
   private static final int MAX_CHARS = 8;
   private static final int WORDS_PER_LINE = 10;
   private static final int ROWS = 30;

   public static void main(String[] args) {
      Random random = new Random();
      final JTextArea textArea = new JTextArea(20, 50);
      JScrollPane scrollpane = new JScrollPane(textArea);
      StringBuilder sb = new StringBuilder();

      for (int row = 0; row < ROWS ; row++) {
         sb = new StringBuilder();
         for (int words = 0; words < WORDS_PER_LINE; words++) {
            int maxChars = random.nextInt(MAX_CHARS - MIN_CHARS) + MIN_CHARS;
            for (int charsPerWord = 0; charsPerWord < maxChars; charsPerWord++) {
               char c = (char) (random.nextInt('z' - 'a' + 1) + 'a');
               sb.append(c);
            }
            sb.append(" ");
         }
         textArea.append(sb.toString() + "\n");
      }

      textArea.addMouseListener(new MouseAdapter() {
         @Override
         public void mouseClicked(MouseEvent e) {
            if (e.getButton() != MouseEvent.BUTTON1) {
               return;
            }
            if (e.getClickCount() != 2) {
               return;
            }

            int offset = textArea.viewToModel(e.getPoint());

            try {
               int rowStart = Utilities.getRowStart(textArea, offset);
               int rowEnd = Utilities.getRowEnd(textArea, offset);
               String selectedLine = textArea.getText().substring(rowStart, rowEnd);
               System.out.println(selectedLine);

            } catch (BadLocationException e1) {
               e1.printStackTrace();
            }

         }
      });


      JOptionPane.showMessageDialog(null, scrollpane);
   }
}

Upvotes: 4

Joseph Farrugia
Joseph Farrugia

Reputation: 327

Use a JList and to retrieve the selected option use the getSelectedIndex() to retrieve the index or use the getSelectedValue() to get the value.

See here: see on getSelectedIndex() method

Upvotes: 0

Jakub Zaverka
Jakub Zaverka

Reputation: 8874

Consider using a JList instead of JTextArea. JList allows you to select an element out of some set. So you just fill this set with whatever strings you need abd let the user choose.

Upvotes: 3

duffy356
duffy356

Reputation: 3716

i think a JList would be more appropriate for your needs.

simple example: http://www.cs.cf.ac.uk/Dave/HCI/HCI_Handout_CALLER/node143.html

Or is there a need to use a JTextArea?

Upvotes: 2

Related Questions