Solved

Displaying Images on JFrame in Java

Posted on 2004-10-07
9
465 Views
Last Modified: 2006-11-17
Here is my Client side code, I want to display image on the output frame where all the values from server are displayed.I have a .gif file.I want it to be displayed on the frame and my file is in the same folder where my code isaved.Can anyone give me this solution.

client code...

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Client extends JFrame

{
     private JTextField textZipcode, textsky, texttemp, texthumidity,
               textwindspeed, textbarometer, textdew, textheat, textvisibility;

     private JLabel labelZipcode, labelsky, labeltemp, labelhumidity,
               labelwindspeed, labelbarometer, labeldew, labelheat,
               labelvisibility;

     private JButton buttonWeather;
     DataInputStream in = null;
     private boolean getWeather = false;

     public Client() {
          Container container = getContentPane();
          container.setLayout(new FlowLayout());

          labelZipcode = new JLabel("ZipCode ");
          container.add(labelZipcode);
          textZipcode = new JTextField(15);
          container.add(textZipcode);

          buttonWeather = new JButton("     Get Weather Info     ");
          container.add(buttonWeather);

          labelsky = new JLabel("Sky ");
          container.add(labelsky);
          textsky = new JTextField(15);
          container.add(textsky);

          labeltemp = new JLabel("Temp ");
          container.add(labeltemp);
          texttemp = new JTextField(15);
          container.add(texttemp);

          labelhumidity = new JLabel("Humidity ");
          container.add(labelhumidity);
          texthumidity = new JTextField(15);
          container.add(texthumidity);

          labelwindspeed = new JLabel("Wind speed ");
          container.add(labelwindspeed);
          textwindspeed = new JTextField(15);
          container.add(textwindspeed);

          labelbarometer = new JLabel("Barometer ");
          container.add(labelbarometer);
          textbarometer = new JTextField(15);
          container.add(textbarometer);

          labeldew = new JLabel("Dew ");
          container.add(labeldew);
          textdew = new JTextField(15);
          container.add(textdew);

          labelheat = new JLabel("Heat ");
          container.add(labelheat);
          textheat = new JTextField(15);
          container.add(textheat);

          labelvisibility = new JLabel("Visibillity ");
          container.add(labelvisibility);
          textvisibility = new JTextField(15);
          container.add(textvisibility);

          setSize(200, 600);
          setVisible(true);

          // Event handler for handing the button events
          ButtonHandler handler = new ButtonHandler();
          buttonWeather.addActionListener(handler);

     }

     public void getWeather() throws IOException {
          while (true) {
               if(getWeather) {
               int t1 = in.readInt();
               int t2 = in.readInt();
               int t3 = in.readInt();
               int t4 = in.readInt();
               System.out.println("Received "+t1+" "+t2+" "+t3+" "+t4);
               if (t1 > 20 && t2 < 40){

                    System.out.println("in 1");
                    textsky.setText("Sky Condition: " + "Clear");
               }
               if (t3 > 40 && t4 < 80) {
                    textsky
                              .setText("Sky Condition: "
                                        + "Partly Cloudy");
                    System.out.println("in 2");
               }
               else{
                    textsky.setText("Sky Condition: " + "Cloudy");
                    System.out.println("in 3");
               }
               texttemp.cut();
               texttemp.setText("Temperature: " + in.readInt()+"\n");
               //texttemp.setText("Temperature:");
               System.out.println("In last");
               texthumidity.setText("Humidity: " + in.readInt());
               textwindspeed.setText("Wind Speed: " + in.readInt());
               textbarometer.setText("Barometer: " + in.readInt());
               textdew.setText("Dewpoint: " + in.readInt());
               textheat.setText("Heat Index: " + in.readInt());
               textvisibility.setText("Visibility: " + in.readInt());
               try {
                    Thread.sleep(5000);
               } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
               }
               }
          }
     }

     // Button Click Event Handler
     class ButtonHandler implements ActionListener {
          public void actionPerformed(ActionEvent event) {
               // After pressing show Status, varios checks and the final message
               // is built
               if (event.getSource() == buttonWeather) {
                    try {
                         //ceating the socket to connect to server running on same
                         // machine binded on port no 3000
                         Socket client = new Socket("localhost", 3000);
                         System.out.println("Client connected ");

                         //getting the o/p stream of that connection
                         PrintStream out = new PrintStream(client.getOutputStream());
                         //sending the message to server
                         out.print("Hello from client\n");
                         out.flush();
                         //reading the response using input stream
                         in = new DataInputStream(client
                                   .getInputStream());
                         //System.out.println("haha.."+in.readInt());



                         //closing the streams
                         //in.close();
                         //out.close();
                         getWeather = true;

                    } catch (Exception err) {
                         System.err.println("* err" + err);
                    }
               }

          }

     }

     public static void main(String a[]) {
          Client abc = new Client();
          try {
               abc.getWeather();
          } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          }

     }

}
...server....
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Server extends JFrame
{


     private JTextField textConnection;
     private JLabel labelConnection;
     Container container = null;


     public Server()

     {

           container = getContentPane() ;
           container.setLayout(new FlowLayout());

           labelConnection = new JLabel("Connection ") ;
           container.add(labelConnection );
           textConnection = new JTextField(15) ;
           container.add(textConnection);
           textConnection.setText("Disconnected");

          setSize ( 200,400) ;
          setVisible(true);

          try
          {
               //creating server socket binding at port # 3000
               ServerSocket server=new ServerSocket(3000);
               System.out.println("Server binded at "+((server.getInetAddress()).getLocalHost()).getHostAddress()+":3000");
               System.out.println("Run the Client");
               //ready to accept client request
               Socket socket=server.accept();
               textConnection.cut();
               textConnection.setText("Connected\n");


               //opening the input stream to read data from client connection
               BufferedReader in= new BufferedReader(new InputStreamReader(socket.getInputStream()));
               System.out.println(in.readLine());
               //using output stream responsing data
               DataOutputStream out=new DataOutputStream(socket.getOutputStream());
               while (true)
               {
                  for (int i=0; i<8; i++)
                  {
                      int s =(int)(Math.random()*10);
                      out.writeInt((s*10)+20);
                  }
                  out.flush();
               }
               //closing the in & out streams
                  //out.close
            //   in.close();
          }
          catch(Exception err)
          {
               System.err.println("* err"+err);
               textConnection.cut();
               textConnection.setText("Disconnected\n");
          }

     }

     public static void main(String a[])
     {
          new Server();
     }

}
0
Comment
Question by:prashanth_gurijala
[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
9 Comments
 
LVL 92

Accepted Solution

by:
objects earned 250 total points
ID: 12246212
JLabel image = new JLabel(new ImageIcon(getClass().getResource("my.gif")));

then add the label to your frame where required.
0
 
LVL 3

Expert Comment

by:eekj
ID: 12246850
Do you mean the Frame Icon?

this.setIconImage(new ImageIcon(getClass().getResource("your.gif"))



0
 
LVL 3

Expert Comment

by:RuadRauFlessa
ID: 12246984
No create a label and pass an instance of Image to it's constructor. So you create an Image (which is an abstract class) by means of the ImageIcon class (which extends from the Image class) and pass it to the constructor of the JLabel class. And voila you have a JLabel that contains an image. Now all you need to do is add the JLabel to a sort of container.

The this.setIconImage changes the icon displayed at the left top of the frame. IOW the application icon and you do not want that.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 5

Expert Comment

by:Naeemg
ID: 12256295

JLabel thisImage = new JLabel(new ImageIcon("my.gif"));

0
 
LVL 4

Expert Comment

by:delphi3
ID: 12256330
Hi prashanth_gurijala,

I asked a similar Q a while back and the solution details may help here with this Q:

http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_20850619.html

Delphi3
0
 
LVL 2

Expert Comment

by:shah1d1698
ID: 12258895
Try this ....

// Fetch icon
Icon icon = new ImageIcon("icon.gif");
   
 // Create a label with text and an icon; the icon appears to the left    of the text..
JLabel label = new JLabel("Text Label", icon, JLabel.CENTER);
   
// Create a label with only an icon
label = new JLabel(icon);

// Add an icon to an existing label
label.setIcon(icon);

0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Convert from a json string array to a Java object 3 65
JAVA API design with micro service cloud in mind 1 82
Is there a simpler dropbox system? 10 44
DTD and JAVA versions 1 33
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

730 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