Reloading and redisplay images on JScrollPane

I am using
Java platform:jdk 1.4.1
Windows platform: Windows 98se
Problem:I am making one application in which i need to display images when i get
it from socket.I had used one JScrollPane over JPanel with scrollbars.But when i get the image i stored it into an Image object.
such as in my main program
screen = Toolkit.getDefaultToolkit().getImage ( "screen.jpg" );
//Draw picture first time it works fine...
paintPicture(screen);
paintPicture(Image image)
     {picpnl = new JPanel();
     picpnl.setLayout(new BorderLayout());
        image = Toolkit.getDefaultToolkit(  ).getImage(image);
//Is picpnl is unable to display image second time       
      picpnl.add(new JScrollPane(new ImageComponent(image)),BorderLayout.CENTER);
        c.add( picpnl, BorderLayout.CENTER );
        picpnl.setVisible(true);
from my refresh code:
       if(image!=null)
          image.flush();
       Runtime rt = Runtime.getRuntime();
       rt.runFinalization();
       rt.gc();
       image = null;
//is this 2nd time image not properly stored in variable image
       image = Toolkit.getDefaultToolkit().createImage( b ,0, b.length );
       paintPicture(image);
//go to paintPicture second time doesn't work
class ImageComponent extends JComponent {
  Image image;
  Dimension size;
  public ImageComponent(Image image) {
    this.image = image;
    MediaTracker mt = new MediaTracker(this);
    mt.addImage(image, 0);
    try {
      mt.waitForAll(  );
catch (InterruptedException e) {
// error ...
size = new Dimension (image.getWidth(null),
image.getHeight(null));
setSize(size);}
public void paint(Graphics g) {
     g.drawImage(image, 0, 0, this);
public Dimension getPreferredSize( ) {
return size;
The above code works fine for (the first time).But when i try to display a different socket image (the second time) it doesn't work.
I didn't know what the problem is...
---whether the previous image didn't get erased from RAM or
---the OS is not aware of the current changed image in variable (image) or the
---JScrollPane is unable to redraw it second time.
How can i display one changed image from the socket onto the JScrollPane? (the second time).
Also i want to know if we are using one file with the name "screen.jpg" and at runtime if i changed that file with another file with the same name. How can i display that changed file?Is it possible in Java or not.(Is it the limitation of Java).
I totally get frustated by reading all forums but i didn't get the answer.Please reply me soon with the complete code?
The complete source code for the problem:
(SERVER):
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.text.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class Remote extends JFrame
private JPanel btnpnl,picpnl;
private JButton button[];
private UIManager.LookAndFeelInfo looks[];
private static int change = 1;
private JLabel label1;
private Icon icon[];
private String names[] = { "looks","connect","control", "refresh", "auto",    "commands" };
private String iconnames[] = { "gifs/look.gif","gifs/connect.gif","gifs/control.gif","gifs/refresh.gif","gifs/auto.gif","gifs/command.gif" };
private String looknames[] = { "Motif", "Windows", "Metal" };
private int port=5000;
private ScrollablePicture picture=null;
private ServerSocket server;
private Socket client;
private ObjectInputStream ins = null;
private ObjectOutputStream ous = null;
private File file;
private String fileName;
private boolean autocontrol=true;
private Image image=null;
private Container c;
     public remote()
          super( "Remote Desktop" );
c = getContentPane();
          c.setLayout( new BorderLayout() );
//String file = "screen.jpg";
looks = UIManager.getInstalledLookAndFeels();
          btnpnl = new JPanel();
          btnpnl.setLayout( new FlowLayout() );
          button = new JButton[names.length];
          icon = new ImageIcon[iconnames.length];
          Buttonhandler handler = new Buttonhandler();
          for( int i=0; i<names.length; ++i )
icon[i] = new ImageIcon( iconnames[i] );
               button[i] = new JButton( names, icon[i] );
               button[i].addActionListener(handler);
btnpnl.add(button[i]);
          c.add( btnpnl, BorderLayout.NORTH );
          //Adding Label1
          label1 = new JLabel("LABEL1");
          c.add( label1, BorderLayout.SOUTH );
picpnl = new JPanel();
     picpnl.setLayout(new BorderLayout());
          //image = Toolkit.getDefaultToolkit( ).getImage(file);
// paintPicture(image);
          c.add( picpnl, BorderLayout.CENTER );
          //setResizable(false);
          setSize( 808, 640 );
          show();
public void paintPicture(Image image)
picpnl.add(new JScrollPane(new ImageComponent(image)),BorderLayout.CENTER);
picpnl.setVisible(true);
public class Buttonhandler implements ActionListener
          public void actionPerformed( ActionEvent e )
try{
               if( e.getActionCommand() == "looks" )
try
               label1.setText( Integer.toString( change ) );
          UIManager.setLookAndFeel( looks[change++].getClassName() );
                    SwingUtilities.updateComponentTreeUI(remote.this);
               if(change==3)
                    change=0;
catch (Exception ex)
ex.printStackTrace();
               if( e.getActionCommand() == "connect" )
                    label1.setText( "connect" );
runServer();
               if( e.getActionCommand() == "refresh" )
                    label1.setText( "refresh" );
                    ous.writeObject("refresh");
                    ous.flush();
                    recieveFile();
               if( e.getActionCommand() == "auto" )
                    label1.setText( "auto" );
                    ous.writeObject("auto");
                    button[4].setText("stop");
                    ous.flush();
                    setButton(false,false,false,false,true,false);
               auto();
               if( e.getActionCommand() == "stop" )
                    ous.writeObject("stop");
                    ous.flush();
                    button[4].setText("auto");
                    setButton(true,true,true,true,true,true);
               autocontrol=false;
          catch(Exception ef)
               ef.getMessage();
     public void auto()
          while(autocontrol)
recieveFile();
     public void setButton( boolean b1, boolean b2, boolean b3, boolean b4, boolean b5, boolean b6)
          button[0].setEnabled(b1);
          button[1].setEnabled(b2);
          button[2].setEnabled(b3);
          button[3].setEnabled(b4);
          button[4].setEnabled(b5);
          button[5].setEnabled(b6);
     public void recieveFile()
     int flag = 0;
          try{
               while(flag<=2){
               Object recieved = ins.readObject();
               System.out.println("from client:" + recieved);
switch (flag) {
case 0:
if (recieved.equals("sot")) {
System.out.println("sot recieved");
                                   flag++;
break;
               case 1:
fileName = (String) recieved;
file = new File(fileName);
                              System.out.println("fileName received");
                              flag++;
break;
               case 2:
               if (file.exists())
                    file.delete();
               byte[] b = (byte[])recieved;
               FileOutputStream ff = new FileOutputStream(fileName);
ff.write(b);
flag = 3;
if(image!=null)
                         image.flush();
                                                            Runtime rt = Runtime.getRuntime();
               rt.runFinalization();
               rt.gc();
               image = null;
          Image = Toolkit.getDefaultToolkit().createImage( b ,0, b.length );          
                    paintPicture(image);
break;
          catch(Exception e)
               e.printStackTrace();
class ImageComponent extends JComponent {
Image image;
Dimension size;
public ImageComponent(Image image) {
this.image = image;
MediaTracker mt = new MediaTracker(this);
mt.addImage(image, 0);
try {
mt.waitForAll( );
catch (InterruptedException e) {
// error ...
size = new Dimension (image.getWidth(null),
image.getHeight(null));
setSize(size);}
public void paint(Graphics g) {
     g.drawImage(image, 0, 0, this);
public Dimension getPreferredSize( ) {
return size;
     public void runServer()
     try{
               server = new ServerSocket(port);
               client = server.accept();
JOptionPane.showMessageDialog(null,"Connected");
               System.out.println("connection received from" + client.getInetAddress().getHostName());
               ous = new ObjectOutputStream( client.getOutputStream() );
ous.flush();
               ins = new ObjectInputStream( client.getInputStream() );
               System.out.println("get i/o streams");
          catch(Exception e)
               e.printStackTrace();
     public static void main(String[] args)
     remote app = new remote();
     app.addWindowListener(
          new WindowAdapter(){
                    public void windowClosing( WindowEvent e )
                         System.exit( 0 );
CLIENT code:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.image.*;
import javax.imageio.*;
public class Client extends JFrame
private JLabel label1;
private JButton button1;
private Socket server;
private ObjectInputStream ins=null;
private ObjectOutputStream ous=null;
private File file;
private boolean autocontrol=true;     
public Client()
     super("Client");
     Container c = getContentPane();
     ButtonHandler handler = new ButtonHandler();
     c.setLayout( new FlowLayout() );
     label1 = new JLabel("");
     button1 = new JButton("connect");
     c.add(label1);
     c.add(button1);
     button1.addActionListener(handler);
     setSize(300,300);
     show();
class ButtonHandler implements ActionListener
     public void actionPerformed(ActionEvent e)
     if(e.getActionCommand()=="connect")
               runClient();
public void runClient()
     try{     
          server = new Socket(InetAddress.getByName("127.0.0.1"),5000);
System.out.println("connected to" + server.getInetAddress().getHostName());
          ous = new ObjectOutputStream(server.getOutputStream());
     ous.flush();
          ins = new ObjectInputStream(server.getInputStream());
          System.out.println("get i/o streams");
               file = new File("screen.jpg");
          listencommands();
     }catch(Exception e)
          e.getMessage();
public void listencommands()
     try
          while(true){
          Object message = ins.readObject();
     if(message.equals("refresh"))
               screenshot();
               sendFile(file);
     if(message.equals("auto"))
               autocontrol=true;
               while(autocontrol)
                    screenshot();
                    sendFile(file);
if(message.equals("stop"))
               autocontrol = false;
     catch(Exception e)
          e.printStackTrace();
public void sendFile( File file ) throws IOException
     try{     
          System.out.println("Ready to send file");
          ous.writeObject("sot");
ous.flush();
System.out.println("sot send");
          ous.writeObject("screen.jpg");
          ous.flush();
System.out.println("fileName send");
          FileInputStream f = new FileInputStream (file);
System.out.println("fileinputstream received");
          int size = f.available();
byte array[] = new byte[size];
f.read(array,0,size);
          System.out.println("Declared array");               
                    //ous.write(size);
                    //ous.flush();
          ous.writeObject(array);
ous.flush();
          System.out.println("image send");
          catch (Exception e)
               System.out.println(e.getMessage());
public void screenshot()
try
     //Get the screen size
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
     Rectangle rectangle = new Rectangle(0, 0, screenSize.width, screenSize.height);
Robot robot = new Robot();     
     BufferedImage image = robot.createScreenCapture(rectangle);
     File file;
//Save the screenshot as a jpg
     file = new File("screen.jpg");
     ImageIO.write(image, "jpg", file);
catch (Exception e)
     System.out.println(e.getMessage());
public static void main( String args[] )
          Client app = new Client();
app.addWindowListener(
          new WindowAdapter(){
                    public void windowClosing( WindowEvent e )
                         System.exit( 0 );
Steps to run code:
if everything goes fine:
1.Run the server.
2.Run the client.
3.Press connect button on server.
4.Press connect on client.
5.You get a Message box "Connected".
6.Press refresh button on Server.
7.You get the first image.
8.Press refresh button on Server.
9.You are not going to get anything but the same image.....this is where the problem begins to display that second changed image screenshot.

This is a Swing related question and you've already posted this question in the Swing forum.
Don't clutter the forum by posting the same question in 3 different forums.

Similar Messages

  • Reloading and Redisplaying images on JScrollPane

    I am using
    Java platform:jdk 1.4.1
    Windows platform: Windows 98se
    Problem:I am making one application in which i need to display images when i get
    it from socket.I had used one JScrollPane over JPanel with scrollbars.But when i get the image i stored it into an Image object.
    such as in my main program
    screen = Toolkit.getDefaultToolkit().getImage ( "screen.jpg" );
    //Draw picture first time it works fine...
    paintPicture(screen);
    paintPicture(Image image)
         {picpnl = new JPanel();
         picpnl.setLayout(new BorderLayout());
            image = Toolkit.getDefaultToolkit(  ).getImage(image);
    //Is picpnl is unable to display image second time       
          picpnl.add(new JScrollPane(new ImageComponent(image)),BorderLayout.CENTER);
            c.add( picpnl, BorderLayout.CENTER );
            picpnl.setVisible(true);
    from my refresh code:
           if(image!=null)
              image.flush();
           Runtime rt = Runtime.getRuntime();
           rt.runFinalization();
           rt.gc();
           image = null;
    //is this 2nd time image not properly stored in variable image
           image = Toolkit.getDefaultToolkit().createImage( b ,0, b.length );
           paintPicture(image);
    //go to paintPicture second time doesn't work
    class ImageComponent extends JComponent {
      Image image;
      Dimension size;
      public ImageComponent(Image image) {
        this.image = image;
        MediaTracker mt = new MediaTracker(this);
        mt.addImage(image, 0);
        try {
          mt.waitForAll(  );
    catch (InterruptedException e) {
    // error ...
    size = new Dimension (image.getWidth(null),
    image.getHeight(null));
    setSize(size);}
    public void paint(Graphics g) {
         g.drawImage(image, 0, 0, this);
    public Dimension getPreferredSize( ) {
    return size;
    The above code works fine for (the first time).But when i try to display a different socket image (the second time) it doesn't work.
    I didn't know what the problem is...
    ---whether the previous image didn't get erased from RAM or
    ---the OS is not aware of the current changed image in variable (image) or the
    ---JScrollPane is unable to redraw it second time.
    How can i display one changed image from the socket onto the JScrollPane? (the second time).
    Also i want to know if we are using one file with the name "screen.jpg" and at runtime if i changed that file with another file with the same name. How can i display that changed file?Is it possible in Java or not.(Is it the limitation of Java).
    I totally get frustated by reading all forums but i didn't get the answer.Please reply me soon with the complete code?
    The complete source code for the problem:
    (SERVER):
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.text.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Remote extends JFrame
    private JPanel btnpnl,picpnl;
    private JButton button[];
    private UIManager.LookAndFeelInfo looks[];
    private static int change = 1;
    private JLabel label1;
    private Icon icon[];
    private String names[] = { "looks","connect","control", "refresh", "auto",    "commands" };
    private String iconnames[] = { "gifs/look.gif","gifs/connect.gif","gifs/control.gif","gifs/refresh.gif","gifs/auto.gif","gifs/command.gif" };
    private String looknames[] = { "Motif", "Windows", "Metal" };
    private int port=5000;
    private ScrollablePicture picture=null;
    private ServerSocket server;
    private Socket client;
    private ObjectInputStream ins = null;
    private ObjectOutputStream ous = null;
    private File file;
    private String fileName;
    private boolean autocontrol=true;
    private Image image=null;
    private Container c;
         public remote()
              super( "Remote Desktop" );
    c = getContentPane();
              c.setLayout( new BorderLayout() );
    //String file = "screen.jpg";
    looks = UIManager.getInstalledLookAndFeels();
              btnpnl = new JPanel();
              btnpnl.setLayout( new FlowLayout() );
              button = new JButton[names.length];
              icon = new ImageIcon[iconnames.length];
              Buttonhandler handler = new Buttonhandler();
              for( int i=0; i<names.length; ++i )
    icon[i] = new ImageIcon( iconnames[i] );
                   button[i] = new JButton( names, icon[i] );
                   button[i].addActionListener(handler);
    btnpnl.add(button[i]);
              c.add( btnpnl, BorderLayout.NORTH );
              //Adding Label1
              label1 = new JLabel("LABEL1");
              c.add( label1, BorderLayout.SOUTH );
    picpnl = new JPanel();
         picpnl.setLayout(new BorderLayout());
              //image = Toolkit.getDefaultToolkit( ).getImage(file);
    // paintPicture(image);
              c.add( picpnl, BorderLayout.CENTER );
              //setResizable(false);
              setSize( 808, 640 );
              show();
    public void paintPicture(Image image)
    picpnl.add(new JScrollPane(new ImageComponent(image)),BorderLayout.CENTER);
    picpnl.setVisible(true);
    public class Buttonhandler implements ActionListener
              public void actionPerformed( ActionEvent e )
    try{
                   if( e.getActionCommand() == "looks" )
    try
                   label1.setText( Integer.toString( change ) );
              UIManager.setLookAndFeel( looks[change++].getClassName() );
                        SwingUtilities.updateComponentTreeUI(remote.this);
                   if(change==3)
                        change=0;
    catch (Exception ex)
    ex.printStackTrace();
                   if( e.getActionCommand() == "connect" )
                        label1.setText( "connect" );
    runServer();
                   if( e.getActionCommand() == "refresh" )
                        label1.setText( "refresh" );
                        ous.writeObject("refresh");
                        ous.flush();
                        recieveFile();
                   if( e.getActionCommand() == "auto" )
                        label1.setText( "auto" );
                        ous.writeObject("auto");
                        button[4].setText("stop");
                        ous.flush();
                        setButton(false,false,false,false,true,false);
                   auto();
                   if( e.getActionCommand() == "stop" )
                        ous.writeObject("stop");
                        ous.flush();
                        button[4].setText("auto");
                        setButton(true,true,true,true,true,true);
                   autocontrol=false;
              catch(Exception ef)
                   ef.getMessage();
         public void auto()
              while(autocontrol)
    recieveFile();
         public void setButton( boolean b1, boolean b2, boolean b3, boolean b4, boolean b5, boolean b6)
              button[0].setEnabled(b1);
              button[1].setEnabled(b2);
              button[2].setEnabled(b3);
              button[3].setEnabled(b4);
              button[4].setEnabled(b5);
              button[5].setEnabled(b6);
         public void recieveFile()
         int flag = 0;
              try{
                   while(flag<=2){
                   Object recieved = ins.readObject();
                   System.out.println("from client:" + recieved);
    switch (flag) {
    case 0:
    if (recieved.equals("sot")) {
    System.out.println("sot recieved");
                                       flag++;
    break;
                   case 1:
    fileName = (String) recieved;
    file = new File(fileName);
                                  System.out.println("fileName received");
                                  flag++;
    break;
                   case 2:
                   if (file.exists())
                        file.delete();
                   byte[] b = (byte[])recieved;
                   FileOutputStream ff = new FileOutputStream(fileName);
    ff.write(b);
    flag = 3;
    if(image!=null)
                             image.flush();
                                                                Runtime rt = Runtime.getRuntime();
                   rt.runFinalization();
                   rt.gc();
                   image = null;
              Image = Toolkit.getDefaultToolkit().createImage( b ,0, b.length );          
                        paintPicture(image);
    break;
              catch(Exception e)
                   e.printStackTrace();
    class ImageComponent extends JComponent {
    Image image;
    Dimension size;
    public ImageComponent(Image image) {
    this.image = image;
    MediaTracker mt = new MediaTracker(this);
    mt.addImage(image, 0);
    try {
    mt.waitForAll( );
    catch (InterruptedException e) {
    // error ...
    size = new Dimension (image.getWidth(null),
    image.getHeight(null));
    setSize(size);}
    public void paint(Graphics g) {
         g.drawImage(image, 0, 0, this);
    public Dimension getPreferredSize( ) {
    return size;
         public void runServer()
         try{
                   server = new ServerSocket(port);
                   client = server.accept();
    JOptionPane.showMessageDialog(null,"Connected");
                   System.out.println("connection received from" + client.getInetAddress().getHostName());
                   ous = new ObjectOutputStream( client.getOutputStream() );
    ous.flush();
                   ins = new ObjectInputStream( client.getInputStream() );
                   System.out.println("get i/o streams");
              catch(Exception e)
                   e.printStackTrace();
         public static void main(String[] args)
         remote app = new remote();
         app.addWindowListener(
              new WindowAdapter(){
                        public void windowClosing( WindowEvent e )
                             System.exit( 0 );
    CLIENT code:
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class Client extends JFrame
    private JLabel label1;
    private JButton button1;
    private Socket server;
    private ObjectInputStream ins=null;
    private ObjectOutputStream ous=null;
    private File file;
    private boolean autocontrol=true;     
    public Client()
         super("Client");
         Container c = getContentPane();
         ButtonHandler handler = new ButtonHandler();
         c.setLayout( new FlowLayout() );
         label1 = new JLabel("");
         button1 = new JButton("connect");
         c.add(label1);
         c.add(button1);
         button1.addActionListener(handler);
         setSize(300,300);
         show();
    class ButtonHandler implements ActionListener
         public void actionPerformed(ActionEvent e)
         if(e.getActionCommand()=="connect")
                   runClient();
    public void runClient()
         try{     
              server = new Socket(InetAddress.getByName("127.0.0.1"),5000);
    System.out.println("connected to" + server.getInetAddress().getHostName());
              ous = new ObjectOutputStream(server.getOutputStream());
         ous.flush();
              ins = new ObjectInputStream(server.getInputStream());
              System.out.println("get i/o streams");
                   file = new File("screen.jpg");
              listencommands();
         }catch(Exception e)
              e.getMessage();
    public void listencommands()
         try
              while(true){
              Object message = ins.readObject();
         if(message.equals("refresh"))
                   screenshot();
                   sendFile(file);
         if(message.equals("auto"))
                   autocontrol=true;
                   while(autocontrol)
                        screenshot();
                        sendFile(file);
    if(message.equals("stop"))
                   autocontrol = false;
         catch(Exception e)
              e.printStackTrace();
    public void sendFile( File file ) throws IOException
         try{     
              System.out.println("Ready to send file");
              ous.writeObject("sot");
    ous.flush();
    System.out.println("sot send");
              ous.writeObject("screen.jpg");
              ous.flush();
    System.out.println("fileName send");
              FileInputStream f = new FileInputStream (file);
    System.out.println("fileinputstream received");
              int size = f.available();
    byte array[] = new byte[size];
    f.read(array,0,size);
              System.out.println("Declared array");               
                        //ous.write(size);
                        //ous.flush();
              ous.writeObject(array);
    ous.flush();
              System.out.println("image send");
              catch (Exception e)
                   System.out.println(e.getMessage());
    public void screenshot()
    try
         //Get the screen size
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
         Rectangle rectangle = new Rectangle(0, 0, screenSize.width, screenSize.height);
    Robot robot = new Robot();     
         BufferedImage image = robot.createScreenCapture(rectangle);
         File file;
    //Save the screenshot as a jpg
         file = new File("screen.jpg");
         ImageIO.write(image, "jpg", file);
    catch (Exception e)
         System.out.println(e.getMessage());
    public static void main( String args[] )
              Client app = new Client();
    app.addWindowListener(
              new WindowAdapter(){
                        public void windowClosing( WindowEvent e )
                             System.exit( 0 );
    Steps to run code:
    if everything goes fine:
    1.Run the server.
    2.Run the client.
    3.Press connect button on server.
    4.Press connect on client.
    5.You get a Message box "Connected".
    6.Press refresh button on Server.
    7.You get the first image.
    8.Press refresh button on Server.
    9.You are not going to get anything but the same image.....this is where the problem begins to display that second changed image screenshot.

    Use the "code" formatting tags when posting code so the code retains its formatting.
    Also, instead of posting a complicated client/server application, why don't you start with something simple. Like create a GUI with two buttons, "Load Image 1", "Load Image 2". Once you learn how to solve this simple program you shouldn't have a problem with a little more complicated scenario.
    I would try just adding a JLabel to the scroll pane. Then when you want to change the image just use the setIcon(...) method of JLabel.

  • Reloading and redisplay images using JScrollPane

    I am using
    Java platform:jdk 1.4.1
    Windows platform: Windows 98se
    Problem:I am making one application in which i need to display images when i get
    it from socket.I had used one JScrollPane over JPanel with scrollbars.But when i get the image i stored it into an Image object.
    such as in my main program
    screen = Toolkit.getDefaultToolkit().getImage ( "screen.jpg" );
    //Draw picture first time it works fine...
    paintPicture(screen);
    paintPicture(Image image)
         {picpnl = new JPanel();
         picpnl.setLayout(new BorderLayout());
            image = Toolkit.getDefaultToolkit(  ).getImage(image);
    //Is picpnl is unable to display image second time       
          picpnl.add(new JScrollPane(new ImageComponent(image)),BorderLayout.CENTER);
            c.add( picpnl, BorderLayout.CENTER );
            picpnl.setVisible(true);
    from my refresh code:
           if(image!=null)
              image.flush();
           Runtime rt = Runtime.getRuntime();
           rt.runFinalization();
           rt.gc();
           image = null;
    //is this 2nd time image not properly stored in variable image
           image = Toolkit.getDefaultToolkit().createImage( b ,0, b.length );
           paintPicture(image);
    //go to paintPicture second time doesn't work
    class ImageComponent extends JComponent {
      Image image;
      Dimension size;
      public ImageComponent(Image image) {
        this.image = image;
        MediaTracker mt = new MediaTracker(this);
        mt.addImage(image, 0);
        try {
          mt.waitForAll(  );
    catch (InterruptedException e) {
    // error ...
    size = new Dimension (image.getWidth(null),
    image.getHeight(null));
    setSize(size);}
    public void paint(Graphics g) {
         g.drawImage(image, 0, 0, this);
    public Dimension getPreferredSize( ) {
    return size;
    The above code works fine for (the first time).But when i try to display a different socket image (the second time) it doesn't work.
    I didn't know what the problem is...
    ---whether the previous image didn't get erased from RAM or
    ---the OS is not aware of the current changed image in variable (image) or the
    ---JScrollPane is unable to redraw it second time.
    How can i display one changed image from the socket onto the JScrollPane? (the second time).
    Also i want to know if we are using one file with the name "screen.jpg" and at runtime if i changed that file with another file with the same name. How can i display that changed file?Is it possible in Java or not.(Is it the limitation of Java).
    I totally get frustated by reading all forums but i didn't get the answer.Please reply me soon with the complete code?
    The complete source code for the problem:
    (SERVER):
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.text.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Remote extends JFrame
    private JPanel btnpnl,picpnl;
    private JButton button[];
    private UIManager.LookAndFeelInfo looks[];
    private static int change = 1;
    private JLabel label1;
    private Icon icon[];
    private String names[] = { "looks","connect","control", "refresh", "auto",    "commands" };
    private String iconnames[] = { "gifs/look.gif","gifs/connect.gif","gifs/control.gif","gifs/refresh.gif","gifs/auto.gif","gifs/command.gif" };
    private String looknames[] = { "Motif", "Windows", "Metal" };
    private int port=5000;
    private ScrollablePicture picture=null;
    private ServerSocket server;
    private Socket client;
    private ObjectInputStream ins = null;
    private ObjectOutputStream ous = null;
    private File file;
    private String fileName;
    private boolean autocontrol=true;
    private Image image=null;
    private Container c;
         public remote()
              super( "Remote Desktop" );
    c = getContentPane();
              c.setLayout( new BorderLayout() );
    //String file = "screen.jpg";
    looks = UIManager.getInstalledLookAndFeels();
              btnpnl = new JPanel();
              btnpnl.setLayout( new FlowLayout() );
              button = new JButton[names.length];
              icon = new ImageIcon[iconnames.length];
              Buttonhandler handler = new Buttonhandler();
              for( int i=0; i<names.length; ++i )
    icon[i] = new ImageIcon( iconnames[i] );
                   button[i] = new JButton( names, icon[i] );
                   button[i].addActionListener(handler);
    btnpnl.add(button[i]);
              c.add( btnpnl, BorderLayout.NORTH );
              //Adding Label1
              label1 = new JLabel("LABEL1");
              c.add( label1, BorderLayout.SOUTH );
    picpnl = new JPanel();
         picpnl.setLayout(new BorderLayout());
              //image = Toolkit.getDefaultToolkit( ).getImage(file);
    // paintPicture(image);
              c.add( picpnl, BorderLayout.CENTER );
              //setResizable(false);
              setSize( 808, 640 );
              show();
    public void paintPicture(Image image)
    picpnl.add(new JScrollPane(new ImageComponent(image)),BorderLayout.CENTER);
    picpnl.setVisible(true);
    public class Buttonhandler implements ActionListener
              public void actionPerformed( ActionEvent e )
    try{
                   if( e.getActionCommand() == "looks" )
    try
                   label1.setText( Integer.toString( change ) );
              UIManager.setLookAndFeel( looks[change++].getClassName() );
                        SwingUtilities.updateComponentTreeUI(remote.this);
                   if(change==3)
                        change=0;
    catch (Exception ex)
    ex.printStackTrace();
                   if( e.getActionCommand() == "connect" )
                        label1.setText( "connect" );
    runServer();
                   if( e.getActionCommand() == "refresh" )
                        label1.setText( "refresh" );
                        ous.writeObject("refresh");
                        ous.flush();
                        recieveFile();
                   if( e.getActionCommand() == "auto" )
                        label1.setText( "auto" );
                        ous.writeObject("auto");
                        button[4].setText("stop");
                        ous.flush();
                        setButton(false,false,false,false,true,false);
                   auto();
                   if( e.getActionCommand() == "stop" )
                        ous.writeObject("stop");
                        ous.flush();
                        button[4].setText("auto");
                        setButton(true,true,true,true,true,true);
                   autocontrol=false;
              catch(Exception ef)
                   ef.getMessage();
         public void auto()
              while(autocontrol)
    recieveFile();
         public void setButton( boolean b1, boolean b2, boolean b3, boolean b4, boolean b5, boolean b6)
              button[0].setEnabled(b1);
              button[1].setEnabled(b2);
              button[2].setEnabled(b3);
              button[3].setEnabled(b4);
              button[4].setEnabled(b5);
              button[5].setEnabled(b6);
         public void recieveFile()
         int flag = 0;
              try{
                   while(flag<=2){
                   Object recieved = ins.readObject();
                   System.out.println("from client:" + recieved);
    switch (flag) {
    case 0:
    if (recieved.equals("sot")) {
    System.out.println("sot recieved");
                                       flag++;
    break;
                   case 1:
    fileName = (String) recieved;
    file = new File(fileName);
                                  System.out.println("fileName received");
                                  flag++;
    break;
                   case 2:
                   if (file.exists())
                        file.delete();
                   byte[] b = (byte[])recieved;
                   FileOutputStream ff = new FileOutputStream(fileName);
    ff.write(b);
    flag = 3;
    if(image!=null)
                             image.flush();
                                                                Runtime rt = Runtime.getRuntime();
                   rt.runFinalization();
                   rt.gc();
                   image = null;
              Image = Toolkit.getDefaultToolkit().createImage( b ,0, b.length );          
                        paintPicture(image);
    break;
              catch(Exception e)
                   e.printStackTrace();
    class ImageComponent extends JComponent {
    Image image;
    Dimension size;
    public ImageComponent(Image image) {
    this.image = image;
    MediaTracker mt = new MediaTracker(this);
    mt.addImage(image, 0);
    try {
    mt.waitForAll( );
    catch (InterruptedException e) {
    // error ...
    size = new Dimension (image.getWidth(null),
    image.getHeight(null));
    setSize(size);}
    public void paint(Graphics g) {
         g.drawImage(image, 0, 0, this);
    public Dimension getPreferredSize( ) {
    return size;
         public void runServer()
         try{
                   server = new ServerSocket(port);
                   client = server.accept();
    JOptionPane.showMessageDialog(null,"Connected");
                   System.out.println("connection received from" + client.getInetAddress().getHostName());
                   ous = new ObjectOutputStream( client.getOutputStream() );
    ous.flush();
                   ins = new ObjectInputStream( client.getInputStream() );
                   System.out.println("get i/o streams");
              catch(Exception e)
                   e.printStackTrace();
         public static void main(String[] args)
         remote app = new remote();
         app.addWindowListener(
              new WindowAdapter(){
                        public void windowClosing( WindowEvent e )
                             System.exit( 0 );
    CLIENT code:
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class Client extends JFrame
    private JLabel label1;
    private JButton button1;
    private Socket server;
    private ObjectInputStream ins=null;
    private ObjectOutputStream ous=null;
    private File file;
    private boolean autocontrol=true;     
    public Client()
         super("Client");
         Container c = getContentPane();
         ButtonHandler handler = new ButtonHandler();
         c.setLayout( new FlowLayout() );
         label1 = new JLabel("");
         button1 = new JButton("connect");
         c.add(label1);
         c.add(button1);
         button1.addActionListener(handler);
         setSize(300,300);
         show();
    class ButtonHandler implements ActionListener
         public void actionPerformed(ActionEvent e)
         if(e.getActionCommand()=="connect")
                   runClient();
    public void runClient()
         try{     
              server = new Socket(InetAddress.getByName("127.0.0.1"),5000);
    System.out.println("connected to" + server.getInetAddress().getHostName());
              ous = new ObjectOutputStream(server.getOutputStream());
         ous.flush();
              ins = new ObjectInputStream(server.getInputStream());
              System.out.println("get i/o streams");
                   file = new File("screen.jpg");
              listencommands();
         }catch(Exception e)
              e.getMessage();
    public void listencommands()
         try
              while(true){
              Object message = ins.readObject();
         if(message.equals("refresh"))
                   screenshot();
                   sendFile(file);
         if(message.equals("auto"))
                   autocontrol=true;
                   while(autocontrol)
                        screenshot();
                        sendFile(file);
    if(message.equals("stop"))
                   autocontrol = false;
         catch(Exception e)
              e.printStackTrace();
    public void sendFile( File file ) throws IOException
         try{     
              System.out.println("Ready to send file");
              ous.writeObject("sot");
    ous.flush();
    System.out.println("sot send");
              ous.writeObject("screen.jpg");
              ous.flush();
    System.out.println("fileName send");
              FileInputStream f = new FileInputStream (file);
    System.out.println("fileinputstream received");
              int size = f.available();
    byte array[] = new byte[size];
    f.read(array,0,size);
              System.out.println("Declared array");               
                        //ous.write(size);
                        //ous.flush();
              ous.writeObject(array);
    ous.flush();
              System.out.println("image send");
              catch (Exception e)
                   System.out.println(e.getMessage());
    public void screenshot()
    try
         //Get the screen size
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
         Rectangle rectangle = new Rectangle(0, 0, screenSize.width, screenSize.height);
    Robot robot = new Robot();     
         BufferedImage image = robot.createScreenCapture(rectangle);
         File file;
    //Save the screenshot as a jpg
         file = new File("screen.jpg");
         ImageIO.write(image, "jpg", file);
    catch (Exception e)
         System.out.println(e.getMessage());
    public static void main( String args[] )
              Client app = new Client();
    app.addWindowListener(
              new WindowAdapter(){
                        public void windowClosing( WindowEvent e )
                             System.exit( 0 );
    Steps to run code:
    if everything goes fine:
    1.Run the server.
    2.Run the client.
    3.Press connect button on server.
    4.Press connect on client.
    5.You get a Message box "Connected".
    6.Press refresh button on Server.
    7.You get the first image.
    8.Press refresh button on Server.
    9.You are not going to get anything but the same image.....this is where the problem begins to display that second changed image screenshot.

    /* (SERVER): */
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.text.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Remote extends JFrame
    private JPanel btnpnl,picpnl;
    private JButton button[];
    private UIManager.LookAndFeelInfo looks[];
    private static int change = 1;
    private JLabel label1;
    private Icon icon[];
    private String names[] = { "looks","connect","control", "refresh", "auto", "commands" };
    private String iconnames[] = { "gifs/look.gif","gifs/connect.gif","gifs/control.gif","gifs/refresh.gif","gifs/auto.gif","gifs/command.gif" };
    private String looknames[] = { "Motif", "Windows", "Metal" };
    private int port=5000;
    private ScrollablePicture picture=null;
    private ServerSocket server;
    private Socket client;
    private ObjectInputStream ins = null;
    private ObjectOutputStream ous = null;
    private File file;
    private String fileName;
    private boolean autocontrol=true;
    private Image image=null;
    private Container c;
    public remote()
    super( "Remote Desktop" );
    c = getContentPane();
    c.setLayout( new BorderLayout() );
    //String file = "screen.jpg";
    looks = UIManager.getInstalledLookAndFeels();
    btnpnl = new JPanel();
    btnpnl.setLayout( new FlowLayout() );
    button = new JButton[names.length];
    icon = new ImageIcon[iconnames.length];
    Buttonhandler handler = new Buttonhandler();
    for( int i=0; i<names.length; ++i )
    icon = new ImageIcon( iconnames );
    button = new JButton( names, icon );
    button.addActionListener(handler);
    btnpnl.add(button);
    c.add( btnpnl, BorderLayout.NORTH );
    //Adding Label1
    label1 = new JLabel("LABEL1");
    c.add( label1, BorderLayout.SOUTH );
    picpnl = new JPanel();
    picpnl.setLayout(new BorderLayout());
    //image = Toolkit.getDefaultToolkit( ).getImage(file);
    // paintPicture(image);
    c.add( picpnl, BorderLayout.CENTER );
    //setResizable(false);
    setSize( 808, 640 );
    show();
    public void paintPicture(Image image)
    picpnl.add(new JScrollPane(new ImageComponent(image)),BorderLayout.CENTER);
    picpnl.setVisible(true);
    public class Buttonhandler implements ActionListener
    public void actionPerformed( ActionEvent e )
    try{
    if( e.getActionCommand() == "looks" )
    try
    label1.setText( Integer.toString( change ) );
    UIManager.setLookAndFeel( looks[change++].getClassName() );
    SwingUtilities.updateComponentTreeUI(remote.this);
    if(change==3)
    change=0;
    catch (Exception ex)
    ex.printStackTrace();
    if( e.getActionCommand() == "connect" )
    label1.setText( "connect" );
    runServer();
    if( e.getActionCommand() == "refresh" )
    label1.setText( "refresh" );
    ous.writeObject("refresh");
    ous.flush();
    recieveFile();
    if( e.getActionCommand() == "auto" )
    label1.setText( "auto" );
    ous.writeObject("auto");
    button[4].setText("stop");
    ous.flush();
    setButton(false,false,false,false,true,false);
    auto();
    if( e.getActionCommand() == "stop" )
    ous.writeObject("stop");
    ous.flush();
    button[4].setText("auto");
    setButton(true,true,true,true,true,true);
    autocontrol=false;
    catch(Exception ef)
    ef.getMessage();
    public void auto()
    while(autocontrol)
    recieveFile();
    public void setButton( boolean b1, boolean b2, boolean b3, boolean b4, boolean b5, boolean b6)
    button[0].setEnabled(b1);
    button[1].setEnabled(b2);
    button[2].setEnabled(b3);
    button[3].setEnabled(b4);
    button[4].setEnabled(b5);
    button[5].setEnabled(b6);
    public void recieveFile()
    int flag = 0;
    try{
    while(flag><=2){
    Object recieved = ins.readObject();
    System.out.println("from client:" + recieved);
    switch (flag) {
    case 0:
    if (recieved.equals("sot")) {
    System.out.println("sot recieved");
    flag++;
    break;
    case 1:
    fileName = (String) recieved;
    file = new File(fileName);
    System.out.println("fileName received");
    flag++;
    break;
    case 2:
    if (file.exists())
    file.delete();
    byte[] b = (byte[])recieved;
    FileOutputStream ff = new FileOutputStream(fileName);
    ff.write(b);
    flag = 3;
    if(image!=null)
    image.flush();
    Runtime rt = Runtime.getRuntime();
    rt.runFinalization();
    rt.gc();
    image = null;
    Image = Toolkit.getDefaultToolkit().createImage( b ,0, b.length );
    paintPicture(image);
    break;
    catch(Exception e)
    e.printStackTrace();
    class ImageComponent extends JComponent {
    Image image;
    Dimension size;
    public ImageComponent(Image image) {
    this.image = image;
    MediaTracker mt = new MediaTracker(this);
    mt.addImage(image, 0);
    try {
    mt.waitForAll( );
    catch (InterruptedException e) {
    // error ...
    size = new Dimension (image.getWidth(null),
    image.getHeight(null));
    setSize(size);}
    public void paint(Graphics g) {
    g.drawImage(image, 0, 0, this);
    public Dimension getPreferredSize( ) {
    return size;
    public void runServer()
    try{
    server = new ServerSocket(port);
    client = server.accept();
    JOptionPane.showMessageDialog(null,"Connected");
    System.out.println("connection received from" + client.getInetAddress().getHostName());
    ous = new ObjectOutputStream( client.getOutputStream() );
    ous.flush();
    ins = new ObjectInputStream( client.getInputStream() );
    System.out.println("get i/o streams");
    catch(Exception e)
    e.printStackTrace();
    public static void main(String[] args)
    remote app = new remote();
    app.addWindowListener(
    new WindowAdapter(){
    public void windowClosing( WindowEvent e )
    System.exit( 0 );
    /* End Server */
    /*CLIENT code: */
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class Client extends JFrame
    private JLabel label1;
    private JButton button1;
    private Socket server;
    private ObjectInputStream ins=null;
    private ObjectOutputStream ous=null;
    private File file;
    private boolean autocontrol=true;
    public Client()
    super("Client");
    Container c = getContentPane();
    ButtonHandler handler = new ButtonHandler();
    c.setLayout( new FlowLayout() );
    label1 = new JLabel("");
    button1 = new JButton("connect");
    c.add(label1);
    c.add(button1);
    button1.addActionListener(handler);
    setSize(300,300);
    show();
    class ButtonHandler implements ActionListener
    public void actionPerformed(ActionEvent e)
    if(e.getActionCommand()=="connect")
    runClient();
    public void runClient()
    try{
    server = new Socket(InetAddress.getByName("127.0.0.1"),5000);
    System.out.println("connected to" + server.getInetAddress().getHostName());
    ous = new ObjectOutputStream(server.getOutputStream());
    ous.flush();
    ins = new ObjectInputStream(server.getInputStream());
    System.out.println("get i/o streams");
    file = new File("screen.jpg");
    listencommands();
    }catch(Exception e)
    e.getMessage();
    public void listencommands()
    try
    while(true){
    Object message = ins.readObject();
    if(message.equals("refresh"))
    screenshot();
    sendFile(file);
    if(message.equals("auto"))
    autocontrol=true;
    while(autocontrol)
    screenshot();
    sendFile(file);
    if(message.equals("stop"))
    autocontrol = false;
    catch(Exception e)
    e.printStackTrace();
    public void sendFile( File file ) throws IOException
    try{
    System.out.println("Ready to send file");
    ous.writeObject("sot");
    ous.flush();
    System.out.println("sot send");
    ous.writeObject("screen.jpg");
    ous.flush();
    System.out.println("fileName send");
    FileInputStream f = new FileInputStream (file);
    System.out.println("fileinputstream received");
    int size = f.available();
    byte array[] = new byte[size];
    f.read(array,0,size);
    System.out.println("Declared array");
    //ous.write(size);
    //ous.flush();
    ous.writeObject(array);
    ous.flush();
    System.out.println("image send");
    catch (Exception e)
    System.out.println(e.getMessage());
    public void screenshot()
    try
    //Get the screen size
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Rectangle rectangle = new Rectangle(0, 0, screenSize.width, screenSize.height);
    Robot robot = new Robot();
    BufferedImage image = robot.createScreenCapture(rectangle);
    File file;
    //Save the screenshot as a jpg
    file = new File("screen.jpg");
    ImageIO.write(image, "jpg", file);
    catch (Exception e)
    System.out.println(e.getMessage());
    public static void main( String args[] )
    Client app = new Client();
    app.addWindowListener(
    new WindowAdapter(){
    public void windowClosing( WindowEvent e )
    System.exit( 0 );
    }

  • Reloading and redrawing Icon using swing

    Hi,
    I am building an application in which I need to display several pictures in GIF format. At some point I allow the user to replace a picture from a pool of other pictures. I then rename the chosen picture to the name of the original picture and then replace the original picture. This is done using replaceIcon. My problem is that although the picture is being replaced, I cannot get it to reload and redisplay the picture. I get a Null pointer exception.
    It is essential for me to replace and rename the file since and since the pool of pictures might be large, it would be impractical to redirect the path to a new chosen picture. Anyone has encountered a similar problem? any help would be very much appreciated.
    thanks
    Nessen

    Hi,
    I am building an application in which I need to display several pictures in GIF format. At some point I allow the user to replace a picture from a pool of other pictures. I then rename the chosen picture to the name of the original picture and then replace the original picture. This is done using replaceIcon. My problem is that although the picture is being replaced, I cannot get it to reload and redisplay the picture. I get a Null pointer exception.
    It is essential for me to replace and rename the file since and since the pool of pictures might be large, it would be impractical to redirect the path to a new chosen picture. Anyone has encountered a similar problem? any help would be very much appreciated.
    thanks
    Nessen

  • Truly dumb question. How do I get PS to actually complete a command, eg straighten an horizon, and finalise the change. Even doing a "save as" with a new file name and reloading brings the image back, straightened, but with the skewed back ground frame st

    Truly dumb question. How do I get PS to actually complete a command, eg straighten an horizon, and finalise the change. Even doing a "save as" with a new file name and reloading brings the image back, straightened, but with the skewed back ground frame still there. Is there a "apply change" or similiar command that I simply cannot see.

    brings the image back, straightened, but with the skewed back ground frame
    PSE did what you told it to do. Choose the Straighten and crop edges or fill edges options when you use the straighten tool if you want it to do more than just straighten the contents of the image. Many people prefer the plain straighten because they'd rather crop themselves than let PSE do it.

  • Java + Safari causes page to 'flash' (i.e. reload even cached images)

    Does anyone know if this is able to be corrected or at least why this occurs?
    For Safari 4 beta when Java is active my site http://www.theimagecache.com 'flashes' a lot (i.e.reloads even cached images). Whereas with Java disabled this does not happen and the pages load considerably more quickly.
    I hadn't noticed this before in Safari 3+... but then again... I usually had Java turned off for security reasons so it may have existed then as well.
    But in Firefox 3.1b3, even with Java turned on the pages load very slightly more slowly (i.e. literally only about a fraction of a second more slowly... which is understandable) but they do not 'flash' (i.e. reload cached images).
    Any ideas as to if this can be corrected so viewers that have Java on by default and are using Safari do not see all of this flashing and slower loading?
    Thanks for any input.
    Ron

    Thanks Michael for posting.
    Yes... this Safari beta may be the problem, because even after the images have been cached often many of the images on a new page (that have already been cached) reload.
    Whereas in Firefox 3.1b3 (beta) this does not happen.
    Hopefully they'll get this fixed.
    Thanks again.
    Hope things are going well for you there in Sweden, considering all of the world economic problems.

  • Load, crop and saving jpg and gif images with JFileChooser

    Hello!
    I wonder is there someone out there who can help me with a applic that load, (crop) and saving images using JFileChooser with a simple GUI as possible. I'm new to programming and i hope someone can show me.
    Tor

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.filechooser.*;
    import javax.swing.filechooser.FileFilter;
    public class ChopShop extends JPanel {
        JFileChooser fileChooser;
        BufferedImage image;
        Rectangle clip = new Rectangle(50,50,150,150);
        boolean showClip = true;
        public ChopShop() {
            fileChooser = new JFileChooser(".");
            fileChooser.setFileFilter(new ImageFilter());
        public void setClip(int x, int y) {
            clip.setLocation(x, y);
            repaint();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            if(image != null) {
                int x = (getWidth() - image.getWidth())/2;
                int y = (getHeight() - image.getHeight())/2;
                g2.drawImage(image, x, y, this);
            if(showClip) {
                g2.setPaint(Color.red);
                g2.draw(clip);
        public Dimension getPreferredSize() {
            int width = 400;
            int height = 400;
            int margin = 20;
            if(image != null) {
                width = image.getWidth() + 2*margin;
                height = image.getHeight() + 2*margin;
            return new Dimension(width, height);
        private void showOpenDialog() {
            if(fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                try {
                    image = ImageIO.read(file);
                } catch(IOException e) {
                    System.out.println("Read error for " + file.getPath() +
                                       ": " + e.getMessage());
                    image = null;
                revalidate();
                repaint();
        private void showSaveDialog() {
            if(image == null || !showClip)
                return;
            if(fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                String ext = ((ImageFilter)fileChooser.getFileFilter()).getExtension(file);
                // Make sure we have an ImageWriter for this extension.
                if(!canWriteTo(ext)) {
                    System.out.println("Cannot write image to " + ext + " file.");
                    String[] formatNames = ImageIO.getWriterFormatNames();
                    System.out.println("Supported extensions are:");
                    for(int j = 0; j < formatNames.length; j++)
                        System.out.println(formatNames[j]);
                    return;
                // If file exists, warn user, confirm overwrite.
                if(file.exists()) {
                    String message = "<html>" + file.getPath() + " already exists" +
                                     "<br>Do you want to replace it?";
                    int n = JOptionPane.showConfirmDialog(this, message, "Confirm",
                                                          JOptionPane.YES_NO_OPTION);
                    if(n != JOptionPane.YES_OPTION)
                        return;
                // Get the clipped image, if available. This is a subImage
                // of image -> they share the same data. Handle with care.
                BufferedImage clipped = getClippedImage();
                if(clipped == null)
                    return;
                // Copy the clipped image for safety.
                BufferedImage cropped = copy(clipped);
                boolean success = false;
                // Write cropped to the user-selected file.
                try {
                    success = ImageIO.write(cropped, ext, file);
                } catch(IOException e) {
                    System.out.println("Write error for " + file.getPath() +
                                       ": " + e.getMessage());
                System.out.println("writing image to " + file.getPath() +
                                   " was" + (success ? "" : " not") + " successful");
        private boolean canWriteTo(String ext) {
            // Support for writing gif format is new in j2se 1.6
            String[] formatNames = ImageIO.getWriterFormatNames();
            //System.out.printf("writer formats = %s%n",
            //                   java.util.Arrays.toString(formatNames));
            for(int j = 0; j < formatNames.length; j++) {
                if(formatNames[j].equalsIgnoreCase(ext))
                    return true;
            return false;
        private BufferedImage getClippedImage() {
            int w = getWidth();
            int h = getHeight();
            int iw = image.getWidth();
            int ih = image.getHeight();
            // Find origin of centered image.
            int ix = (w - iw)/2;
            int iy = (h - ih)/2;
            // Find clip location relative to image origin.
            int x = clip.x - ix;
            int y = clip.y - iy;
            // clip must be within image bounds to continue.
            if(x < 0 || x + clip.width  > iw || y < 0 || y + clip.height > ih) {
                System.out.println("clip is outside image boundries");
                return null;
            BufferedImage subImage = null;
            try {
                subImage = image.getSubimage(x, y, clip.width, clip.height);
            } catch(RasterFormatException e) {
                System.out.println("RFE: " + e.getMessage());
            // Caution: subImage is not independent from image. Changes
            // to one will affect the other. Copying is recommended.
            return subImage;
        private BufferedImage copy(BufferedImage src) {
            int w = src.getWidth();
            int h = src.getHeight();
            BufferedImage dest = new BufferedImage(w, h, src.getType());
            Graphics2D g2 = dest.createGraphics();
            g2.drawImage(src, 0, 0, this);
            g2.dispose();
            return dest;
        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(getCropPanel(), gbc);
            panel.add(getImagePanel(), gbc);
            return panel;
        private JPanel getCropPanel() {
            JToggleButton toggle = new JToggleButton("clip", showClip);
            toggle.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    showClip = ((AbstractButton)e.getSource()).isSelected();
                    repaint();
            SpinnerNumberModel widthModel = new SpinnerNumberModel(150, 10, 400, 1);
            final JSpinner widthSpinner = new JSpinner(widthModel);
            SpinnerNumberModel heightModel = new SpinnerNumberModel(150, 10, 400, 1);
            final JSpinner heightSpinner = new JSpinner(heightModel);
            ChangeListener cl = new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    JSpinner spinner = (JSpinner)e.getSource();
                    int value = ((Number)spinner.getValue()).intValue();
                    if(spinner == widthSpinner)
                        clip.width = value;
                    if(spinner == heightSpinner)
                        clip.height = value;
                    repaint();
            widthSpinner.addChangeListener(cl);
            heightSpinner.addChangeListener(cl);
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weightx = 1.0;
            panel.add(toggle, gbc);
            addComponents(new JLabel("width"),  widthSpinner,  panel, gbc);
            addComponents(new JLabel("height"), heightSpinner, panel, gbc);
            return panel;
        private void addComponents(Component c1, Component c2, Container c,
                                   GridBagConstraints gbc) {
            gbc.anchor = GridBagConstraints.EAST;
            c.add(c1, gbc);
            gbc.anchor = GridBagConstraints.WEST;
            c.add(c2, gbc);
        private JPanel getImagePanel() {
            final JButton open = new JButton("open");
            final JButton save = new JButton("save");
            ActionListener al = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JButton button = (JButton)e.getSource();
                    if(button == open)
                        showOpenDialog();
                    if(button == save)
                        showSaveDialog();
            open.addActionListener(al);
            save.addActionListener(al);
            JPanel panel = new JPanel();
            panel.add(open);
            panel.add(save);
            return panel;
        public static void main(String[] args) {
            ChopShop chopShop = new ChopShop();
            ClipMover mover = new ClipMover(chopShop);
            chopShop.addMouseListener(mover);
            chopShop.addMouseMotionListener(mover);
            JFrame f = new JFrame("click inside rectangle to drag");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(chopShop));
            f.getContentPane().add(chopShop.getControls(), "Last");
            f.pack();
            f.setLocation(200,100);
            f.setVisible(true);
    class ImageFilter extends FileFilter {
        static String GIF = "gif";
        static String JPG = "jpg";
        static String PNG = "png";
        // bmp okay in j2se 1.5+
        public boolean accept(File file) {
            if(file.isDirectory())
                return true;
            String ext = getExtension(file).toLowerCase();
            if(ext.equals(GIF) || ext.equals(JPG) || ext.equals(PNG))
                return true;
            return false;
        public String getDescription() {
            return "gif, jpg, png images";
        public String getExtension(File file) {
            String s = file.getPath();
            int dot = s.lastIndexOf(".");
            return (dot != -1) ? s.substring(dot+1) : "";
    class ClipMover extends MouseInputAdapter {
        ChopShop component;
        Point offset = new Point();
        boolean dragging = false;
        public ClipMover(ChopShop cs) {
            component = cs;
        public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            if(component.clip.contains(p)) {
                offset.x = p.x - component.clip.x;
                offset.y = p.y - component.clip.y;
                dragging = true;
        public void mouseReleased(MouseEvent e) {
            dragging = false;
        public void mouseDragged(MouseEvent e) {
            if(dragging) {
                int x = e.getX() - offset.x;
                int y = e.getY() - offset.y;
                component.setClip(x, y);
    }

  • IPod display is upside down and mirror image - fixable?

    The display on my mom's iPod display is upside down and mirror image. I can read the menus if I hold the iPod horizontal, and look into a mirror about six inches in front of my nose, but it's inconvenient.
    I have tried the 5 R's (except for upgrading the Mac OS 10.3.9 - she has an 800 MHz G3 iBook and won't support Leopard). Apparently the songs all reloaded and play OK, but the display is hard to read without (and with!) the mirror.
    I found a similar help request from last June, but no solution.

    I have the same problem, have you found a solution.
    Janet1960

  • I am trying to import developed images from LightRoom 5 in o Photoshop 6.  I am receiving this message and the images will not open.....'Could not open scratch file because the file is locked, you do not have necessary access permissions or another progra

    I am trying to import developed images from LightRoom 5 Photoshop 6 for further editing.  I am receiving this message and the images will not open.....'Could not open scratch file because the file is locked, or you do not have necessary access permissions or another program is using the file.  Use the 'Properties' command in the Windows Explorer to unlock the file. How do I fix this?  I would greatly appreciate it if you would respond with terms and procedures that a computer ignorant user, such as me, will understand.   Thanks.

    Have you tried restoring the Preferences yet?

  • Web of Trust no longer working with google and bing image searches

    Hello All,
    I have searched and searched but have not found an answer that matches my specifics. Any help would be appreciated.
    I used to be able to do this but now I can no longer search and browse images on google or bing image search and have Web of Trust function. Here is how I am going about it.
    What I use:
    DuckDuckGo's annoymous google or bing image search link when I enter querries. Also, searching directly from Google's or Bing's image search page doesn't work with WOT anymore either.
    Firefox 23.0.1
    The following add-on's:
    Add-block plus 2.3.2
    BetterPrivacy 1.68
    Flagfox 4.2.12
    Ghostery 5.0.4
    Google/Yandex search link fix 1.4.1
    No Script 2.6.7.1
    Web of Trust 20130515
    If anyone has a fix for this please let me know.

    I guess what I learned is that sometimes the best solution is to do nothing and wait for the problem to solve itself! Funny, this has never worked for me before.
    WOT is now working for me but often for only the first few rows of images. That's cool that it is also working with bing images.
    Boudica, thanks for understanding. I am new contributor/ question-asker here on mozilla and may not understand how things are done. I was just frustrated, getting an email saying that my question was answered, logging in to find that it wasn't.
    Now we have the functionality that we wanted, right?

  • What is diff B/W dalta image and reverse image

    What is diff B/W dalta image and reverse image
    Edited by: Philip Eller on Jun 3, 2008 8:44 AM
    Edited by: Philip Eller on Jun 17, 2008 9:18 AM*

    Please post your question to the BW forum.

  • I am trying to use photomerge compose.  I open one standard jpeg image and one image that is my business logo in a png format.  When I select the png image, to extract the logo from it, it appears as all white and will not allow me to select the logo from

    I am trying to use photomerge compose.  I open one standard jpeg image and one image that is my business logo in a png format.  When I select the png image, to extract the logo from it, it appears as all white and will not allow me to select the logo from it.  It has worked in the past but I downloaded the update today and photomerge will not work correctly.  Any ideas?

    hedger,
    How do you expect anyone to help when we don't know a darned thing about the file, abut your setup, exact version of Photoshop and your OS, machine specs, etc.?
    BOILERPLATE TEXT:
    Note that this is boilerplate text.
    If you give complete and detailed information about your setup and the issue at hand,
    such as your platform (Mac or Win),
    exact versions of your OS, of Photoshop (not just "CS6", but something like CS6v.13.0.6) and of Bridge,
    your settings in Photoshop > Preference > Performance
    the type of file you were working on,
    machine specs, such as total installed RAM, scratch file HDs, total available HD space, video card specs, including total VRAM installed,
    what troubleshooting steps you have taken so far,
    what error message(s) you receive,
    if having issues opening raw files also the exact camera make and model that generated them,
    if you're having printing issues, indicate the exact make and model of your printer, paper size, image dimensions in pixels (so many pixels wide by so many pixels high). if going through a RIP, specify that too.
    etc.,
    someone may be able to help you (not necessarily this poster, who is not a Windows user).
    a screen shot of your settings or of the image could be very helpful too.
    Please read this FAQ for advice on how to ask your questions correctly for quicker and better answers:
    http://forums.adobe.com/thread/419981?tstart=0
    Thanks!

  • I am trying to import developed images from LightRoom 5 into Photoshop 6.  I am receiving this message and the images will not open.....'Could not open scratch file because the file is locked, you do not have necessary access permissions or another progra

    I am trying to import developed images from LightRoom 5 into Photoshop 6.  I am receiving this message and the images will not open.....'Could not open scratch file because the file is locked, you do not have necessary access permissions or another program is using the file.  Use the 'properties' command in the Windows Explorer to unlock the file'.  This has not happened before.  How do I change this?

    Could not open a scratch file because the file is locked or you do not have the necessary access privileges. (…) | Mylen…
    Mylenium

  • What is the fastest way to record and write image data?

    Hello,
    I am new to labview and am using the IMAQ software package to record and write data from a CCD camera to the hard drive. The end goal is a program that records and saves as much data as possible as quickly as possible, for experiments lasting on the scale of days. I have been experimenting with the snap, grab, and sequence methods of recording. To save the image data I was told by NI customer support that TDMS streaming would be the fastest method. I have also been experimenting with the TDMS VIs, however I have found the IMAQ Write File 2 VI to be faster in practice. Am I doing something wrong with the TDMS file structure? Is there a more efficient way to convert IMAQ image data to a dataform that can be written as TDMS? I am posting two of my programs to provide a clearer example of what I am trying to do. The first takes a snap of the image and appends it to a TDMS file. The second is the fastest I have found so far and uses Grab to record the images and the IMAQ Write File VI to save them. 
    Thanks
    Attachments:
    Camera Capture (Snap) and stream TDMS.vi ‏24 KB
    Camera Capture (Grab) and write image.vi ‏24 KB

    Hi
    For me it is no surprise that the second VI is faster then the first one, the reason is you can not compare this two VI with each other.
    In the first VI you work with TDMS files, in the second with png files. That would be much faster, because TDMS files need a lot of diskspace.
    Second point, why do you open, write and close for eacht iteration of the for loop a TDMS file in your first VI? That need really a lot of resources, so it coudn´t be fats as well.
    Save your converted pictures in one array, an after the acquisition you can save it in one TDMS file. When you need for each picture a TDMS file you have to know that this need some time to do this.
    So now for the architecture of your first VI, please look to the LL Sequence.vifrom the examples (C:\Program Files\National Instruments\LabVIEW 8.6\examples\IMAQ\IMAQ Low Level.llb\LL Sequence.vi), there you can see how an acquisition of a number of images have been to do.
    When you like it really fast, you make a producer/consumer architecture (see examples in LabVIEW for that).
    So in the first whileloop you acquire the images, write into a queue and in the second, parallel whileloop you read the queue and save the images. (see attachment)
    Hope that helps
    Kind regards
    Beat
    NI Germany
    Attachments:
    ProducerConsumerData.vi ‏10 KB
    ProducerConsumerData_LV8.5.vi ‏12 KB

  • I have an IPad 2 and an Iphone4, but as it suggests that I can click a photo on my iPhone and the image will also reflect simultaneously on my IPad does not happen, though I have activated cloud on my iPhone. What could be the problem.???

    I have an IPad 2 and an Iphone4, but as it suggests that I can click a photo on my iPhone and the image will also reflect simultaneously on my IPad does not happen, though I have activated cloud on my iPhone. What could be the problem.???
    Also in my iPhone4 the photos that I have downloaded manually from my computer cannot be erased from the phone, how do i do this.???

    Sounds like you are not running iOS 5 ..........
    Update your iPad 2 to iOS 5............
    I purchased an iPad 2 for my wife for Xmas and it did not come with iOS 5 so I had to update it......
    http://www.apple.com/icloud/get-started/
    http://support.apple.com/kb/HT4972

Maybe you are looking for

  • Get key values from HashMap

    Hi, I'm trying to get the values of the keys in my HashMap into a String array. Here is the code I'm using: HashMap row = new HashMap(); row.put("A","Approved"); row.put("D","Disapproved"); row.put("P","Pending Approval"); row.put("S","For Simulation

  • Can not update ipod ios

    I can not update my ipod touch....its model is 4.3.5.(8L1)... i tried to update on i tunes...everytime for 70 minutes it loads and loads and at the end itt gives error...and can not load the update....so icant update to ios 5...is there an other way

  • Purchase Order with (BOM) Components.

    Hi Gurus, We want to create PO with a component list that should be appears under the main item. The component list is a mterial BOM. exam:- bom MATERIAL - CATALOG1 (Non Stock Materials) COMPONENT 1 :-ABCD COMPONENT 2 :- XYZ. WHEN I ENTER THE BOM MAT

  • SAP JAM work pattern for SAP C4C Service ticket

    Can anybody familiar with the SAP JAM Work pattern for SAP Cloud for Customer Service tickets answer these questions? My client would like to use SAP JAM groups in Service tickets in the following way: C4C service agents raise service tickets which a

  • What to do if Photoshop CC update gives download error repeatedly?

    Creative Cloud tells me there are updates for many apps, including Photoshop CS6 and Photoshop CC (2014).  When I try to download them, others work fine, but the two Photoshops give a download error; retry does not help.  Error is marked (49).  What