Solved

Applet displaying an image and letting user select area

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

Expert Comment

by:mickoo
Comment Utility
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
Comment Utility
Can we see your code?
0
 

Author Comment

by:borbjo
Comment Utility
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 

Author Comment

by:borbjo
Comment Utility

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
Comment Utility
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
Comment Utility
per recommendation

SpideyMod
Community Support Moderator @Experts Exchange
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
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 will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

772 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now