java中如何在JTextArea中添加图片?
发布网友
发布时间:2023-07-17 08:35
我来回答
共2个回答
热心网友
时间:2024-12-01 08:57
JTextPane 是可以做的,
import java.io.File;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class 文本窗格里的组件和图标 extends JFrame {
private JFileChooser chooser = new JFileChooser();
private JTextPane textPane = new JTextPane();
public 文本窗格里的组件和图标() {
Container contentPane = getContentPane();
JMenuBar menuBar = new JMenuBar();
JMenu insertMenu = new JMenu("Insert");
JMenuItem imageItem = new JMenuItem("image"),
chooserItem = new JMenuItem("color chooser");
insertMenu.add(imageItem);
insertMenu.add(chooserItem);
menuBar.add(insertMenu);
setJMenuBar(menuBar);
textPane.setFont(new Font("Serif", Font.ITALIC, 24));
contentPane.add(textPane, BorderLayout.CENTER);
chooserItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JColorChooser chooser = new JColorChooser();
chooser.setMaximumSize(
chooser.getPreferredSize());
textPane.insertComponent(chooser);
}
});
imageItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int option =
chooser.showDialog(文本窗格里的组件和图标.this,"Pick An Image");
if(option == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
if(file != null) {
textPane.insertIcon(new ImageIcon(
file.getPath()));
}
}
}
});
}
public static void main(String args[]) {
GJApp3.launch(new 文本窗格里的组件和图标(),
"Using JTextPane",300,300,450,300);
}
}
class GJApp3 extends WindowAdapter {
static private JPanel statusArea = new JPanel();
static private JLabel status = new JLabel(" ");
public static void launch(final JFrame f, String title,
final int x, final int y,
final int w, int h) {
f.setTitle(title);
f.setBounds(x,y,w,h);
f.setVisible(true);
statusArea.setBorder(BorderFactory.createEtchedBorder());
statusArea.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));
statusArea.add(status);
status.setHorizontalAlignment(JLabel.LEFT);
f.setDefaultCloseOperation(
WindowConstants.DISPOSE_ON_CLOSE);
f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
}
static public JPanel getStatusArea() {
return statusArea;
}
static public void updateStatus(String s) {
status.setText(s);
}
}
热心网友
时间:2024-12-01 08:58
JTextArea 对应于 PlainDocument, 不支持 插入图片之类Rich Text。
想插入图片需要使用JTextPane。
JTextPane textPane = new JTextPane();
StyledDocument doc = (StyledDocument) textPane.getDocument();
Style style = doc.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon("imagefile"));
doc.insertString(doc.getLength(), "ignored text", style);