Chado
Chado

Reputation: 11

jTextArea, text and picture

I have a text and I wish to connect specific words of the text to pictures.

Like "I have an apple" the word apple will be click-able and will load the picture of an apple in the jTextArea next to the one of the text.

I am using jTextArea in Swing GUI with Netbeans.

The methods I thought where :

  1. Using hyperlinks to the words.
  2. Making the words some kind of buttons
  3. To use mouse events on the words.
  4. Make the two areas scroll at the same time.

The choices 2 and 3 seem like I will have place the text inside the code instead of loading it from file, as I do know.

4 will not allow me use multiple pictures if they are in the same line.

Upvotes: 1

Views: 62

Answers (2)

indiketa
indiketa

Reputation: 59

There's another JComponent that is more closer to that functionallity: JTextPane.

Try this:

import javax.swing.*;
import javax.swing.text.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;

class TextPaneDemo extends JFrame
{
    public void createAndShowGUI()throws Exception
    {
        JTextPane tp = new JTextPane();
        ArrayList<String> data = new ArrayList();
        data.add("Data here");
        data.add("Data here 2");
        data.add("Data here 3");
        data.add("Data here 4");
        getContentPane().add(tp);
        setSize(300,400);
        StyledDocument doc = tp.getStyledDocument();
        SimpleAttributeSet attr = new SimpleAttributeSet();
        for (String dat : data )
        {
            doc.insertString(doc.getLength(), dat, attr );
            tp.setCaretPosition(tp.getDocument().getLength());
            tp.insertComponent(new JButton("Click"));
            doc.insertString(doc.getLength(), "\n", attr );
        }

        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
    public static void main(String[] args) 
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                TextPaneDemo tpd = new TextPaneDemo();
                try
                {
                    tpd.createAndShowGUI(); 
                }
                catch (Exception ex){}
            }
        });
    }
}

Upvotes: 2

ControlAltDel
ControlAltDel

Reputation: 35106

Best way to achieve would be to create a simple html webpage that looks just like you want it, and then use a JEditorPane or a JTextPane with the HTMLEditorKit to load the content into your GUI.

http://docs.oracle.com/javase/tutorial/uiswing/components/editorpane.html

Upvotes: 2

Related Questions