Clickable text in JTextArea?

Hi all,
I'm writing a program that populates a textarea with medical terms and such. And, the problem is I need to give an explanation to the more difficult words by allowing the user to click on the words and a popup window with the explanations will appear. I'm not familiar with the mouse clicks technology in Java, so please help if you can!
Also, any suggestions on how the data can be stored/retrieved when I'm using a MySQL database?
Many thanks!

For this you have to add mouse listener in a text area. So that on mouse click you can do something.
try following code, Run it and double click on some word.
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class TextAreaDemo extends JPanel{
private JTextArea text = null, answer = null;
public TextAreaDemo(){
text=new JTextArea("Hi all,\nI'm writing a program that populates a textarea with medical terms and " +
"such. And, the problem is I need to give an explanation to the more difficult words " +
"by allowing the user to click on the words and a popup window with the explanations " +
"will appear. I'm not familiar with the mouse clicks technology in Java, so please " +
"help if you can!\n\nAlso, any suggestions on how the data can be stored/retrieved " +
"when I'm using a MySQL database?\n\nMany thanks!");
answer=new JTextArea(3, 20);
answer.setEditable(false);
setLayout(new BorderLayout());
add(new JScrollPane(text));
add(new JScrollPane(answer), BorderLayout.SOUTH);
text.addMouseListener(new MyMouseListener());
class MyMouseListener extends MouseAdapter{
public void mouseClicked(MouseEvent e){
if(e.getClickCount() == 2){
answer.setText("Do you want to know about:\n\t" + text.getSelectedText());
public static void main(String argv[]){
JFrame frame=new JFrame();
frame.setContentPane(new TextAreaDemo());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
May help you.
Regards,

Similar Messages

  • TextArea with formatted Text, Hyperlinks, and clickable Text with SWING?

    Hi again,
    Ok if I decide to use Swing, is there any TextArea which supports Formatted Text Hyperlinks AND clickable Text wich calls a callback routine??? I think formatted Text and Hyperlinks are possible with JTextArea and the RTF editorKit, but clickable text, in order to controll the program in some way???
    Could anyone help me?
    Greets

    Try the JEditorPane class.See the intro exapmle at the top of
    [url=http://java.sun.com/j2se/1.4.2/docs/api/javax/swin
    /JEditorPane.html] this page.That seems to be the solution! Can I use the JTextPane, too? Does a DefaultStyledEditorKit support Hyperlinks and Hyperlinklisteners, too?
    In order to realize callback functions I have to insert a HTML-Anchor with the Attribute as the Parameter for my method. Then my HyperlinkListener catches the HyperlinkEvent and the hyperlinkUpdate method reminds the parameter!
    Is that right?
    Thank you very much!
    Greets

  • How to print diffrent color and diffrent size of text in JTextArea ?

    Hello All,
    i want to make JFrame which have JTextArea and i append text in
    JTextArea in diffrent size and diffrent color and also with diffrent
    fonts.
    any body give me any example or help me ?
    i m thanksfull.
    Arif.

    You can't have multiple text attributes in a JTextArea.
    JTextArea manages a "text/plain" content type document that can't hold information about attributes ( color, font, size, etc.) for different portions of text.
    You need a component that can manage styled documents. The most basic component that can do this is JEditorPane. It can manage the following content types :
    "text/rtf" ==> via StyledDocument
    "text/html" ==> via HTMLDocument
    I've written for you an example of how a "Hello World" string could be colorized in a JEditorPane with "Hello" in red and "World" in blue.
    import javax.swing.JEditorPane;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyledEditorKit;
    import javax.swing.text.StyledDocument;
    import javax.swing.text.MutableAttributeSet;
    import javax.swing.text.SimpleAttributeSet;
    import java.awt.Color;
    public class ColorizeTextTest{
         public static void main(String args[]){
              //build gui
              JFrame frame = new JFrame();
              JEditorPane editorPane = new JEditorPane();
              frame.getContentPane().add(editorPane);
              frame.pack();
              frame.setVisible(true);
              //create StyledEditorKit
              StyledEditorKit editorKit = new StyledEditorKit();
              //set this editorKit as the editor manager [JTextComponent] <-> [EditorKit] <-> [Document]
              editorPane.setEditorKit(editorKit);
              StyledDocument doc = (StyledDocument) editorPane.getDocument();
              //insert string "Hello World"
              //this text is going to be added to the StyledDocument with positions 0 to 10
              editorPane.setText("Hello World");
              //create and attribute set
              MutableAttributeSet atr = new SimpleAttributeSet();
              //set foreground color attribute to RED
              StyleConstants.setForeground(atr,Color.RED);
              //apply attribute to the word "Hello"
              int offset = 0; //we want to start applying this attribute at position 0
              int length = 5; //"Hello" string has a length of 5
              boolean replace = false; //should we override any other attribute not specified in "atr" : anwser "NO"
              doc.setCharacterAttributes(offset,length,atr,replace);
              //set foreground color attribute to BLUE
              StyleConstants.setForeground(atr,Color.BLUE);
              //apply attribute to the word "World"
              offset = 5; //we include the whitespace
              length = 6;
              doc.setCharacterAttributes(offset,length,atr,replace);
    }

  • Centering Text in JTextArea

    How can I center texts in JTextArea?
    "jta.setAlignemtX(CENTER)" +
    "jta.setAlignemtY(CENTER)" dont work.
    I need a little assistense.
    Dirk

    I apologize for the above wrong answer!
    Why dont u use a JTextPane instead of JTextArea
    JTextPane text=new JTextPane();
    SimpleAttributeSet set=new SimpleAttributeSet();
    StyledDocument doc=text.getStyledDocument();
    StyleConstants.setAlignment(set,StyleConstants.ALIGN_CENTER);
    text.setParagraphAttributes(set,true);

  • How to display giant text in JTextArea???

    hi!.......how can i display lets say 20mbs of text in JTextArea?......i try to display but it only show till 2-3mb then the rest is empty.....anyone knows how?

    Hi, I don't know how.
    But I know that it wouldn't be so nice loading 20/30 Mb of text at once. You could load a smaller amount of data like 1 Mb and show it. Then when the user scrolls to bottom you could load more text.
    pseudocode :
    - load some text and show it
    - while true
    if user scrolls down
    * actualize text showed loading more text if necesary
    if user scrolls up
    * actualize text showed
    - end while
    Hope it helps.

  • Highlighting text in JtextArea

    I want to highlight text in a JTextArea each time the text changes and therefore i use a DocumentListener and also the following :
    public Highlighter.HighlightPainter redHighlightPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.red);
    Highlighter hilite = gJTextArea.getHighlighter();
    hilite.addHighlight(bufferBegin , bufferEnd, redHighlightPainter);
    but the text remains black
    How can you explain this?
    Thanks

    I have used the same exact piece of code in a JTextArea and it works perfectly. Maybe your problem is elsewhere in the code because this should work fine. Are you sure that the Document listener is fireing when changes occur?

  • Can't update text in JTextArea! Can you help?

    [Update: If I remove the transparency everything is fine. However, I really need the transparency..]
    Hi,
    I have the simplest question, but I can't seem to get an answer to it. The problem is very simple: I have defined a JTextArea and I'm reading text into it. The problem is that the old text does not disappear, and the new text is pasted on top, making it unreadable. As an "act of desperation" I fixed this by setting the area invisible, updating it and setting it visible again, as you can see in the code. It works, but now it blinks in the screen (quite annoying!).
    Is there a smarter way to to this? I need this on a transparent window (see class init below), overlayed on another JFrame.
    I am on Mac OS X.
    I hope some of you can help me with this problem
    Thanks a lot in advance
    Lele
    public void UpdateOverlay(){
            try{
                BufferedReader b = this.ReadUrl("http://localhost/~"+System.getProperty("user.name")+"/overlaytext.txt");
                this.Overlay.setVisible(false);
                this.OverlayText.read(b, null);
                this.Overlay.setVisible(true);
            }catch(Exception e){
                e.printStackTrace();
        }Here you can see how I have initialized the class
    public class MyClass {
        //Overlay section
        public JFrame Overlay=new JFrame("Overlay");
        public Color OverlayColor=new Color(0.0f,0.0f,0.0f,0.0f);
        public JTextArea OverlayText=new JTextArea();
        public long Refresh_time=200;//ms
        /** Creates a new instance of MyClass */
        public MyClass(AWT1UpFrame f) {
            int width=270,height=170,border_x=20,border_y=20;
            //Initialize Overlay
            this.Overlay.setVisible(false);
            this.Overlay.setBackground(this.OverlayColor);
            this.Overlay.setLocationRelativeTo(null);
            this.Overlay.setUndecorated(true);
            this.Overlay.setSize(width,height);
            System.out.println("loc="+f.getLocation());
            int x = f.getLocation().x+border_x;
            int y = f.getLocation().y +f.getSize().height - border_y - height;
            this.Overlay.setLocation(x, y);
            this.Overlay.add(this.OverlayText);
            this.Overlay.setAlwaysOnTop(true);
            this.OverlayText.setLineWrap(true);
            this.OverlayText.setWrapStyleWord(true);
            this.OverlayText.setForeground(Color.GREEN);
            this.OverlayText.setBackground(this.OverlayColor);
            this.OverlayText.setFont(new Font("Arial", Font.ROMAN_BASELINE, 16));
    /* and so on*/Edited by: Lele on Oct 25, 2007 4:22 PM

    Hi, so this is the class. If I keep it like this, it simply overwrites old text with the new (like JTextArea thinks that the old text is a part of the background to be buffered). If I set it invisible and back to visible it works, but it blinks.
    How can I let JTextArea understand that it shouldn't consider the old window as a background? Should I use another class?
    Pls keep in mind that I'm on Mac, so maybe it's a Mac-specific thing, but I'd like to know..
    Thanks
    Lele
    package transparency;
    import java.net.*;
    import javax.swing.*;
    import javax.xml.parsers.*;
    import java.awt.*;
    import java.awt.font.*;
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    import java.util.List;
    import apple.awt.CTextArea;
    public class Overlay {
        //Overlay section
        public JFrame Overlay=new JFrame("Overlay");
        public Color OverlayColor=new Color(0.0f,0.0f,0.0f,0.0f);
        public JTextArea OverlayText=new JTextArea();
        public long Refresh_time=200;//ms
        /** Creates a new instance of Overlay */
        public Overlay() {
            int width=270,height=170,border_x=20,border_y=20;
            //Initialize Overlay
            this.Overlay.setVisible(false);
            this.Overlay.setBackground(this.OverlayColor);
            this.Overlay.setLocationRelativeTo(null);
            this.Overlay.setUndecorated(true);
            this.Overlay.setSize(width,height);
            //System.out.println("loc="+f.getLocation());
            //int x = f.getLocation().x+border_x;
            //int y = f.getLocation().y +f.getSize().height - border_y - height;
            //this.Overlay.setLocation(x, y);
            this.Overlay.add(this.OverlayText);
            this.Overlay.setAlwaysOnTop(true);
            this.OverlayText.setLineWrap(true);
            this.OverlayText.setWrapStyleWord(true);
            this.OverlayText.setForeground(Color.GREEN);
            this.OverlayText.setBackground(this.OverlayColor);
            this.OverlayText.setFont(new Font("Arial", Font.ROMAN_BASELINE, 16));
            this.Overlay.setVisible(true);
        public void UpdateOverlay(){
            try{
                //Reading URL
                //String Address="http://localhost/~"+System.getProperty("user.name")+"/overlaytext.txt";
                //URL url= new URL(Address);
                //BufferedReader b = new BufferedReader(new InputStreamReader(url.openStream()));
                //this.Overlay.setVisible(false);
                //this.OverlayText.read(b, null);
                //this.Overlay.setVisible(true);
                //Test
                //this.Overlay.setVisible(false);
                String RandomText="The time is: "+System.currentTimeMillis();
                this.OverlayText.setText(RandomText);
                //this.Overlay.setVisible(true);
            }catch(Exception e){
                e.printStackTrace();
    }.. and this is the main
    package transparency;
    import java.net.*;
    import javax.swing.*;
    import javax.xml.parsers.*;
    import java.awt.*;
    import java.awt.font.*;
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    import java.util.List;
    import transparency.*;
    public class Main {
        /** Creates a new instance of Main */
        public Main() {
        public static void main(String[] args) {
            JFrame f=new JFrame();
            f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
            f.setVisible(true);
            Overlay ov=new Overlay();
            try{
                while(f.isVisible()){
                    ov.UpdateOverlay();
                    Thread.sleep(100);
            }catch(Exception e){
                e.printStackTrace();
    }Edited by: Lele on Oct 26, 2007 3:40 AM

  • How to write selected text in JTextArea in selected location

    iam using JTextArea ...
    i want to writer selected text in selected location,,,,,,

    use
    JTextArea.getSelectedText() and
    JTextArea.replaceRange(String str, int start, int end)
    methods.

  • 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);

  • Set text of jtextArea to a text file

    I have tried everything in trying to let the user select a text file using jfilechooser and then set the text of a jtextArea as the text file. Nothing has worked so far, so all I have right here is the basic functionality of choosing the file.
    If someone could show me a good way to read the whole text file and put that text into a jtextArea, I would really appreciate it.
    Since nothing has worked all I have is this:
    JFileChooser chooser = new JFileChooser();
         int returnVal = chooser.showOpenDialog(this);
         String getFile = chooser.getSelectedFile().getPath();

    ... followed by theJTextArea.read(new FileReader(getFile), null);

  • How to change a predefined group of text in JTextArea

    I am adding pre defined words to a JTextArea. How can I ensure that if I want to change the text in the text area that the entire word is changed. I would like to have the capability of keeping the text in a string.
    Thank you in advance.

    Do your required process on the model level, i.e. text level or document level, and add the result using setDocument() or setText() of the JTextArea.

  • Bolding a text in JTextArea

    Hi,
    I have a JTextArea and I need to make the text appear bold? Is it possible ? I tried using html tags as shown below, but this is not working ?
    jTextArea.setText("<html><b>Hello</b></html>");
    Thanks

    then you need to use JEditorPane.
    http://javaalmanac.com/egs/javax.swing.text/style_HiliteWords2.html?l=rel

  • Centered text in JTextArea (java)

    how to center multiple line of text both vertically and horizontally in JTextArea ?

    Try:
    <html><center>text to center</center></html>
    V.V.viravan's way is the way to do it. Yoiu can use HTML for all sorts of things:
    <html><h1>text</h1></html> gives bigger text.
    <html><font color="cc3333">Set hexdecimal font color</font></html>
    You see the idea. :)

  • Select higlighted text in JTextArea

    Hello,
    I am developing a swing application and have a JTextArea included. In the JTextArea I highlight one or more words with the addHighlight method. Now the user should also be able to select text, especially the highlighted text. But when I select some highlighted text, it does not change the color, so the user is not aware that he selected text.
    How can I implement the intended behaviour?
    Thanks in advance
    Sandra

    1) Change the style of highlights so that both highlights are painted:
    DefaultHighlighter highlighter =  (DefaultHighlighter)textComponent.getHighlighter();
    highlighter.setDrawsLayeredHighlights(false);2) You need to use a different color highlighter to distinguish the highlighted text from the selected text:
    Highlighter.HighlightPainter cyanPainter =
        new DefaultHighlighter.DefaultHighlightPainter( Color.cyan );
    textComponent.getHighlighter().addHighlight( 8, 15, cyanPainter );

  • Append text in JTextArea

    greetings.. i'm having the following code:
    public class GUI extends JPanel implements ActionListener
      JTextArea theText;
      public GUI()
         // and so on and so forth that initializes the textarea
          displayToTextArea("call from inside");
    public void displayToTextArea(String message)
      theText.append(message + "\n");
    }and at another class:
    GUI theGUI = new GUI;
    theGUI.displayToConsole("call from outside");but after running, the only text appended is the "call from inside", the "call from outside" is not appended into the textarea.
    any clues?
    please advice.
    thanks. ^_^

    I think you need to show how you are using it because if I use it from a simple test harness and add what must be missing (the creation of 'theText' and the action listener method) it works OK for me.
    Make sure you have defined the number of lines for the JTextArea.
    import javax.swing.*;
    import java.awt.event.*;
    public class Test20050115
        static class GUI extends JPanel implements ActionListener
            JTextArea theText = new JTextArea(4, 50); // 4 lines
            public GUI()
                add(theText);
                // and so on and so forth that initializes the textarea
                displayToTextArea("call from inside");
            public void displayToTextArea(String message)
                theText.append(message + "\n");
            public void actionPerformed(java.awt.event.ActionEvent actionEvent)
        public static void main(String[] args)
            JFrame frame = new JFrame("Test");
            GUI gui = new GUI();
            gui.displayToTextArea("call from outside");
            frame.getContentPane().add(gui);
            frame.pack();
            frame.setVisible(true);    
    }

Maybe you are looking for

  • HP Officejet 4500 Desktop All-in-One Printer - G510a and Windows 8.1

    The drivers for this do not seem to work on Windows 8.1.  Whilst I can print no problem I cannot access the solution centre from my new laptop and i cannot scan.  It gives me the message No scan options refer to device documentation to troubleshoot. 

  • SQL LOADER USING EXTRNAL TABLE

    I have .csv file having around 70k records in which fields are delimited by tab and enclosed in double quotes but double quotes may be part of data. and records are delimited by newline. After creating external table when I issue SELECT statment sele

  • 802.1x Auth-Fail VLAN --- XP does not recognize

    With Auth-Fail VLAN configured on Cisco 3550 the Switch successfully configures the port to the configured auth-fail vlan upon unsuccessful authentication. The PC even gets the IP address from DHCP. However, the Windows XP network icon on the task ba

  • Installing Oracle Terminal on a NT 4.0 station

    We need to install oracle terminal, in order to map the page up and page down keys. The product isn't available on the install list. Has anyone else install oracle terminal in a windows environment or is there another way to map the up/down keys?

  • Scriping xhost + after server reboot

    Hi, We have Oracle Applications E-Business suite R12 running on OEL 5.4. We have a requirement that the application owner be able to create bit map reports. So we need to run xhost + as root on DISPLAY :0.0 before starting some application services.