Link to home
Start Free TrialLog in
Avatar of borbjo
borbjoFlag for Norway

asked on

Applet displaying an image and letting user select area



I'm creating an applet that's going to display an image on the screen, letting the user select an area, and grabbing the x,y,height,width positions of that area.

The way I am doing it now:
- Using getImage() >> icon >> label >> panel >> container to display the image ..
- I use MouseMotionListener to do a repaint() and then drawRect() when the user drags on the screen.

This will display the image, and let the user select a rectangle.

However, it does not look that good. It's a bit slow, and it flickers. I suppose this is because the repaint() (to draw the image on the screen again, and removing the rectangle) and the drawRect over it to draw the new rectangle.

Any other, better solutions?
Avatar of mickoo
mickoo

try redrawing only certain part of the image using cliprect or drawrect.Not very sure the name of the function so check the api
Avatar of Mick Barry
Can we see your code?
Avatar of borbjo

ASKER

Sure, it's a bit messy but I was going to fix that now .. ignore the comments unless you understand norwegian.
--------------
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.lang.Object.*;
import java.net.*;


public class imageCrop extends javax.swing.JApplet implements MouseListener, MouseMotionListener, ActionListener {
      
      private Image img;
      private int drawX=0, drawY=0,startX=-1,startY=-1;            // disse variable holder greie pe width, height, xpos, ypos
      private String imageFile;
      private JPanel panel, panel2;
      private JLabel bilde;
      private JButton quitBtn;
      private JCheckBox chk;
      private JTextField txtX,txtY;
      boolean prop=false;                                                            // holder greie pe om keep proportions er true eller ikke
      boolean allowChangeProp=false;

      // init kjxres fxrst, oppretter paneler
      public void init() {
            Container c = getContentPane();
       
            GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints cons = new GridBagConstraints();
            cons.gridheight = 1;

            panel = new JPanel( gridbag );
            quitBtn = new JButton("Use Selection");
            quitBtn.setSize(20,10);
            quitBtn.addActionListener( this );
      

            // Her hentes Parameterne fra HTML filen
            imageFile = getParameter("image");                                          // hent filnavn
            allowChangeProp = (getParameter("AllowChangeProportions").equals("1")?true:false); // lov til e forandre proporsjoner? (checkbox)
      
            img = getImage( getCodeBase(), imageFile );                        // load bildet
            ImageIcon icn = new ImageIcon(img);                                    // opprett nytt ikon av bildet
            bilde = new JLabel(icn);                                                // legg ikonet inn i en JLabel

            bilde.addMouseListener(this);                                          // opprett MouseListener pe bildet
            bilde.addMouseMotionListener(this);
            

            txtX = new JTextField("0000");
            txtY = new JTextField("0000");
            chk = new JCheckBox("Keep proportions");
            
            CheckBoxListener myListener = new CheckBoxListener();
            TextFieldListener txtListener = new TextFieldListener();
            
            txtX.addActionListener(txtListener);
            txtY.addActionListener(txtListener);
            chk.addItemListener(myListener);

            // Hvis PARAM AllowChangeProportions er false, gjxr dette:
            if(allowChangeProp == false) {
                  chk.setSelected(true);
                  chk.setEnabled(false);
                  prop=true;
            }

            gridbag.setConstraints(txtX, cons);            
            gridbag.setConstraints(txtY, cons);            
            gridbag.setConstraints(chk, cons);            

            panel.add(txtX);
            panel.add(txtY);
            panel.add(chk);

            gridbag.setConstraints(quitBtn, cons);
            panel.add(quitBtn);
            cons.gridwidth = GridBagConstraints.REMAINDER;
            gridbag.setConstraints(bilde, cons);
            c.add(bilde, BorderLayout.WEST);
            gridbag.setConstraints(panel, cons);

            c.add(panel, BorderLayout.SOUTH);
      }


      // ActionListener for Use Selection knappen
      public void actionPerformed(ActionEvent e) {
            if(e.getActionCommand().equals("Use Selection")) {
                  System.out.println("Exit!");
            }
      }

      // Mouse listeners - behandler events fra musen
      public void mousePressed(MouseEvent e) {
            System.out.println("Mouse PRessed");
            startX = e.getX();
            startY = e.getY();
            System.out.println("new startX=" + startX + ", startY=" + startY);
      }

    public void mouseReleased(MouseEvent e) {
         System.out.println("mouseReleased:");

               if(startX != -1) {
                  drawSelection();
                  startX = e.getX();
                  startY = e.getY();
                  System.out.println("new startX=" + startX + ", startY=" + startY);
            }
      }

    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}

    public void mouseClicked(MouseEvent e) {
         // hvis bruker klikker med musen skal firkanten fjernes
         startX = -1;
         startY = -1;
         repaint();
      }

      // MouseMotionListener implementasjon
      public void mouseMoved(MouseEvent e) {}

      public void mouseDragged(MouseEvent e) {
            System.out.println("Mouse x,y: [" + e.getX() + "," + e.getY() + "]");
          if(startX == -1) {
                  startX = e.getX();
                startY = e.getY();
                  System.out.println("startX==1 - new startX=" + startX + ", startY=" + startY);
                  drawSelection();
            }
            else {
                  
                  drawY = e.getY();
                  drawX = e.getX();
                  repaint();
                  drawSelection();
            }
      }

      // Metode som tegner firkanten over bildet
      public void drawSelection() {
                  Graphics g = bilde.getGraphics();
               
                  if(prop == true ) {
                        drawX = drawY;
                  }

                  g.drawString( startX + "," + startY + " => " + drawX + "," + drawY + ": " + (drawX-(prop == true ? startY:startX)) + "x" + (drawY-startY), startX+20,startY+20);
               
                  if( (drawX-startX) < 0 && (drawY-startY) < 0 ) {
                        System.out.println("** NEGATIVE DRAWING");
                        startX = startX + drawX;
                        startY = startY + drawY;
                        g.drawRect(startX, startY, drawX + ( prop == true ? startY : startX ), drawY + startY);
                  }                        
                  else
                        g.drawRect(startX, startY, drawX - ( prop == true ? startY : startX ), drawY - startY);
                  
                  
                  
                  txtY.setText(""+(drawY-startY));                                                // oppdater textbox med Y verdi
                  txtX.setText(""+(drawX-( prop == true ? startY : startX )));      // oppdater textbox med X verdi
      }


      class CheckBoxListener implements ItemListener {
            public void itemStateChanged(ItemEvent e) {
                  Object source = e.getItemSelectable();
                  if (source==chk)
                  {
                        // sett keep proportions ..
                        if (e.getStateChange() == ItemEvent.DESELECTED) {
                              prop = false;
                        }
                        else
                              prop = true;
                  }
            }
      };

      // Klasse som behandler textfield events
      class TextFieldListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                  if( e.getSource() == txtX ) {
                        // hvis txtX forandres, sett width (drawX) til e bli Start posisjon + txtX
                        drawX = startX + Integer.parseInt(txtX.getText());
                        repaint();
                        drawSelection();
                        System.out.println(txtX.getText());
                  }
                  else if( e.getSource() == txtY) {
                        // hvis txtY forandres, sett height (drawY) til e bli Start posisjon + txtY
                        drawY = startY + Integer.parseInt(txtY.getText());
                        repaint();
                        drawSelection();
                        System.out.println(txtY.getText());
                  }
      }      
      };

};
Avatar of borbjo

ASKER


Hmm, ok, I "cleaned up" my code a bit.

Created an imagePanel class that would take care of drawing the image AND the rectangle.

And it doesn't "flicker" any more .. thanks for answering guys! :)

- bjorn
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:
PAQ'd and pts refunded
Please leave any comments here within the next seven days.
 
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
 
Venci75
EE Cleanup Volunteer
ASKER CERTIFIED SOLUTION
Avatar of SpideyMod
SpideyMod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial