Solved

Java panel for images:

Posted on 2004-04-28
39
1,586 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 19
  • 12
  • 6
39 Comments
 
LVL 14

Expert Comment

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

Expert Comment

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

Author Comment

by:AntoniRyszard
ID: 10942771

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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 

Author Comment

by:AntoniRyszard
ID: 10942971

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
ID: 10943763
>> 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
ID: 10943971

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
ID: 10944126
Create a blank label, and then use it's setIcon() method to display the image.
0
 
LVL 14

Expert Comment

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

Author Comment

by:AntoniRyszard
ID: 10947539

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
ID: 10947772
try setting the preferred size for the label

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

Author Comment

by:AntoniRyszard
ID: 10964025

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
ID: 10964043

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
ID: 10964814
0
 

Author Comment

by:AntoniRyszard
ID: 10968780
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
ID: 10979900
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
ID: 10982249
0
 
LVL 92

Expert Comment

by:objects
ID: 10983229
question seems answered to me
0
 
LVL 14

Expert Comment

by:Tommy Braas
ID: 10983541
The original question has been answered, and so has subsequent questions which should have been posted separately. No refund, point split.
0
 

Author Comment

by:AntoniRyszard
ID: 10984813

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
ID: 10992086
code examples was already posted to open/save images files.
0
 

Author Comment

by:AntoniRyszard
ID: 10994539

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
ID: 10996053
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
ID: 10996889
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
ID: 10997030
Hmmm
files.setFileFilter(filter);
0
 

Author Comment

by:AntoniRyszard
ID: 10997096

The filter variable would this be a string?

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

Thanks
0
 
LVL 14

Expert Comment

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

Author Comment

by:AntoniRyszard
ID: 10997313

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

Thanks
0
 

Author Comment

by:AntoniRyszard
ID: 10997801
Hello,

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

Any thoughts?

0
 
LVL 14

Expert Comment

by:Tommy Braas
ID: 10997999
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
ID: 10998508

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
ID: 10999531
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
ID: 11006375
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
ID: 11006872
Up the points, you'll get more help.
0
 

Author Comment

by:AntoniRyszard
ID: 11007573
Sorry I have only 5 points more, at the moment.

0
 

Author Comment

by:AntoniRyszard
ID: 11007590

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

0
 
LVL 14

Expert Comment

by:Tommy Braas
ID: 11007678
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
ID: 11008439

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

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
runtime exception 2 67
web project error add remove 1 84
wild fly 8 startup error 2 81
dao vs facade design patterns 2 72
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Suggested Courses

739 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