1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| public class DemoImageInTextPane {
private final static String IMAGE1 = "C:\\Temp\\image1.png";
private final static String IMAGE2 = "C:\\Temp\\image2.png";
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1));
final JTextPane textpane = new JTextPane();
populateTextPane(textpane,IMAGE1);
panel.add(textpane);
final JLabel label = new JLabel("Texte", new ImageIcon(IMAGE1), JLabel.LEFT);
panel.add(label);
mainPanel.add(panel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 2));
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
JButton button1 = new JButton("JTextPane");
buttonPanel.add(button1);
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
populateTextPane(textpane, IMAGE2);
}
});
JButton button2 = new JButton("JLabel");
buttonPanel.add(button2);
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setIcon(new ImageIcon(IMAGE2));
}
});
frame.getContentPane().add(mainPanel);
frame.setSize(200,200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void populateTextPane(JTextPane textpane, String imagePath) {
try {
StyledDocument document = (StyledDocument)textpane.getDocument();
document.remove(0, document.getLength()); // effacetr le texte précédent
document.insertString(document.getLength(), "Du texte ", null);
Style imageStyle = document.addStyle("ImageStyle", null);
StyleConstants.setIcon(imageStyle, new ImageIcon(imagePath));
document.insertString(document.getLength(), "\ufffc", imageStyle);
document.insertString(document.getLength(), " encore du texte", null);
} catch (BadLocationException e){
e.printStackTrace();
}
}
} |
Partager