我想知道如何複製JTextPane中的圖像和文本。 當我使用此代碼時,它只複製文本,但我想複製文本和圖像。如何做到這一點?如何在JTextPane java中複製圖像?
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
/**
*
* @author admin
*/
public class Main extends JFrame implements KeyListener, ActionListener{
public static JTextPane textPane;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
JFrame Frame = new Main();
Frame.setVisible(true);
Frame.setSize(400, 400);
}
public Main()
{
JMenuBar mb = new JMenuBar();
setJMenuBar(mb);
JMenu menu = new JMenu("File");
JMenuItem mi = new JMenuItem("select all");
mi.addActionListener(this);
menu.setMnemonic(KeyEvent.VK_F);
menu.add(mi);
mi = new JMenuItem("copy");
mi.addActionListener(this);
menu.add(mi);
mi = new JMenuItem("Exit");
mi.addActionListener(this);
menu.add(mi);
mi = new JMenuItem("insert image");
mi.addActionListener(this);
menu.add(mi);
mb.add(menu);
textPane = new JTextPane();
JScrollPane scrollPane = new JScrollPane(textPane);
getContentPane().add(scrollPane);
}
public void keyTyped(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void keyPressed(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void keyReleased(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void actionPerformed(ActionEvent e) {
String cmd=e.getActionCommand();
if ("Exit".equals(cmd)) {
System.exit(0);
} else if ("select all".equals(cmd)) {
textPane.selectAll();
}
else if ("copy".equals(cmd)) {
textPane.copy();
}
else if("insert image".equals(cmd))
{
try {
JFileChooser file = new JFileChooser();
file.showOpenDialog(null);
File selFile = file.getSelectedFile();
Image img = ImageIO.read(selFile);
textPane.insertIcon(new ImageIcon(img));
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}