?
Solved

Applet displaying an image and letting user select area

Posted on 2002-04-21
6
Medium Priority
?
227 Views
Last Modified: 2009-07-29


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?
0
Comment
Question by:borbjo
[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
6 Comments
 

Expert Comment

by:mickoo
ID: 6957824
try redrawing only certain part of the image using cliprect or drawrect.Not very sure the name of the function so check the api
0
 
LVL 92

Expert Comment

by:objects
ID: 6958373
Can we see your code?
0
 

Author Comment

by:borbjo
ID: 6959021
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());
                  }
      }      
      };

};
0
Technology Partners: 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!

 

Author Comment

by:borbjo
ID: 6959111

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
0
 
LVL 9

Expert Comment

by:Venci75
ID: 7973079
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
0
 

Accepted Solution

by:
SpideyMod earned 0 total points
ID: 8021392
per recommendation

SpideyMod
Community Support Moderator @Experts Exchange
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying 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

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Suggested Courses
Course of the Month8 days, 8 hours left to enroll

765 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