簡體   English   中英

jTextArea,文本和圖片

[英]jTextArea, text and picture

我有一個文本,我希望將文本的特定單詞連接到圖片。

像“我有一個蘋果”一樣,“蘋果”一詞是可點擊的,它將在文本之一旁邊的jTextArea中加載一個蘋果的圖片。

我在帶有Netbeans的Swing GUI中使用jTextArea。

我認為的方法在哪里:

  1. 使用指向單詞的超鏈接。
  2. 使單詞成為某種按鈕
  3. 在單詞上使用鼠標事件。
  4. 使兩個區域同時滾動。

如我所知,選擇2和3似乎將文本放置在代碼中,而不是從文件加載文本。

如果它們位於同一行,則4不允許我使用多張圖片。

最好的實現方法是創建一個看起來像您想要的簡單html網頁,然后將JEditorPane或JTextPane與HTMLEditorKit一起使用,以將內容加載到GUI中。

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

還有一個更接近該功能的JComponent: JTextPane

嘗試這個:

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){}
            }
        });
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM