Results 1 to 19 of 19
  1. #1
    mystified is offline Member
    Join Date
    Sep 2008
    Posts
    21
    Rep Power
    0

    Default Help With JavaSwing - JFileChooser

    I have created a JButton which on actionevent calls a constructor of a second class in a separate file. The second file contains a 'select file' button which on clicking should open up a dialogbox for the user to select a file. I have used Jfilechooser for this purpose. The problem is When I click on 'select file' nothing happens. The following two are the respective files.

    Ex.java
    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    
    public class Ex extends JFrame {
    JPanel p;    
    JButton bound;
    
    public static void main(String [] args) {
    Ex m=new Ex();
    }
    
    public Ex() {
    p = new JPanel();
    bound=new JButton("Bound");
    p.add(bound);
    this.getContentPane().add(p);
    this.setSize(500,500);
    this.setVisible(true);
    JBound b1=new JBound(); bound.addActionListener(b1);
    }
    
    class JBound implements ActionListener {
    public void actionPerformed(ActionEvent bdy) {
    Object obj3=bdy.getSource();
    if(obj3==bound) {
    Boundary bd=new Boundary();
    }
    }
    }    
    }


    Boundary.java
    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.File;
    
    public class Boundary {
    JFrame frame;
    JButton button;
    JPanel p1;
    	  
    public Boundary() {
    frame = new JFrame("JComboBox Test");
    button = new JButton("Select File");
    p1=new JPanel();
    
    button.setBounds(700,170,110,27); p1.add(button);
    p1.setLayout(null);
    p1.setBackground(Color.lightGray);
               		frame.getContentPane().add(p1);
    frame.pack();
    frame.setVisible(true);
    
    JBrowse bro = new JBrowse();
    button.addActionListener(bro);
    }
    
    public class JBrowse implements ActionListener { 
        	public void actionPerformed(ActionEvent bu) { 
        		Object obj8=bu.getSource();
                if(obj8==button) {
                        JFileChooser fileChooser = new JFileChooser();
            int returnValue = fileChooser.showOpenDialog(null);
            if (returnValue == JFileChooser.APPROVE_OPTION) {
              File selectedFile = fileChooser.getSelectedFile();
              System.out.println(selectedFile.getName());
    }
    }
    }
    }
    }

    Any help? And I am using the JFileChooser to open and display the image chosen. So if possible, can someone please tell me how to do that too..?

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    1) Avoid using null layout.
    2) You use null layout, don't set preferredSize and then call pack() on the JFrame which is causing your Boundary JFrame to be really really tiny.
    3) Read the Sun tutorials on the layout managers.

    Also, when I clicked on Select File, it worked fine.
    Last edited by Fubarable; 09-18-2008 at 03:12 AM.

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,266
    Rep Power
    25

    Default

    When I click on 'select file' nothing happens
    Do some debugging to see where the code is executing. Do this by adding println statements in the actionPerformed method to see if it is being called and with what args.

  4. #4
    serjant's Avatar
    serjant is offline Senior Member
    Join Date
    Jun 2008
    Location
    Ukraine,Zaporozhye
    Posts
    487
    Rep Power
    7

    Default

    Of course it only prints the name of the selected file in console.

  5. #5
    mystified is offline Member
    Join Date
    Sep 2008
    Posts
    21
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    1) Avoid using null layout.
    2) You use null layout, don't set preferredSize and then call pack() on the JFrame which is causing your Boundary JFrame to be really really tiny.
    3) Read the Sun tutorials on the layout managers.

    Also, when I clicked on Select File, it worked fine.
    Thank You :) Is there a way to display an image based on RGB values?

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,266
    Rep Power
    25

    Default

    display an image based on RGB values
    Can you explain a bit more? Is the image in a file on disk or are you creating it in a program?

  7. #7
    mystified is offline Member
    Join Date
    Sep 2008
    Posts
    21
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Can you explain a bit more? Is the image in a file on disk or are you creating it in a program?
    The image is in the disk.. I need to display the image and then after I enter RGB values(in separate textboxes), and press enter or extract, only the corresponding pixels which match the entered RGB values of the image has to be displayed.

    Any help plz..

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,266
    Rep Power
    25

    Default

    Here's the code to get the pixels from an image. I'll leave the rest to you (or maybe hardwired will give you the code)

    int[] pixels = new int[w * h];
    try {
    PixelGrabber pg = new PixelGrabber(
    image, 0, 0, w, h, pixels, 0, w);
    pg.grabPixels();
    ...

  9. #9
    mystified is offline Member
    Join Date
    Sep 2008
    Posts
    21
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Here's the code to get the pixels from an image. I'll leave the rest to you (or maybe hardwired will give you the code)
    Thanx mate :) I haven't tried it out yet.. Gtg to coll. now.. Ll try it in the evening..

    Who is hardwired btw?

  10. #10
    mystified is offline Member
    Join Date
    Sep 2008
    Posts
    21
    Rep Power
    0

    Default

    I managed to convert the image into a grayscale..

    Any idea how I can display only the pixelx which match the RGB values I enter?

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,266
    Rep Power
    25

    Default

    What do you want to happen to the other pixels?

    What is the Alpha value for?
    Last edited by Norm; 09-20-2008 at 04:27 PM.

  12. #12
    mystified is offline Member
    Join Date
    Sep 2008
    Posts
    21
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    What do you want to happen to the other pixels?

    What is the Alpha value for?
    alpha value?

    And I just want the pixels matching the same RGB values to be displayed.. Just Ignore the other pixels.. Its like if I enter 255 for Red and 0 for Green And Blue, Only the pixels corresponding to 255 for Red should be printed..

  13. #13
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,266
    Rep Power
    25

    Default

    Only the pixels corresponding to 255 for Red should be printed..
    How are you printing the pixels? I thought you were displaying an image.

    Alpha has to do with transparency. A 0 value means transparent (ie invisible)

  14. #14
    mystified is offline Member
    Join Date
    Sep 2008
    Posts
    21
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    How are you printing the pixels? I thought you were displaying an image.

    Alpha has to do with transparency. A 0 value means transparent (ie invisible)
    No No I meant displayed.. sorry wrong use of term.. I want the pixels to be displayed..

    Oh.. thanx for that info :)

  15. #15
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    using the JFileChooser to open and display the image chosen. So if possible, can someone please tell me how to do that too
    How to Use File Choosers
    Reading/Loading an Image

    Any idea how I can display only the pixelx which match the RGB values I enter?
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.swing.*;
    
    public class OneColor implements ActionListener {
        Color[] colors = {
            Color.green.darker(), Color.red, Color.cyan,
            Color.blue, Color.magenta
        };
        Color color = colors[0];
        BufferedImage image;
        JLabel right;
    
        public OneColor() {
            initImage();
        }
    
        public void actionPerformed(ActionEvent e) {
            int index = ((JComboBox)e.getSource()).getSelectedIndex();
            color = colors[index];
            right.setIcon(new ImageIcon(strip()));
        }
    
        private JScrollPane getContent() {
            JPanel panel = new JPanel(new GridLayout(1,0,5,0));
            panel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
            panel.add(wrap(image));
            panel.add(right = wrap(strip()));
            return new JScrollPane(panel);
        }
    
        private BufferedImage strip() {
            int target = color.getRGB();
            int count = 0;
            int w = image.getWidth();
            int h = image.getHeight();
            int type = BufferedImage.TYPE_INT_ARGB_PRE;
            BufferedImage dst = new BufferedImage(w, h, type);
            for(int y = 0; y < h; y++) {
                for(int x = 0; x < w; x++) {
                    int pixel = image.getRGB(x, y);
                    if(pixel == target) {
                        dst.setRGB(x, y, target);
                        count++;
                    }
                }
            }
            System.out.printf("color = [%3d, %3d, %3d]  count = %d%n",
                               color.getRed(), color.getGreen(),
                               color.getBlue(), count);
            return dst;
        }
    
        private JLabel wrap(BufferedImage image) {
            ImageIcon icon = new ImageIcon(image);
            return new JLabel(icon, JLabel.CENTER);
        }
    
        private void initImage() {
            int w = 300;
            int h = 300;
            int type = BufferedImage.TYPE_INT_RGB;
            image = new BufferedImage(w, h, type);
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setBackground(colors[0]);
            g2.clearRect(0,0,w,h);
            g2.setPaint(colors[1]);
            g2.fillOval(40,40,100,100);
            g2.setPaint(colors[2]);
            g2.fillOval(65,65,50,50);
            g2.setPaint(colors[3]);
            g2.fillRect(160,160,100,100);
            g2.setPaint(colors[4]);
            g2.fillRect(185,185,50,50);
            g2.dispose();
        }
    
        private JPanel getLast() {
            String[] items = { "green", "red", "cyan", "blue", "magenta" };
            JComboBox comboBox = new JComboBox(items);
            comboBox.addActionListener(this);
            JPanel panel = new JPanel();
            panel.add(comboBox);
            return panel;
        }
    
        public static void main(String[] args) {
            OneColor test = new OneColor();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(test.getContent());
            f.add(test.getLast(), "Last");
            f.pack();
            f.setLocation(200,200);
            f.setVisible(true);
        }
    }

  16. #16
    mystified is offline Member
    Join Date
    Sep 2008
    Posts
    21
    Rep Power
    0

    Default

    @hardwired:

    Thanx.. :) that code worked fine though I couldn't figure out how to implement the same in my code..

    I have succeeded in displaying the image and getting the RGB values..

    I need to compare the input rgb values with each pixel of the image and display the pixel if the comparison matches..

    This is my code..

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.File;
    import java.applet.*;
    import javax.imageio.*;
    import java.io.*;
    
     
    public class Color1 extends Applet {
    	JFrame frame, frame1;
    	JButton button1, extract;
    	JPanel p1;
        Image img;
        JTextField file, tr, tg, tb;
        
        public static void main(String [] args) {
    	Color1 C=new Color1();
    	}
    	
    	public Color1() {
    		
    		Font f1=new Font("Book Antiqua",Font.BOLD,45);
    		
    		frame1 = new JFrame("Feature Extraction: Color");
    		
    		file = new JTextField(100);
    		file.setEditable(false);
    		tr = new JTextField(4);
    		tg = new JTextField(4);
    		tb = new JTextField(4);
    		
       		JLabel L1=new JLabel("Feature Extraction: Color");	
       		L1.setFont(f1);	
       				
    		JLabel R = new JLabel("Red");
    		JLabel G = new JLabel("Green");
    		JLabel B = new JLabel("Blue");
    		
    		extract = new JButton("Extract");
    		button1 = new JButton("Select File");
    
    		p1=new JPanel();
    		
    		L1.setBounds(210,70,650,90);		
    		R.setBounds(150,270,70,27);
    		G.setBounds(300,270,70,27);
    		B.setBounds(450,270,70,27);
    		file.setBounds(150,170,500,27);
    		tr.setBounds(200,270,70,27);
    		tg.setBounds(350,270,70,27);
    		tb.setBounds(500,270,70,27);
    		extract.setBounds(600,270,100,27);
    		button1.setBounds(700,170,130,27); 		
    
    		p1.add(R);
    		p1.add(G);
    		p1.add(B);
    		p1.add(file);
    		p1.add(tr);
    		p1.add(tg);
    		p1.add(tb);
    		p1.add(extract);
    		p1.add(L1);
    		p1.add(button1);
    		
    		p1.setLayout(null);
    		p1.setBackground(Color.lightGray);
    		frame1.getContentPane().add(p1);
        	frame1.setSize(500,500);
        	frame1.setVisible(true);
        	frame1.pack();
    
    		JExtract ext = new JExtract();
    		extract.addActionListener(ext);
    		
    		JBrowse bro = new JBrowse();
    		button1.addActionListener(bro);
    		}
    
    	public class JBrowse implements ActionListener { 
        	public void actionPerformed(ActionEvent bu) { 
        		Object objcolor=bu.getSource();
                if(objcolor==button1) {
            		frame = new JFrame();     
            		JFileChooser jFileChooser1 = new javax.swing.JFileChooser();
    	      		java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    	        	frame.setLocation((screenSize.width-500)/2,(screenSize.height-300)/2);
            		int returnVal = jFileChooser1.showOpenDialog(frame);
            		if (returnVal == jFileChooser1.APPROVE_OPTION) {
                       		File fi = jFileChooser1.getSelectedFile();
    			            String path = fi.getPath();
    			            System.out.println(path);
    			            ImageIcon icon = new ImageIcon(path);
    			            frame.getContentPane().add(new JLabel(icon));
    			            frame.pack();
    			            frame.setVisible(true);
    			            file.setText(path);
            				}
           			}			
          		}	
    		}
    	
    	public class JExtract implements ActionListener { 
        	public void actionPerformed(ActionEvent ex) { 
        		Object objextract=ex.getSource();
                if(objextract==extract) {
                	String redval= tr.getText();
                	String greenval=tg.getText();
                	String blueval=tb.getText();
                	System.out.println(redval+"\t"+greenval+"\t"+blueval);
                //Code To Display Extracted Image
                	}
        		}
    		}			
    }

  17. #17
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    Java Code:
    	public class JExtract implements ActionListener { 
        	public void actionPerformed(ActionEvent ex) { 
        		Object objextract=ex.getSource();
                if(objextract==extract) {
                	String redval= tr.getText();
                	String greenval=tg.getText();
                	String blueval=tb.getText();
                	System.out.println(redval+"\t"+greenval+"\t"+blueval);
                    // Parse these strings to [i]int[/i] values
                    // and make a color (see Color class api
                    // Constructor Summary for some ideas).
                    // Make a new BufferedImage using this color
                    // and the current image as shown in OneColor.
                    // Display the new image.
                //Code To Display Extracted Image
                	}
        		}
    		}

  18. #18
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.filechooser.FileFilter;
    
    public class FilterColor implements ActionListener {
        JFileChooser fileChooser;
        BufferedImage image;
        JLabel label;
        JSpinner[] spinners;
        boolean showSource = true;
    
        public FilterColor() {
            fileChooser = new JFileChooser("images");
            fileChooser.setAcceptAllFileFilterUsed(false);
            fileChooser.setFileFilter(new ImageFilter());
        }
    
        public void actionPerformed(ActionEvent e) {
            String ac = e.getActionCommand();
            if(ac.equals("OPEN")) {
                openDialog();
            } else {
                showSource = ac.equals("SOURCE");
                if(image != null) {
                    showImage();
                }
            }
        }
    
        private void openDialog() {
            if(fileChooser.showOpenDialog(label) == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                try {
                    image = javax.imageio.ImageIO.read(file);
                } catch(IOException e) {
                    System.out.println("read error: " + e.getMessage());
                }
                showImage();
            }
        }
    
        private void showImage() {
            ImageIcon icon;
            if(showSource) {
                icon = new ImageIcon(image);
            } else {
                icon = new ImageIcon(filterImage());
            }
            label.setIcon(icon);
        }
    
        private BufferedImage filterImage() {
            Color color = getColor();
            int target = color.getRGB();
            int count = 0;
            int w = image.getWidth();
            int h = image.getHeight();
            int type = BufferedImage.TYPE_INT_ARGB_PRE;
            BufferedImage dst = new BufferedImage(w, h, type);
            for(int y = 0; y < h; y++) {
                for(int x = 0; x < w; x++) {
                    int pixel = image.getRGB(x, y);
                    if(pixel == target) {
                        dst.setRGB(x, y, target);
                        count++;
                    }
                }
            }
            System.out.printf("color = [%3d, %3d, %3d]  count = %d%n",
                               color.getRed(), color.getGreen(),
                               color.getBlue(), count);
            return dst;
        }
    
        private Color getColor() {
            int r = ((Integer)spinners[0].getValue()).intValue();
            int g = ((Integer)spinners[1].getValue()).intValue();
            int b = ((Integer)spinners[2].getValue()).intValue();
            return new Color(r, g, b);
        }
    
        private JScrollPane getCenterComponent() {
            label = new JLabel((ImageIcon)null);
            label.setHorizontalAlignment(JLabel.CENTER);
            return new JScrollPane(label);
        }
    
        private JPanel getControls() {
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            panel.add(getActionPanel(), gbc);
            panel.add(getSpinnerPanel(), gbc);
            return panel;
        }
    
        private Box getActionPanel() {
            String[] ids = { "open", "source", "filtered" };
            ButtonGroup group = new ButtonGroup();
            Box box = Box.createHorizontalBox();
            AbstractButton button;
            for(int i = 0; i < ids.length; i++) {
                if(i > 0) {
                    button = new JRadioButton(ids[i], i==1);
                    group.add(button);
                    box.add(button);
                } else {
                    button = new JButton(ids[i]);
                    box.add(Box.createHorizontalGlue());
                    box.add(button);
                    box.add(Box.createHorizontalGlue());
                }
                button.setActionCommand(ids[i].toUpperCase());
                button.addActionListener(this);
            }
            box.add(Box.createHorizontalGlue());
            return box;
        }
    
        private JPanel getSpinnerPanel() {
            spinners = new JSpinner[3];
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weightx = 1.0;
            spinners[0] = add("red",   200, panel, gbc);
            spinners[1] = add("green", 100, panel, gbc);
            spinners[2] = add("blue",  150, panel, gbc);
            return panel;
        }
    
        private JSpinner add(String s, int value, Container c,
                             GridBagConstraints gbc) {
            SpinnerNumberModel model = new SpinnerNumberModel(value, 0, 255, 1);
            JSpinner spinner = new JSpinner(model);
            gbc.anchor = GridBagConstraints.EAST;
            c.add(new JLabel(s), gbc);
            gbc.anchor = GridBagConstraints.WEST;
            c.add(spinner, gbc);
            return spinner;
        }
    
        public static void main(String[] args) {
            FilterColor test = new FilterColor();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(test.getCenterComponent());
            f.add(test.getControls(), "Last");
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
        }
    }
    
    class ImageFilter extends FileFilter {
        static final String BMP  = "bmp";
        static final String GIF  = "gif";
        static final String JPG  = "jpg";
        static final String JPEG = "jpeg";
        static final String PNG  = "png";
    
        public boolean accept(File file) {
            if(file.isDirectory()) {
                return true;
            }
            String ext = getExtension(file);
            return ext.equals(BMP) || ext.equals(GIF)  ||
                   ext.equals(JPG) || ext.equals(JPEG) ||
                   ext.equals(PNG);
        }
    
        public String getDescription() {
            return BMP + ", " + GIF  + ", " + JPG +
                         ", " + JPEG + ", " + PNG;
        }
    
        private String getExtension(File file) {
            String s = file.getPath();
            int dot = s.lastIndexOf(".");
            if(dot > -1 && dot < s.length()) {
                return s.substring(dot+1);
            }
            return null;
        }
    }

  19. #19
    mystified is offline Member
    Join Date
    Sep 2008
    Posts
    21
    Rep Power
    0

    Default

    @hardwired:

    that code was perfect-o..

    thanx a lot mate :) I was able to link it to my code though there really was no problem at all.. :)

Similar Threads

  1. Need JFileChooser Help
    By Wraithier in forum New To Java
    Replies: 4
    Last Post: 06-18-2008, 05:40 PM
  2. Localize JFileChooser
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 03-14-2008, 11:54 AM
  3. JFileChooser remember the location
    By Mr tuition in forum AWT / Swing
    Replies: 3
    Last Post: 12-08-2007, 05:17 PM
  4. JFileChooser/Scanner/openFileReader
    By Feng in forum New To Java
    Replies: 5
    Last Post: 11-24-2007, 04:31 PM
  5. how to use JFileChooser
    By tommy in forum New To Java
    Replies: 1
    Last Post: 08-06-2007, 08:49 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •