Solved

Applet displaying an image and letting user select area

Posted on 2002-04-21
6
224 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

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
sql import cannot be resolved jsp 3 113
java example issue 5 63
Cisco ASA: Java web start no go, asdm launcher no go 3 81
Where to place postgres JDBC driver jar on tomcat 8 66
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…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses

738 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