Hi everyone,
I'm having trouble inserting icons into a textpane and I'm not sure why. I'd like to set up a textpane and then be able to insert and display images in that textpane during runtime. As a test I've written the code below for a simple GUI with a textpane and a button - when the button is pressed I want the image to appear in the text pane under the text that's already there.
If anyone can point out where I'm going wrong here, or if there is a better way to go about this, I'd be very grateful.
Thanks!
package inserticon;
import javax.swing.ImageIcon;
public class Display extends javax.swing.JFrame
{
// Variables
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextPane jTextPane1;
// Constructor
public Display()
{
initComponents();
}
// Method to intialise the GUI
private void initComponents()
{
jScrollPane1 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextPane1.setFont(new java.awt.Font("Tahoma", 0, 16));
jTextPane1.setText("Some fairly boring text.");
jScrollPane1.setViewportView(jTextPane1);
jButton1.setFont(new java.awt.Font("Tahoma", 0, 16));
jButton1.setText("Insert icon");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 446, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE))
.addContainerGap())
);
pack();
}
// Method it insert an icon into the textpane when the button is pressed.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
jTextPane1.insertIcon( new ImageIcon( "icon.png" ) );
}
}