Disadvantage: You need to click a click to display the image. For example, you can display the image only when the maximum value is minimized.
Code:
- Import java. AWT .*;
- Import java. Io. file;
- Import java. AWT. event .*;
- Import javax. Swing. filechooser .*;
- Import javax. Swing .*;
- Public class test4 {
- Public static void main (string [] ARGs ){
- Filechooser fc = new filechooser ();
- }
- }
- Class filechooser extends jframe implements actionlistener {
- Container P;
- Static int I = 0;
- Jpanel imgpane;
- Jlabel labeimag;
- Jtoolbar TB = new jtoolbar ();
- Jbutton BTN = new jbutton ("O ");
- Public filechooser (){
- P = getcontentpane ();
- BTN. settooltiptext ("open to select image"); // The button prompts
- BTN. setforeground (color. Red );
- BTN. addactionlistener (this );
- Imgpane = new jpanel ();
- TB. Add (BTN );
- P. Add (TB, borderlayout. North );
- Setbounds (100,100,800,600 );
- Setdefaclocloseoperation (exit_on_close );
- Setvisible (true );
- }
- Public void actionreceivmed (actionevent e ){
- If (E. getsource () = BTN ){
- Jfilechooser choosefile = new jfilechooser ();
- Choosefile. addchoosablefilefilter (New filecanchoose ());
- Int returnval = choosefile. showopendialog (null );
- If (returnval = choosefile. approve_option ){
- If (I! = 0 ){
- Imgpane. Remove (labeimag); // remove the previous image
- }
- I ++;
- File F = choosefile. getselectedfile ();
- String fname = f. getabsolutepath ();
- Labeimag = new jlabel ();
- Labeimag. seticon (New imageicon (fname ));
- Labeimag. sethorizontalalignment (jlabel. center); // you can specify the center of the image.
- Imgpane. Add (labeimag, borderlayout. center );
- P. Add (imgpane, borderlayout. center );
- }
- }
- }
- }
- Class filecanchoose extends filefilter {// file filter, set to select the corresponding type of file
- Public Boolean accept (File file ){
- String name = file. getname ();
- Return (name. tolowercase (). endswith (". GIF") |
- Name. tolowercase (). endswith (". jpg") |
- Name. tolowercase (). endswith (". BMP") |
- Name. tolowercase (). endswith (". PNG") |
- Name. tolowercase (). endswith (". jpeg "));
- }
- Public String getdescription (){
- Return "image files:. GIF,. jpg,. BMP,. PNG,. jpeg ";
- }
- }