Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Applet displaying an image and letting user select area

Posted on 2002-04-21
6
Medium Priority
?
228 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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

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

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

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 …
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses

618 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