Jose Ortiz Jose Ortiz - 3 months ago 11
Java Question

Dynamically adding ImageIcon in Java

Okay, I am a newbie at GUI stuff. I am experimenting with a simple program where you pick a color, width, height and it'll generate a png file with the specified values. My problem is adding the image icon to the label after the my generate function executes. The file is created, but the imageIcon is not displaying in the imagePanel.This is just a test I am creating.

This is where I am having trouble:

private void generateActionPerformed(java.awt.event.ActionEvent evt) {
int Width=getWidthInput();
int Height= getHeightInput();
BufferedImage image= new BufferedImage(Width,Height, BufferedImage.TYPE_INT_ARGB);
File directory= null;
BufferedImage generatedPic;
//drawing portions of image
for(int i = 0; i < Height; i++){
for(int j=0; j<Width; j++){
int a=255;
int r=getRed();
int g=getGreen();
int b=getBlue();
int p= (a<<24)|(r<<16)|(g<<8)|b;
image.setRGB(j,i,p);
}
}
try{
directory= new File("testImg.png");
ImageIO.write(image,"png",directory);
System.out.println("Image Has Been Written");
ImageIcon ii= new ImageIcon(getClass().getResource("testImg.png"));
imageLabel.setIcon(ii);
revalidate();
repaint();
}
catch(IOException e){
System.out.println("Error: "+ e);
}
directory.deleteOnExit();
}


This is the whole program:

public class MainFrame extends javax.swing.JFrame {
private JButton submitBtn;
/**
* Creates new form MainFrame
*/
public MainFrame() {
initComponents();
}

public int getRed(){
return Integer.parseInt(red.getText());
}

public int getGreen(){
return Integer.parseInt(green.getText());
}

public int getBlue(){
return Integer.parseInt(blue.getText());
}

public int getWidthInput(){
return Integer.parseInt(width.getText());
}

public int getHeightInput(){
return Integer.parseInt(height.getText());
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")

private void initComponents() {

mainPanel = new javax.swing.JPanel();
imagePanel = new javax.swing.JPanel();
imageLabel= new JLabel();


jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
red = new javax.swing.JTextField();
green = new javax.swing.JTextField();
blue = new javax.swing.JTextField();
width = new javax.swing.JTextField();
height = new javax.swing.JTextField();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
jMenu3 = new javax.swing.JMenu();
submitBtn= new JButton("Generate Image");

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

mainPanel.setForeground(new java.awt.Color(54, 136, 137));
mainPanel.setAutoscrolls(true);





jLabel2.setText("color:");

jLabel3.setText("width:");

jLabel4.setText("height:");

submitBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
generateActionPerformed(evt);
}
});

javax.swing.GroupLayout imagePanelLayout = new javax.swing.GroupLayout(imagePanel);
imagePanel.setLayout(imagePanelLayout);
imagePanelLayout.setHorizontalGroup(
imagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(imageLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 446, Short.MAX_VALUE)
);
imagePanelLayout.setVerticalGroup(
imagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(imageLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);

javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(mainPanelLayout.createSequentialGroup()
.addComponent(red, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(green, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(blue, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(width)
.addComponent(height)
.addComponent(submitBtn))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43, Short.MAX_VALUE)
.addComponent(imagePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(imagePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(mainPanelLayout.createSequentialGroup()
.addGap(50, 50, 50)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(red, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(green, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(blue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(width, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(height, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(submitBtn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(297, Short.MAX_VALUE))
);

jMenuBar1.setBackground(new java.awt.Color(54, 136, 137));

jMenu1.setText("File");
jMenuBar1.add(jMenu1);

jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);

jMenu3.setText("jMenu3");
jMenuBar1.add(jMenu3);

setJMenuBar(jMenuBar1);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);

pack();
}
private void generateActionPerformed(java.awt.event.ActionEvent evt) {
int Width=getWidthInput();
int Height= getHeightInput();
BufferedImage image= new BufferedImage(Width,Height, BufferedImage.TYPE_INT_ARGB);
File directory= null;
BufferedImage generatedPic;
//drawing portions of image
for(int i = 0; i < Height; i++){
for(int j=0; j<Width; j++){
int a=255;
int r=getRed();
int g=getGreen();
int b=getBlue();
int p= (a<<24)|(r<<16)|(g<<8)|b;
image.setRGB(j,i,p);
}
}
try{
directory= new File("testImg.png");
ImageIO.write(image,"png",directory);
System.out.println("Image Has Been Written");
ImageIcon ii= new ImageIcon(getClass().getResource("testImg.png"));
imageLabel.setIcon(ii);
revalidate();
repaint();
}
catch(IOException e){
System.out.println("Error: "+ e);
}
directory.deleteOnExit();




}




/*
private void redActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
*/
/**
* @param args the command line arguments
*/
public static void main(String args[]) throws IOException {

/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {

new MainFrame().setVisible(true);

}
});
}

// Variables declaration - do not modify
private javax.swing.JTextField blue;
private javax.swing.JTextField green;
private javax.swing.JTextField height;
private javax.swing.JLabel imageLabel;
private javax.swing.JPanel imagePanel;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel mainPanel;
private javax.swing.JTextField red;
private javax.swing.JTextField width;
// End of variables declaration
}

Answer

Since the code has already created a File, it makes perfect sense to use that file as the basis for the URL for the ImageIcon! E.G.

import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import javax.imageio.ImageIO;
import javax.swing.*;

public class SavedImageDisplayer {

    public static void main(String[] args) throws IOException {
        BufferedImage img = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB);
        final File file = new File("testImg.png");
        ImageIO.write(img, "png", file);
        Runnable r = new Runnable() {
            @Override
            public void run() {
                ImageIcon imageIcon;
                try {
                    // use the File as basis for the URL!
                    imageIcon = new ImageIcon(file.toURI().toURL());
                    JOptionPane.showMessageDialog(null, imageIcon);
                } catch (MalformedURLException ex) {
                    ex.printStackTrace();
                }
            }
        };
        SwingUtilities.invokeLater(r);
    }
}