4 Replies - 17129 Views - Last Post: 05 December 2010 - 04:26 PM Rate Topic: -----

#1 meks08  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 13-September 10

Java GUI - Click button to display image

Posted 03 December 2010 - 05:26 PM

So I have to write a program. When the load button is clicked, a file choose should appear. That works. Then once the file is chosen, it should display in on the open area that I have in the gui (upper left corner and middle area). How would I go about displaying that image once I get it loaded?

Here is my code


   import java.lang.String.*;
   import java.lang.Exception.*;
   import javax.swing.*;
   import java.awt.*;
   import java.awt.event.*;

   public class ImageProcessor extends JFrame implements ActionListener{
    // instance variables
      private static final int FRAME_WIDTH = 975;
      private static final int FRAME_HEIGHT = 725;
   
      private static final int FRAME_X_ORIGIN = 150;
      private static final int FRAME_Y_ORIGIN = 250;
   
      private static final int SIDE_BUTTON_WIDTH = 150;
      private static final int SIDE_BUTTON_HEIGHT = 150;
      private static final int BOTTOM_BUTTON_WIDTH = 80;
      private static final int BOTTOM_BUTTON_HEIGHT = 30;
   
      private JButton stats;
      private JButton resize;
      private JButton brighten;
      private JButton darken;
      private JButton load;
      private JButton quit;
   		      	
      JFileChooser chooser;
      String choosertitle;
   
      public static void main(String[] args){
         ImageProcessor frame = new ImageProcessor();
         frame.setVisible(true);
      	
      
       
      }
   
    /**
     * Constructor for objects of class Calculate
     */
      public ImageProcessor(){
         Container contentPane;
    
      
      
        //Set the frame properties
         setSize         (FRAME_WIDTH, FRAME_HEIGHT);
         setResizable    (false);
         setTitle        ("Image Processor");
         setLocation     (FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
      
         contentPane = getContentPane();
         contentPane.setLayout(null);
         contentPane.setBackground( Color.white );
      
        //Create and Place the Buttons on the frame
         stats = new JButton("Stats");
         stats.setBounds(825, 0, SIDE_BUTTON_WIDTH, SIDE_BUTTON_HEIGHT);
         contentPane.add(stats);
      
         resize = new JButton("Resize");
         resize.setBounds(825, 150, SIDE_BUTTON_WIDTH, SIDE_BUTTON_HEIGHT);
         contentPane.add(resize);
      
         brighten = new JButton("Brighten");
         brighten.setBounds(825, 300, SIDE_BUTTON_WIDTH, SIDE_BUTTON_HEIGHT);
         contentPane.add(brighten);
      	
         darken = new JButton("Darken");
         darken.setBounds(825, 450, SIDE_BUTTON_WIDTH, SIDE_BUTTON_HEIGHT);
         contentPane.add(darken);
      	
         load = new JButton("Load");
         load.setBounds(392, 650, BOTTOM_BUTTON_WIDTH, BOTTOM_BUTTON_HEIGHT);
         contentPane.add(load);
      	
         quit = new JButton("Quit");
         quit.setBounds(503, 650, BOTTOM_BUTTON_WIDTH, BOTTOM_BUTTON_HEIGHT);
         contentPane.add(quit);
      
      
        //Register this frame as an Action listener of the buttons
         stats.addActionListener(this);
         resize.addActionListener(this);
         brighten.addActionListener(this);
         darken.addActionListener(this);
         load.addActionListener(this);
         quit.addActionListener(this);
      	
         add(load);
      
        //Exit program when the viewer is closed
         setDefaultCloseOperation(EXIT_ON_CLOSE);
      }
   
    //Event handler
      public void actionPerformed(ActionEvent event){
         if(event.getSource() instanceof JButton){
            
         
         
         	
            JButton clickedButton = (JButton) event.getSource();
         
            String buttonText = clickedButton.getText();
                        
            
            
               if(buttonText.equals("Stats")){    
                                 
               }
            	
               if(buttonText.equals("Resize")){
               						
               }
            	
               if(buttonText.equals("Brighten")){
               
               }
            	
               if(buttonText.equals("Darken")){
               
               }
            	
               if(buttonText.equals("Load")){
               
                  chooser = new JFileChooser(); 
                  chooser.setCurrentDirectory(new java.io.File("."));
                  chooser.setDialogTitle(choosertitle);
                  chooser.setAcceptAllFileFilterUsed(true);
               
               
                  if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { 
                     System.out.println("getCurrentDirectory(): " 
                        +  chooser.getCurrentDirectory());
                     System.out.println("getSelectedFile() : " 
                        +  chooser.getSelectedFile());
                  }
                  else {
                     System.out.println("No Selection ");
                  }
               	
               
               
               
               }
            	
               if(buttonText.equals("Quit")){
                  System.exit(0);
               }
               
         
         
         }
               
      }
   	 	
   	
   }




Is This A Good Question/Topic? 0
  • +

Replies To: Java GUI - Click button to display image

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10469
  • View blog
  • Posts: 38,809
  • Joined: 27-December 08

Re: Java GUI - Click button to display image

Posted 03 December 2010 - 06:17 PM

You could read the image in as an ImageIcon, and pass it to a JLabel using the setIcon() method, and add the JLabel to the JFrame. That would be the easiest way.
Was This Post Helpful? 0
  • +
  • -

#3 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2871
  • View blog
  • Posts: 11,026
  • Joined: 15-July 08

Re: Java GUI - Click button to display image

Posted 03 December 2010 - 06:48 PM

Like mac siad, there are a variety of ways. I cover 2 in my Image Manipulation Tutorials: http://www.dreaminco...part-1-loading/
Was This Post Helpful? 0
  • +
  • -

#4 meks08  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 13-September 10

Re: Java GUI - Click button to display image

Posted 05 December 2010 - 12:44 PM

Ok. I still don't get how to exactly get the image into the original JFrame. I added more on to my code. Under the displayGrayScaleImage method, it should display the image in the JFrame. I know how to display it in another new window as you can see it in other methods below it but what do I need to change to get it in the original JFrame?


 import java.awt.BorderLayout;
   import java.awt.image.BufferedImage;
   import java.io.File;
   import java.io.IOException;
   import javax.imageio.ImageIO;
   import javax.swing.ImageIcon;
   import javax.swing.JFrame;
   import javax.swing.JLabel;
   import java.util.*;
   import java.text.DecimalFormat;
   import java.lang.String.*;
   import java.lang.Exception.*;
   import javax.swing.*;
   import java.awt.*;
   import java.awt.event.*;

   public class ImageProcessor extends JFrame implements ActionListener{
    // instance variables
    
      static Scanner scanner = new Scanner(System.in);
      static DecimalFormat df = new DecimalFormat("0.00");
    
      private static final int FRAME_WIDTH = 975;
      private static final int FRAME_HEIGHT = 725;
   
      private static final int FRAME_X_ORIGIN = 150;
      private static final int FRAME_Y_ORIGIN = 250;
   
      private static final int SIDE_BUTTON_WIDTH = 150;
      private static final int SIDE_BUTTON_HEIGHT = 150;
      private static final int BOTTOM_BUTTON_WIDTH = 80;
      private static final int BOTTOM_BUTTON_HEIGHT = 30;
   
      private JButton stats;
      private JButton resize;
      private JButton brighten;
      private JButton darken;
      private JButton load;
      private JButton quit;
   	
      public static JLabel image;
   		      	
      JFileChooser chooser;
      String choosertitle;
      static String fileName;
      
   	
   
   
   
      public static void main(String[] args){
         ImageProcessor frame = new ImageProcessor();
         frame.setVisible(true);
      	
      
       
      }
   
    /**
     * Constructor for objects of class Calculate
     */
      public ImageProcessor(){
         Container contentPane;
      
      
      
        //Set the frame properties
         setSize         (FRAME_WIDTH, FRAME_HEIGHT);
         setResizable    (false);
         setTitle        ("Image Processor");
         setLocation     (FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
      
         contentPane = getContentPane();
         contentPane.setLayout(null);
         contentPane.setBackground( Color.white );
      
        //Create and Place the Buttons on the frame
         stats = new JButton("Stats");
         stats.setBounds(825, 0, SIDE_BUTTON_WIDTH, SIDE_BUTTON_HEIGHT);
         contentPane.add(stats);
      
         resize = new JButton("Resize");
         resize.setBounds(825, 150, SIDE_BUTTON_WIDTH, SIDE_BUTTON_HEIGHT);
         contentPane.add(resize);
      
         brighten = new JButton("Brighten");
         brighten.setBounds(825, 300, SIDE_BUTTON_WIDTH, SIDE_BUTTON_HEIGHT);
         contentPane.add(brighten);
      	
         darken = new JButton("Darken");
         darken.setBounds(825, 450, SIDE_BUTTON_WIDTH, SIDE_BUTTON_HEIGHT);
         contentPane.add(darken);
      	
         load = new JButton("Load");
         load.setBounds(392, 650, BOTTOM_BUTTON_WIDTH, BOTTOM_BUTTON_HEIGHT);
         contentPane.add(load);
      	
         quit = new JButton("Quit");
         quit.setBounds(503, 650, BOTTOM_BUTTON_WIDTH, BOTTOM_BUTTON_HEIGHT);
         contentPane.add(quit);
      	
         
			
			JLabel image = new JLabel("Display Image Text ");
         image.setBounds(10, 0, 100, 100);
         contentPane.add(image);
      	
      
      	
      
      
        //Register this frame as an Action listener of the buttons
         stats.addActionListener(this);
         resize.addActionListener(this);
         brighten.addActionListener(this);
         darken.addActionListener(this);
         load.addActionListener(this);
         quit.addActionListener(this);
      	
      
        //Exit program when the viewer is closed
         setDefaultCloseOperation(EXIT_ON_CLOSE);
      }
   
    //Event handler
      public void actionPerformed(ActionEvent event){
         if(event.getSource() instanceof JButton){
            
         
         
         	
            JButton clickedButton = (JButton) event.getSource();
         
            String buttonText = clickedButton.getText();
                        
            if(buttonText.equals("Load")){
               
               chooser = new JFileChooser(); 
               chooser.setCurrentDirectory(new java.io.File("."));
               chooser.setDialogTitle(choosertitle);
               chooser.setAcceptAllFileFilterUsed(true);
               
               
               if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { 
                  fileName = chooser.getSelectedFile().getAbsolutePath();
                
					  /* 
                 System.out.println("getCurrentDirectory(): " 
                        +  chooser.getCurrentDirectory());
                  System.out.println("getSelectedFile() : " 
                        +  chooser.getSelectedFile());
               			*/
               			
                  int arr[][] = readImageintoArray(fileName);
                  displayGrayscaleImage(arr); 
               
               }
               else {
                  System.out.println("No Selection ");
               }
            
               
            }
            
            if(buttonText.equals("Stats")){     
               int arr[][] = readImageintoArray(fileName);
               computeImageStatistics(arr);               
            }
            	
            if(buttonText.equals("Resize")){ 
               int arr[][] = readImageintoArray(fileName);
               resizeImage(arr);					
            }
            	
            if(buttonText.equals("Brighten")){  
               int arr[][] = readImageintoArray(fileName);
               brightenImage(arr);
            	
            }
            	
            if(buttonText.equals("Darken")){
               int arr[][] = readImageintoArray(fileName);					
               darkenImage(arr); 
            }
            	
         
            	
            if(buttonText.equals("Quit")){
               System.exit(0);
            }
              
         
         
         }
               
      }
   	
      public static int[][] readImageintoArray(String fileName) {
         File f = new File(fileName);
         BufferedImage readimage = null;
         try {
            readimage = ImageIO.read(f);
         } 
            catch (IOException e) {
               e.printStackTrace();
            }
         int imageWidth = readimage.getWidth();
         int imageHeight = readimage.getHeight();
      
        // fix the sizes of RGB arrays according to the size of the image
      
         int[][] GrayScaleData = new int[imageWidth][imageHeight];
         for (int i = 0; i < imageHeight; i++) {
            for (int j = 0; j < imageWidth; j++) {
               int pixel = readimage.getRGB(j, i);
            
               GrayScaleData[j][i] = (((pixel >> 16) & 0xff) + ((pixel >> 8) & 0xff) + ((pixel) & 0xff)) / 3;            
            }
         }
         return GrayScaleData;
      }
   
    // This function displays the array as a grayscale image
      public static void displayGrayscaleImage(int arr[][]) {
         int imageWidth = arr.length;
         int imageHeight = arr[0].length;
      
         BufferedImage showImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_4BYTE_ABGR);
         for (int i = 0; i < imageHeight; i++) {
            for (int j = 0; j < imageWidth; j++) {
               int grayscale = (((255 << 24) + (arr[j][i] << 16) + (arr[j][i] << 8) + arr[j][i]));
               showImage.setRGB(j, i, grayscale);
            }
         }
        // This is a frame object that displays the image.
         image = new JLabel(new ImageIcon(showImage));
         frame.getContentPane().add(image);
         frame.pack();
         frame.setVisible(true);
              
      }
    
   // This function computes the image statistics (max, min, average, and standard deviation)
      public static void computeImageStatistics(int arr[][]) {
      
      // The max value in the array is found by using loops
         int maxValue = arr[0][0];   	
         for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
               if (arr[i][j] > maxValue) {
                  maxValue = arr[i][j];
               }
            }
         }
         // The max value is printed
         System.out.println("Max Value is: " + maxValue);
        
      // The min value of the array is found 
         int minValue = arr[0][0];   	
         for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
               if (arr[i][j] < minValue) {
                  minValue = arr[i][j];
               }
            }
         } 
            // The min value is printed
         System.out.println("Min value is: " + minValue);
         
          // Variables to get the average
         double average = 0;
         double sum = 0;
         double count = 0;
          
          // The sum of all the values is calculated in this loop
         for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
               sum += arr[i][j];
               count++;
            }
         }
          	
          	// The average is calculated by dividing the sum by the total amount of entries
         average = sum/count;
          	
          	// The average is printed
         System.out.println("Average is: " + df.format(average));
          	
          // Variables to get the standard deviation
         double standardDeviation = 0;
         sum = 0;
              
          // The sum of each entry minus the average squared
         for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
               sum += (Math.pow(arr[i][j] - average,2.0));
               count ++;	  
            }
         }
          
          // The standard deviation is calculated by dividing the sum by the (count - 1)
         standardDeviation = Math.sqrt((sum/(count-1)));
          
          // The standard deviation is printed
         System.out.println("Standard Deviation: " + df.format(standardDeviation));  	  
        
         return;    
      }
   
    // This funstion brightens the image by a percent that the user enters
      public static void brightenImage(int arr[][]){
      
      // The user is prompted how much to brighten the image by and then brightenAmount is set to that
         double brightenAmount = 0;
         System.out.println("Please enter how much you want to brighten the image (in %): ");
         brightenAmount = (scanner.nextDouble() * .01);
      
         int imageWidth = arr.length;
         int imageHeight = arr[0].length;
      
      // An array arrBright is created and then each value is assigned 
      // the original value of array arr and then is multiplied by the amount to brighten the image by
         int arrBright[][] = new int[imageWidth][imageHeight];
         for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
               arrBright[i][j] = ((int) (arr[i][j] * brightenAmount)) + (arr[i][j]);
               if (arrBright[i][j] > 255) {
                  arrBright[i][j] = 255;
               }
            } 
         }
        
         BufferedImage brightImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_4BYTE_ABGR);
         for (int i = 0; i < imageHeight; i++) {
            for (int j = 0; j < imageWidth; j++) {
               int brightGrayscale = (((255 << 24) + (arrBright[j][i] << 16) + (arrBright[j][i] << 8) + arrBright[j][i]));
               brightImage.setRGB(j, i, brightGrayscale);
            }
         }
            
            // This is a frame object that displays the image.
         JFrame frame = new JFrame();
         JLabel label = new JLabel(new ImageIcon(brightImage));
         frame.getContentPane().add(label, BorderLayout.CENTER);
         frame.pack();
         frame.setVisible(true);
      
         return;
      }
   
      public static void darkenImage(int arr[][]){
      
      // The user is prompted how much to darken the image by and then darkenAmount is set to that
         double darkenImage = 0;
         System.out.println("Please enter how much you want to darken the image (in % of the original 0 = black 100 = original): ");
         darkenImage = (scanner.nextDouble() * .01);
      
         int imageWidth = arr.length;
         int imageHeight = arr[0].length;
      
      
      // An array arrDark is created and then each value is assigned 
      // the original value of array arr and then is multiplied by the amount to darken the image by
         int arrDark[][] = new int[imageWidth][imageHeight];
         for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
               arrDark[i][j] = ((int)(arr[i][j] * darkenImage)) ;
               if (arrDark[i][j] < 0) {
                  arrDark[i][j] = 0; 
               }
            } 
         }
      
      
        
         BufferedImage darkImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_4BYTE_ABGR);
         for (int i = 0; i < imageHeight; i++) {
            for (int j = 0; j < imageWidth; j++) {
               int darkGrayscale = (((255 << 24) + (arrDark[j][i] << 16) + (arrDark[j][i] << 8) + arrDark[j][i]));
               darkImage.setRGB(j, i, darkGrayscale);
            }
         }
            
            // This is a frame object that displays the image.
         JFrame frame = new JFrame();
         JLabel label = new JLabel(new ImageIcon(darkImage));
         frame.getContentPane().add(label, BorderLayout.CENTER);
         frame.pack();
         frame.setVisible(true);
      
      
         return;
      } 
    
      public static void resizeImage(int arr[][]){
      
         int imageWidth = arr.length;
         int imageHeight = arr[0].length;
      
        // A new array arrResize is created and its size is 1/2 of the array arr.
         int arrResize[][] = new int[(imageWidth/2)][(imageHeight/2)];
      
      // The values of the original array in groups of 4 ( 2 X 2) are average into 1 pixel
      // These pixels are assigned to places in the array arrResize
         int k = 0;
         int l = 0;
         for (int i = 0; i < (imageWidth); i+=2) {
            for (int j = 0; j < (imageHeight); j+=2) {
               int avg = (arr[i][j] + arr[i][j+1] + arr[i+1][j] + arr[i+1][j+1])/4;
               arrResize[l][k] = avg;
               k ++;
            }
            k = 0;
            l ++;
         } 
      
         BufferedImage resizeImage = new BufferedImage((imageWidth/2), (imageHeight/2), BufferedImage.TYPE_4BYTE_ABGR);
         for (int i = 0; i < (imageHeight/2); i++) {
            for (int j = 0; j < (imageWidth/2); j++) {
               int resizeGrayscale = (((255 << 24) + (arrResize[j][i] << 16) + (arrResize[j][i] << 8) + arrResize[j][i]));
               resizeImage.setRGB(j, i, resizeGrayscale);
            }
         }
            
            // This is a frame object that displays the image.
         JFrame frame = new JFrame();
         JLabel label = new JLabel(new ImageIcon(resizeImage));
         frame.getContentPane().add(label, BorderLayout.CENTER);
         frame.pack();
         frame.setVisible(true);
      
      
         return;
      
      
      }
   
   	
   
   	 	
   	
   }



Was This Post Helpful? 0
  • +
  • -

#5 meks08  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 13-September 10

Re: Java GUI - Click button to display image

Posted 05 December 2010 - 04:26 PM

Sorry for a double post but couldn't edit my last post now.

Here is my updated code parts.

            if(buttonText.equals("Load")){
               chooser = new JFileChooser(); 
               chooser.setCurrentDirectory(new java.io.File("."));
               chooser.setDialogTitle(choosertitle);
               chooser.setAcceptAllFileFilterUsed(true);
               
               if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { 
                   //File file = chooser.getSelectedFile(); 
                   fileName = chooser.getSelectedFile().getAbsolutePath();
                
//                 System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
//                 System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
               			
                   int arr[][] = readImageintoArray(fileName);
                   BufferedImage showImage = displayGrayscaleImage(arr);
                  
			       Container contentPane = getContentPane();
		           showImageLabel = new JLabel(new ImageIcon(showImage));
		           showImageLabel.setBounds(0,0, 500,500);
		           contentPane.add(showImageLabel);





I had it displaying part of the image someway but now I don't have any of the image displayed this way. Any help is very much appreciated.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1