Solved

Java panel for images:

Posted on 2004-04-28
39
1,575 Views
Last Modified: 2013-11-23

Hello,

Could anyone demonstrate how to display jpeg and png images in a java swing Jframe.

I understand the image will read using the bufferedimage. And anyone explain how to changed the size of the image window.

I am using the GridBagLayout to position swing objects.

Thanks

 
0
Comment
Question by:AntoniRyszard
  • 19
  • 12
  • 6
39 Comments
 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
myFrame.add(new JLabel(new ImageIcon(myImagePath)));
0
 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
Revision;
 myFrame.getContentPane().add(new JLabel(new ImageIcon(myImagePath)), constraints);
0
 

Author Comment

by:AntoniRyszard
Comment Utility

Are the constraints the size of the label?

I would prefer when the swing frame opens, a white box is displayed at a pre defined size. Then I use a menu option open to set the image in the label, or a button called open.

0
 

Author Comment

by:AntoniRyszard
Comment Utility

Could I also ask in following code, where the code says myImagePath does this refer to a image on the hard disk?

And how can I display an image stored in the bufferedimage?

myFrame.getContentPane().add(new JLabel(new ImageIcon(myImagePath)), constraints);

Thank you
0
 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
>> Are the constraints the size of the label?
No, it is an instance of GridBagConstraints

>> And how can I display an image stored in the bufferedimage?
myFrame.getContentPane().add(new JLabel(new ImageIcon(myBufferedImage)), constraints);
0
 

Author Comment

by:AntoniRyszard
Comment Utility

Thank you for your advice.

Could I is there any method to display the label as a clear median sized box within the swing frame. Before we use it to display any images?

Or would I need to stretch the label using the gridbag?

Thanks
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
Create a blank label, and then use it's setIcon() method to display the image.
0
 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
objects' suggestion should work just fine. Have you tried it?
0
 

Author Comment

by:AntoniRyszard
Comment Utility

I will try to use the label, but I would like to ask further. To display a median sized blank label when the swing frame first executes. Would I need to use the gridbag to define the size of the label?

Would I be correct in saying the label cannot be passed dimensions directly?

Thank you
0
 
LVL 92

Accepted Solution

by:
objects earned 85 total points
Comment Utility
try setting the preferred size for the label

label.setPrefferedSize(new Dimension(w, h));
0
 

Author Comment

by:AntoniRyszard
Comment Utility

Thank you for your comments on labels.

Could anyone possibly demonstrate how to write an open files dialog box, I understand Java has a tool to the dialog boxs similar to those in windows.

I would like to use this to list jpeg and png files, and as a way to load images into the bufferedimage. Is this possible?

May thanks
 
0
 

Author Comment

by:AntoniRyszard
Comment Utility

I would also much appreciate if anyone could demonstrate a (save-as) dialog box, which writes the bufferedimage values as a jpeg or png? And allows the user to select the new file name.

Thank you
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
0
 

Author Comment

by:AntoniRyszard
Comment Utility
Thank you all for replying.

I just wondered if I ask a final question.

I am trying to store an grayscale image in a 2 dimensional int array.

The code below works, the buffered image data is copied to the byte array (data). Then I copy the (data array) to a 2d array. I have used seperate loops for x and y when I tried.

But I once saw an example where someone managed to copy  integers from a 1d array to a 2d int array in just one for loop. They were able to calculate where the int should be stored in the 2d array.

I just wondered if anyone know to achieve this?

Thanks

image = ImageIO.read(new File(filename));
int width = image.getWidth(), height = image.getHeight();
pixels = new int[width][height];

DataBufferByte buffer = (DataBufferByte) image.getRaster().getDataBuffer();
byte[] data = buffer.getData();

for(int x = 0; x < width; x++){
   for(int y = 0; y < height; y++){
       pixels[x][y] = (int) getByte(x,y,width) & 0xff;
   }
}

public final byte getByte(int x, int y, int width) {
   return this.data[y * width + x];
}
0
 

Author Comment

by:AntoniRyszard
Comment Utility
The question above I posted here by mistake.

(Objects) I looked at the examples on the page you recommended. I managed the following code, could anyone demonstrate how to read in images and save them. And when we use the open dialogbox, only jpeg or png files can be selected. I could not workout this from the Java web-sites example.

Thanks

   public void actionPerformed(ActionEvent e){
      String actionCommand = e.getActionCommand();

      if(actionCommand.compareTo("Open")==0){
         openFile();
      }else if(actionCommand.compareTo("Save As")==0){
         saveFile();
      }else if(actionCommand.compareTo("Exit")==0){
          System.exit(0);
      }
   }

   private File showDialog(String dialogTitle, String approveButtonText,
                           String approveButtonTooltip, File file){

      files.setDialogTitle(dialogTitle);
      files.setApproveButtonText(approveButtonText);
      files.setApproveButtonToolTipText(approveButtonTooltip);
      files.setFileSelectionMode(files.FILES_ONLY);
      files.setSelectedFile(file);

      int result = files.showDialog(Frame.this, null);
      return(result == files.APPROVE_OPTION) ? files.getSelectedFile() : null;
   }

   void openFile(){
      File file = showDialog("Open File","Open","Open image",null);
   }

   void saveFile(){
      File file = showDialog("Save as","Save","Save image",null);
   }
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
question seems answered to me
0
 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
The original question has been answered, and so has subsequent questions which should have been posted separately. No refund, point split.
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 

Author Comment

by:AntoniRyszard
Comment Utility

Hello,

I felt my question about the use of dialog-box for opening, and saving jpg, png files was linked to setting the label with a image.

I added more points to the questions, when I ask related questions to the orginal. If anyone could offer any guidance with regards the dialog box. I would be willing to kept the question open and even increase points.

Any thoughts?

Thank you
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
code examples was already posted to open/save images files.
0
 

Author Comment

by:AntoniRyszard
Comment Utility

Hello,

If the files we opened or saved using the dialog box were images, jpgs or png. How could I add a filter so the open dialog only displays jpeg or png images.

And the save as only saves jpegs or png's? And how would I get the file read in the open method into a bufferedimage for displaying in the label?

Thanks
0
 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
Read the javadocs for JFileChooser. There's an example in the class description and a link to the appropriate page in the Java tutorial. http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JFileChooser.html
0
 

Author Comment

by:AntoniRyszard
Comment Utility
Thank you for replying.

This was the example (objects) recommend, I have been trying to workout how they achieve the filter. The problem I have is used many different classes, for example as below. And I could workout how to seperate the code include in my program.

  ExampleFileFilter filter = new ExampleFileFilter();


I have written this code: where the openFile, and saveFile methods call the showdialog method I also declared. Could I add some filter code to the showDialog method. And could anyone demonstrate what the filater would be for jpeg, png image files?

Thanks

   public void actionPerformed(ActionEvent e){
      String actionCommand = e.getActionCommand();

      if(actionCommand.compareTo("Open")==0){
         openFile();
      }else if(actionCommand.compareTo("Save As")==0){
         saveFile();
      }else if(actionCommand.compareTo("Exit")==0){
          System.exit(0);
      }
   }

   private File showDialog(String dialogTitle, String approveButtonText,
                           String approveButtonTooltip, File file){

      files.setDialogTitle(dialogTitle);
      files.setApproveButtonText(approveButtonText);
      files.setApproveButtonToolTipText(approveButtonTooltip);
      files.setFileSelectionMode(files.FILES_ONLY);
      files.setSelectedFile(file);

      int result = files.showDialog(Frame.this, null);
      return(result == files.APPROVE_OPTION) ? files.getSelectedFile() : null;
   }

   void openFile(){
      File file = showDialog("Open File","Open","Open image",null);
   }

   void saveFile(){
      File file = showDialog("Save as","Save","Save image",null);
   }
0
 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
Hmmm
files.setFileFilter(filter);
0
 

Author Comment

by:AntoniRyszard
Comment Utility

The filter variable would this be a string?

And would the value be ".jpg, .png"

Thanks
0
 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
>> And would the value be ".jpg, .png"
Yes indeed!
0
 

Author Comment

by:AntoniRyszard
Comment Utility

Will the filter add jpg, png to the dialog box, where it says (files of type).

Thanks
0
 

Author Comment

by:AntoniRyszard
Comment Utility
Hello,

The compiler don't seem to like: files.setFileFilter(".jpg, .png");

Any thoughts?

0
 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
It is now quite apparent that you have not read the very brief example on how to attach a FileFilter to the JFileChooser class.

If you look there and locate the line:
files.setFileFilter(filter);

You will quickly discover the 'filter' is a class which implements the FileFilter interface, not a String or several.

If you're unable to read the Javadocs and read the example code provided there and in a multitude of other locations, you are in for a VERY rough ride when it comes to learning how to program. Read and learn.
0
 

Author Comment

by:AntoniRyszard
Comment Utility

Hello,

I did read through the example, in my eailer reply I mentioned the line:

ExampleFileFilter filter = new ExampleFileFilter();

And mentioned I was hoping not to have a seperate class for the filter, but to include the code in the showdialog function.

Could I include something like:

files.setFileFilter(new JFileFilter());

and then use the addExtension to specify the file types, using the JFileFilter?

Thanks
0
 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
You would still have to define the class which implements the interface. Sorry, but there is no default implementation of the FileFilter interface. You could always just copy the ExampleFileFilter from the tutorial and define it as an inner class in the class which you need it. However, that makes no sense as you will probably need that functionality elsewhere in your project, or in other projects going forward.
0
 

Author Comment

by:AntoniRyszard
Comment Utility
Thank you for replying.

The filter example on java's tutorial pages, uses a second class Util. Though I found some code in a java text, shown below and changed my showDialog method as appropriate.

But I wondered if I should write the Util and Filter classes. Because I think my code will only allow us to filter one fil type, I have currently set this to jpeg's. I would like to filter for png's as well. In this line could I add two file types.

ExtensionFilter filter = new ExtensionFilter(".jpg", "Image files");

Thank you

   private File showDialog(String dialogTitle,
                           String approveButtonText,
                           String approveButtonTooltip,
                           File file){

      files.setDialogTitle(dialogTitle);
      files.setApproveButtonText(approveButtonText);
      files.setApproveButtonToolTipText(approveButtonTooltip);
      files.setFileSelectionMode(files.FILES_ONLY);

      ExtensionFilter filter = new ExtensionFilter(".jpg", "Image files");
      files.addChoosableFileFilter(filter);
      files.setFileFilter(filter);

      int result = files.showDialog(Frame.this, null);
      return(result == files.APPROVE_OPTION) ? files.getSelectedFile() : null;
   }


import javax.swing.filechooser.*;
import java.io.File;

public class ExtensionFilter extends FileFilter{

   private String description;
   private String extension;

   public ExtensionFilter(String ext, String descr){
      extension = ext.toLowerCase();
      description = descr;
   }

   public boolean accept(File file){
      return(file.isDirectory() || file.getName().toLowerCase().endsWith(extension));
   }

   public String getDescription(){
      return description;
   }

}
0
 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
Up the points, you'll get more help.
0
 

Author Comment

by:AntoniRyszard
Comment Utility
Sorry I have only 5 points more, at the moment.

0
 

Author Comment

by:AntoniRyszard
Comment Utility

Although I have added 35 points since the question first opened.

0
 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
Here's a hint:
Your filter currently supports filtering on ONE file extension. How do you need to change it in order to filter on a LIST of file extensions?


This is from the Member FAQ: http://www.experts-exchange.com/Programming/Programming_Languages/Java/help.jsp#hs8

> Asking a number of questions in one question

This is more of a huge annoyance than an actual violation of the Membership Guidelines, but it happens often enough to warrant inclusion here.

The idea at Experts Exchange is to ask a question, assign a point value to it, get an answer from several possible answers, select the best one, and award the points for it. Frequently, new users will ask several questions in one (because they don't have very many points), and then withhold awarding the points until one or more Experts have answered a few follow-up questions -- sometimes totally unrelated to the original question.

This will be met with disfavor by Experts, and will likely get you a warning from the Moderators. Let's keep it simple and to the point: You're better off asking one question at a time for few points than you are asking one question that has five questions plus a couple of follow-ups.
0
 

Author Comment

by:AntoniRyszard
Comment Utility

Sorry orangehead911, I could not workout how to split the points. And I actually used objects code and example web-site.

Sorry again
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
powerN  challenge 3 46
countAbc challenge 9 49
json format text only 4 64
word0 challenge 3 55
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues undeā€¦
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importingā€¦
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now