MouseMove problem in JPanel

Hello I am writing an applet and I am calling a class which extends JPanel.
In the JPanel I am trying to create a rectangle (fillRect) which than I will be able to move using the method mouseMove().
I have been able to draw the rectangle on the panel which is in the applet but i havent succeded in moving the rectangle with mouseMove().
Could somebody please show me to implement the mouseMove correctly .

Here's a sloppy sort of example for you. It could be vastly improved, but it shows you one example of using a MouseMotionAdapter to change the state of your JPanel subclass.
Basically, you maintain a model - in this case, the location of your rectangle. When you get input from the mouse, you change the model appropriately. Then you need your view to be redrawn to show your new model. In this case, we just call repaint() and let Swing handle it. In other programs, you might have a loop continuously redrawing the view for you (but that's another story).
Cheers,
John
package moop;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JPanel;
public class MyPanel extends JPanel  {
     /** the last known location of the corner of our rectangle  */
     private Point cornerPoint = new Point(0,0);
      * Constructor, giving us a chance to add a mouse motion listener.
     public MyPanel() {
          addMouseMotionListener(new MouseMotionAdapter() {
                * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
               public void mouseMoved(MouseEvent e) {
                    cornerPoint.x = e.getX() - 10;
                    cornerPoint.y = e.getY() - 10;
                    repaint();
      * Override the default method to draw a rectangle.
     public void paintComponent(Graphics g) {
          // let the superclass do it's stuff first
          super.paintComponent(g);          
          // draw a red rectangle
          g.setColor(Color.red);
          g.fillRect(cornerPoint.x, cornerPoint.y, 20, 20);
}

Similar Messages

  • Problem with Jpanel repaintingl

    Hi!
    I have a problem with Jpanel.
    First , I add a Jscrollpane to the panel and I don't
    see it.
    Second, I have a paint method in the Jpanel and I do there some painting but when I exe the application I can see the panel painting only when I put the mouse cursor
    on the place where the panel need to be.
    It is very strange.
    Help me.
    Yair.

    Example code??
    Can't tell what's wrong otherwise.
    First , I add a Jscrollpane to the panel and I don't
    see it.Have you added anything to this JScrollPane? Unless you set the scroll bar policies to always on you won't see anything if you haven't added anything to the scrollpane.
    Also, if you're only adding this scrollPane to your JPanel initilise it with
    JPanel whippet = new JPanel(new BorderLayout())
    .. then when you add your scrollPanel to your JPanel do this to make sure its added slap in the in middle of it:
    whippet.add(yourScrollPanel, BorderLayout.CENTER);
    Bit more info please - duuuuuuuuuuuuuuuude (man, "Finding Nemo" was well funny didn't you think.. anyways, that's besides the point.... could just be my 8 year old mental age though.. who knows.)?

  • Problem with JPanel and/or Thread

    Hello all,
    I have the following problem.
    I have a JFrame containing to JPanels. The JPanels are placed
    via BorderLayout.
    JPanel #1 is for moving a little rectangle (setDoubleBufferd), it is
    a self defined object extending JPanel.
    The paint methon in JPanel #1 has been overwritten to do the drawings.
    JPanel #2 contains 4 JButtons, but they have no effect at the
    moment. It is an "original" JPanel.
    The class extending JFrame implemented the interface Runnable and
    is started in its own thread.
    After starting the programm everthing looks fine.
    But if I press a Button in the second JPanel this button is painted in
    the top left corner of my frame. It changes if I press another button.
    Any help would be appreciated.
    Thanks.
    Ralf

    I have a JFrame containing to JPanels. The JPanels are
    placed
    via BorderLayout.The type of Layout does not seem to be relevant
    >
    JPanel #1 is for moving a little rectangle
    (setDoubleBufferd), it is
    a self defined object extending JPanel.
    The paint methon in JPanel #1 has been overwritten to
    do the drawings.
    JPanel #2 contains 4 JButtons, but they have no effect
    at the
    moment. It is an "original" JPanel.
    The class extending JFrame implemented the interface
    Runnable and
    is started in its own thread.
    After starting the programm everthing looks fine.
    But if I press a Button in the second JPanel this
    button is painted in
    the top left corner of my frame. It changes if I press
    another button.
    I noticed you solved this by painting the whole JFrame.
    Yeh Form time to time I get this problem too......
    Especially if the screen has gone blank - by going and having a cup of tea etc -
    Text from one Panel would be drawn in another.. annoying
    At first it was because I changed the state of some Swing Components
    not from the Event Thread.
    So make sure that your new Thread doesn't just blithely call repaint() or such like cos that leads to problems
    but rather something like
    SwingUtilities.invokeLater( new Runnable()
       public void run()
          MyComponent.repaint();
    });However I still get this problem using JScrollPanes, and was able to fix it by using the slower backing store method for the JScrollPane
    I could not see from my code how something on one JPanel can get drawn on another JPanel but it was happening.
    Anyone who could totally enlighten me on this?

  • Problem with JPanel in JFrame

    hai ashrivastava..
    thank u for sending this one..now i got some more problems with that screen .. actually i am added one JPanel to JFrame with BorderLayout at south..the problem is when i am drawing diagram..the part of diagram bellow JPanel is now not visible...and one more problem is ,after adding 6 ro 7 buttons remaing buttons are not vissible..how to increase the size of that JPanel...to add that JPanel i used bellow code
    JFrame f = new JFrame();
    JPanel panel = new JPanel();
    f.getContentPane().add(BorderLayout.SOUTH, panel);

    Hi
    JFrame f = new JFrame();
    JPanel panel = new JPanel();
    // Add this line to ur code with ur requiredWidth and requiredHeight
    panel.setPreferredSize(new Dimension(requiredWidth,requiredHeight));
    f.getContentPane().add(BorderLayout.SOUTH, panel);
    This should solve ur problem
    Ashish

  • Problem with JPanel, JMenuBar

    Hi, I'm new here so I'm not even sure if I'm posting in the correct forum ^^
    I usually don't have problems when building a JFrame and adding items into it but now I'm confused.
    When the JFrame is "built", I get a NullPointerException from the Panel's paintComponent method when it's trying to draw an image (g.drawImage())
    This is the whole JPanel class
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class PanneauDe extends JPanel
      private static final String [] TAB_IMAGE = { "De1.GIF", "De2.GIF", "De3.GIF",
                                                   "De4.GIF", "De5.GIF", "De6.GIF" };
      private static final int [] TAB_FREQUENCE = {0,0,0,0,0,0};
      private static final int SIDE = 100;
      private De unDe;
      private ImageIcon imageDe;
      private boolean aFirstTime;
      private int aX, aY; 
      public PanneauDe()
        unDe = new De();
        aX = aY = 0;
        aFirstTime = true;  
        addMouseListener(new EcouteurSouris());   
      public String getStats()
        String statsMsg = "";
        for ( int iPos = 0; iPos < TAB_FREQUENCE.length; iPos ++ )
          statsMsg += "Face " + (iPos + 1) + " : " + TAB_FREQUENCE[iPos] + " fois\n\n";
        return statsMsg;
      public String getTotal()
        int total = 0;
        for ( int iPos = 0; iPos < TAB_FREQUENCE.length; iPos ++ )
          total += TAB_FREQUENCE[iPos];
        return "Le d� a �t� lanc� " + total + " fois";
      public void throwDice()
        unDe.throwAgain();
        TAB_FREQUENCE[unDe.getFace() - 1] ++;   
      public void paintComponent (Graphics g) 
        super.paintComponent(g);
        g.drawImage (imageDe.getImage(), aX, aY, null); // <---- THIS GENERATES THE NULLPOINTEREXCEPTION
      class EcouteurSouris extends MouseAdapter
        public void mouseClicked (MouseEvent pMouseEvent)
          aX = pMouseEvent.getX();
          aY = pMouseEvent.getY();
          throwDice();
          imageDe = new ImageIcon(TAB_IMAGE[unDe.getFace() - 1]);
          repaint();
    }When I click in the windows, a picture of a dice (different side, randomly generated by the method throwDice() ), when I click again the first image dissapear and another one appears... and I make statistics about the results.
    I tried ...
      public void paintComponent (Graphics g) 
        super.paintComponent(g);
        //g.drawImage (imageDe.getImage(), aX, aY, null);
      class EcouteurSouris extends MouseAdapter
        public void mouseClicked (MouseEvent pMouseEvent)
          aX = pMouseEvent.getX();
          aY = pMouseEvent.getY();
          throwDice();
          imageDe = new ImageIcon(TAB_IMAGE[unDe.getFace() - 1]);
          Graphics g = getGraphics();
          g.drawImage (imageDe.getImage(), aX, aY, null);
          g.dispose();
        }Everything works correctly, no more NullPointerException, but the images don't dissapear when I click again. They just stay there.
    I'm not completly familiar with the repaint/dispose/paintComponent but I really don't understand why i get this NullPointerException error :\
    If you see some weird words in the code, it's because i'm canadian-frenchy! :)
    Full program is here

    The real question is why are you trying to override the paintComponent() method. Just add the image to a JLabel and add the label to a panel.
    However, the problem is that the paintComponent() method is invoked when the frame is shown and since you don't create the image until you do a mouseClick, the image in null.

  • Problem with jpanel size

    Hi I want to add a view port to a JPanel
    the main problem is that the Jpanel change size as the frame.
    how can i make it independent from the frame so having it; own w, h
    thanks
    package help;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import javax.swing.*;
    public abstract class MyFrame extends JFrame {
    private static final long serialVersionUID = 1L;
    private static JButton drawCircle, drawRectangle, drawSquare, drawStar, start, clear,quit,back, screenshoot;
    static final int FPS_MIN = 0;
    static final int FPS_MAX = 150;
    static final int FPS_INIT = 0;
    static int fps;
    double x1,x2;
    double y1,y2;
    int dr =1;
    int dy= 1;
    int Selection=0;
    boolean click=true; //check if start has been clicked
    int width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;  // screen width
    int height = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;     //screen higth
    protected static int count;
    int R,G,B;  //color
    Cursor c;                    //cursor object
    private static ShapePanel bpnl;
    public MyFrame()
            R=G=B=0;
            int width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;
            int height = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height-100;
            JFrame frame=new JFrame();
            BorderLayout layout=new BorderLayout();
            frame.setLayout(layout);
            frame.setTitle("Game");
            //panel to hold buttons
            JPanel upPanel = new JPanel();
            upPanel.setLayout(new FlowLayout());
            upPanel.setSize(width, height/5);
            //panel to hold SLIDERS
            JPanel leftPanel = new JPanel();
            leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
            leftPanel.setSize(50, height);
            //initialize buttons and add to the upPanel
            drawCircle=new JButton("Draw Circle");
            upPanel.add(drawCircle);
            drawStar=new JButton("Draw Star");
            upPanel.add(drawStar);
            drawRectangle=new JButton("Draw Rectangle");
            upPanel.add(drawRectangle);
            drawSquare=new JButton("Draw Square");
            upPanel.add(drawSquare);
            start=new JButton("Start");
            start.setBackground(Color.GREEN);
            //upPanel.add(start);
            clear=new JButton("Clear");
            upPanel.add(clear);
            back=new JButton("Back");
            upPanel.add(back);
            quit=new JButton("Quit");
            quit.setBackground(Color.red);
            upPanel.add(quit);  
            screenshoot=new JButton("ScreenShoot");
            c = new Cursor (Cursor.CROSSHAIR_CURSOR);     //Change cursor to cross hair
         this.setCursor (c);
            //new object spanel to hold TIMER
            JPanel spanel=new JPanel();
                spanel.setLayout(new GridLayout());
                //slider dimension construction
                JSlider sDimension = new JSlider(JSlider.HORIZONTAL,FPS_MIN, FPS_MAX, FPS_INIT);
                sDimension.setMajorTickSpacing(30);
                sDimension.setMinorTickSpacing(3);
                sDimension.setPaintTicks(true);
                sDimension.setPaintLabels(true);
                Font font = new Font("Serif", Font.ITALIC, 15);
                sDimension.setFont(font);
                sDimension.setBorder(BorderFactory.createTitledBorder("Shape Dimension"));
                //slider speed construction
                int FPS_MIN_s = 0;
                int FPS_MAX_s = 60;
                int FPS_INIT_s = 0;    //initial frames per second
                JSlider sSpeed = new JSlider(JSlider.HORIZONTAL,FPS_MIN_s, FPS_MAX_s, FPS_INIT_s);
                sSpeed.setBorder(BorderFactory.createTitledBorder("Shape Speed"));
             ////////////////////////// // slider colors////////////////////////////////////////////////////
                int FPS_MIN_C = 0;
                int FPS_MAX_C = 250;
                int FPS_INIT_C = 0;  
                JSlider sliderR= new JSlider(JSlider.HORIZONTAL,FPS_MIN_C, FPS_MAX_C, FPS_INIT_C);
                sliderR.setBorder(BorderFactory.createTitledBorder("Red Channel"));
                JSlider sliderG= new JSlider(JSlider.HORIZONTAL,FPS_MIN_C, FPS_MAX_C, FPS_INIT_C);
                sliderG.setMajorTickSpacing(50);
                sliderG.setMinorTickSpacing(25);
                sliderG.setPaintTicks(true);
                sliderG.setPaintLabels(true);
                sliderG.setFont(font);
                sliderG.setBorder(BorderFactory.createTitledBorder("Green Channel"));
                JSlider sliderB= new JSlider(JSlider.HORIZONTAL,FPS_MIN_C, FPS_MAX_C, FPS_INIT_C);
                sliderB.setBorder(BorderFactory.createTitledBorder("Blue Channel"));
              //     spanel.add(sSpeed,BorderLayout.EAST);
                  frame.add(upPanel,BorderLayout.NORTH);
                  frame.add(leftPanel,BorderLayout.WEST);
                  bpnl = new ShapePanel(3000,3000);
                        System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
                        bpnl.setFocusable(true);
                  upPanel.setBackground(Color.DARK_GRAY);
                  upPanel.setBorder(BorderFactory.createLineBorder(Color.white));
            frame.add(spanel,BorderLayout.SOUTH);       
            frame.add(bpnl, BorderLayout.CENTER);
            frame.setSize(width, height);
            frame.setVisible(true);               
               leftPanel.add(sliderR);
               leftPanel.add(sliderB);
               leftPanel.add(sliderG);
               leftPanel.add(sDimension,BorderLayout.WEST); 
                 System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
              public static  int getPanelWidth()
                  System.out.println("panel width   "+bpnl.getWidth());
                  return bpnl.getWidth();
              public static  int getPanelHeigth()
                  System.out.println("Panel heigth  " +bpnl.getHeight());
                  return bpnl.getHeight();
              public static void main(String args[])
                  new MyFrame() {};
    package help;
    import java.awt.Cursor;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    class ShapePanel extends JPanel  {
         private static final long serialVersionUID = 1L;
         private javax.swing.Timer animationTmr;
         private float heigth;
         private float width;
         private Cursor c;
         public ShapePanel(int w, int h) {
                    int W=w;
                    int H=h;
                    c = new Cursor (Cursor.CROSSHAIR_CURSOR);     //Change cursor to cross hair
                    this.setCursor (c); 
                    this.setPreferredSize(3000,3000);
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.fillRect(0, 0, this.getWidth(), this.getHeight());
        private void setPreferredSize(int i, int i0) {
        thanks

    sorry i hope this is better
    package help;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public abstract class MyFrame extends JFrame {
    private static final long serialVersionUID = 1L;
    int dr =1;
    int dy= 1;
    int Selection=0;
    int width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;  // screen width
    int height = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height-100;     //screen higth
    private static ShapePanel bpnl;
    public MyFrame()
            JFrame frame=new JFrame();
            BorderLayout layout=new BorderLayout();
            frame.setLayout(layout);
            bpnl = new ShapePanel(3000,3000);
            System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
            bpnl.setFocusable(true);
              frame.add(bpnl);
            frame.setSize(width, height);
               pack();
            frame.setVisible(true);               
    System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
              public static  int getPanelWidth()
                  System.out.println("panel width   "+bpnl.getWidth());
                  return bpnl.getWidth();
              public static  int getPanelHeigth()
                  System.out.println("Panel heigth  " +bpnl.getHeight());
                  return bpnl.getHeight();
              public static void main(String args[])
                  new MyFrame() {};
    package help;
    import java.awt.Cursor;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    class ShapePanel extends JPanel  {
         private static final long serialVersionUID = 1L;
         private Cursor c;
         public ShapePanel(int w, int h) {
                    int W=w;
                    int H=h;
                    c = new Cursor (Cursor.CROSSHAIR_CURSOR);     //Change cursor to cross hair
                    this.setCursor (c); 
                    this.setPreferredSize(3000,3000);
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.fillRect(0, 0, this.getWidth(), this.getHeight());
        private void setPreferredSize(int i, int i0) {
       

  • Problem with jpanel zooming

    friends,
    i have a jpanel with image as background and i am adding jlabels dynamically to the jpanel. i have to move the jlabel on the image so i added mouse listener to jlabel. now i want to add zooming functionality to the jpanel.
    now if zoom out jpanel everything works well but jlabel mouse listener location is not changing so if i click on jlabel its not activating listener - i need to click outside of jlabel/jpanel (its original location when its 100% zoom) to activate the listener. how can i correct this ?
    thanks in advance
    i will add example after i cutdown (its part of big application)

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.*;
    import java.util.ArrayList;
    import java.util.List;
    import javax.imageio.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    public class PP3 extends JFrame {
        private JButton btnStart;
        private JButton btnStop;
        private JLabel logoLabel;
        private JSlider zoom;
        private JPanel mainPanel;
        private JPanel btnPanel;
        private JScrollPane jspane;
        private BackPanel3 secondPanel;
        private boolean start = false;
        public PP3() {
            initComponents();
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        private void initComponents() {
            logoLabel = new JLabel();
            mainPanel = new JPanel();
            btnPanel = new JPanel();
            btnStart = new JButton();
            btnStop = new JButton();
            zoom = new JSlider(0,100,100);
            setBackground(Color.white);
            setLayout(new BorderLayout());
            mainPanel.setBackground(Color.white);
            mainPanel.setBorder(new EtchedBorder());
            mainPanel.setPreferredSize(new Dimension(650, 600));
            mainPanel.setLayout(new CardLayout());
            jspane = new JScrollPane(getSecondPanel());
            mainPanel.add(jspane,"Second Panel");
            add(mainPanel, BorderLayout.CENTER);
            btnPanel.setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weighty = 1.0;
            gbc.gridwidth = gbc.REMAINDER;
            btnPanel.setBackground(Color.white);
            btnPanel.setBorder(new EtchedBorder());
            btnPanel.setPreferredSize(new Dimension(150, 600));
            btnStart.setText("Start Labelling");
            btnPanel.add(btnStart, gbc);
            btnStart.setEnabled(true);
            btnStart.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent ae){
                    start = true;
                    btnStart.setEnabled(false);
                    btnStop.setEnabled(true);
                    if(secondPanel != null){
                        secondPanel.setStart(start);
                        Cursor moveCursor = new Cursor(Cursor.TEXT_CURSOR);
                        secondPanel.setCursor(moveCursor);
            btnStop.setText("Done Labelling");
            btnPanel.add(btnStop, gbc);
            btnStop.setEnabled(false);
            btnStop.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent ae){
                    start = false;
                    btnStart.setEnabled(true);
                    btnStop.setEnabled(false);
                    if(secondPanel != null){
                        secondPanel.setStart(start);
                        Cursor moveCursor = new Cursor(Cursor.DEFAULT_CURSOR);
                        secondPanel.setCursor(moveCursor);
            final JLabel zoomLabel = new JLabel("Zoom");
            zoomLabel.setBorder(BorderFactory.createEtchedBorder());
            gbc.weighty = 0;
            gbc.weightx = 1.0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            btnPanel.add(zoomLabel, gbc);
            btnPanel.add(zoom, gbc);
            zoom.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent ce) {
                    JSlider source = (JSlider)ce.getSource();
                    if(secondPanel != null) {
                        secondPanel.setZoomFactor((double)source.getValue());
                        zoomLabel.setText("Zoom = " + source.getValue()/100.0);
            String id = "<html><nobr>show label</nobr><br><center>locations";
            JCheckBox check = new JCheckBox(id, secondPanel.showLocations);
            check.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    secondPanel.toggleShowLocations();
            gbc.weighty = 1.0;
            gbc.fill = GridBagConstraints.NONE;
            btnPanel.add(check, gbc);
            add(btnPanel, BorderLayout.EAST);
            pack();
        public JPanel getSecondPanel() {
            if(secondPanel == null) {
                secondPanel = new BackPanel3("images/cougar.jpg", 850, 1100);
                secondPanel.setStart(false);
            return secondPanel;
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new PP3();
    class BackPanel3 extends JPanel implements MouseListener,
                                               MouseMotionListener{
        String imgPath = null;
        BufferedImage image;
        private int width = 0;
        private int height = 0;
        private double zoomFactor = 1.0;
        private boolean start = false;
        private boolean same = false;
        Cursor hourglassCursor = new Cursor(Cursor.MOVE_CURSOR);
        // choose a declaration according to your java version
        List<JLabel> labels;     // declaration for j2se 1.5+
    //    List labels;           // j2se 1.4-
        JLabel lastSelected;
        boolean showLocations;
        JLabel selectedLabel;
        boolean dragging;
        Point offset;
        int count = 0;
        private static String SELECTED = "selected";
        public BackPanel3(String path, int width, int height){
            setLayout(null);
            this.width = width;
            this.height = height;
            setPreferredSize(new Dimension(width,height));
            addMouseListener(this);
            addMouseMotionListener(this);
            // chose an instantiation according to your java version
            labels = new ArrayList<JLabel>();    // j2se 1.5+
    //        labels = new ArrayList();          // j2se 1.4-
            lastSelected = new JLabel();
            lastSelected.putClientProperty(SELECTED, Boolean.FALSE);
            showLocations = true;
            dragging = false;
            offset = new Point();
            this.imgPath = path;
            setImage();
        public void setImage(){
            try{
                image = getImage(imgPath);
            }catch(Exception e){
                System.out.println(" (init) ERROR: " + e);
                e.printStackTrace();
        public void setStart(boolean flag){
            start = flag;
        public void setZoomFactor(double zoom){
            zoomFactor = (zoom/100);
            setPreferredSize(new Dimension((int)(850*zoomFactor), (int)(1100*zoomFactor)));
            repaint();
            revalidate();
        public double getZoomFactor(){
            return zoomFactor;
        public void toggleShowLocations() {
            showLocations = !showLocations;
            repaint();
        public void mouseClicked(MouseEvent e) {
            if(start){
                JLabel msgLabel = new JLabel("Test " + count++);
                this.add(msgLabel);
                Dimension d = msgLabel.getPreferredSize();
                msgLabel.setBounds(e.getX(), e.getY(), d.width, d.height);
                labels.add(msgLabel);
                msgLabel.putClientProperty(SELECTED, Boolean.FALSE);
                return;
        public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            for(int j = 0; j < labels.size(); j++) {
                JLabel label = (JLabel)labels.get(j);
                Rectangle bounds = label.getBounds();
                AffineTransform at =
                    AffineTransform.getScaleInstance(zoomFactor, zoomFactor);
                Shape xs = at.createTransformedShape(bounds);
                if(xs.contains(p)) {
                    selectedLabel = label;
                    Rectangle r = xs.getBounds();
                    offset.x = p.x - r.x;
                    offset.y = p.y - r.y;
                    dragging = true;
                    break;
        public void mouseReleased(MouseEvent e) {
            dragging = false;
        public void mouseDragged(MouseEvent me){
            if(dragging) {
                Rectangle bounds = selectedLabel.getBounds();
                AffineTransform at =
                    AffineTransform.getScaleInstance(1.0/zoomFactor, 1.0/zoomFactor);
                Point2D p = at.transform(me.getPoint(), null);
                int x = (int)(p.getX() - offset.x);
                int y = (int)(p.getY() - offset.y);
                selectedLabel.setLocation(x, y);
                repaint();
        public void mouseMoved(MouseEvent me){
            if(labels.size() == 0)
                return;
            Point p = me.getPoint();
            boolean hovering = false;
            boolean selectionChanged = false;
            for(int j = 0; j < labels.size(); j++) {
                final JLabel label = (JLabel)labels.get(j);
                Rectangle r = label.getBounds();
                AffineTransform at =
                    AffineTransform.getScaleInstance(zoomFactor, zoomFactor);
                Shape scaledBounds = at.createTransformedShape(r);
                if(scaledBounds.contains(p)) {
                    hovering = true;
                    if(!((Boolean)label.getClientProperty(SELECTED)).booleanValue()) {
                        label.putClientProperty("selected", Boolean.TRUE);
                        setCursor(hourglassCursor);
                        if(lastSelected != label)  // for only one JLabel
                            lastSelected.putClientProperty(SELECTED, Boolean.FALSE);
                        lastSelected = label;
                        selectionChanged = true;
                        break;
            // reset lastSelected when there is no selection/hovering
            if(!hovering &&
                ((Boolean)lastSelected.getClientProperty(SELECTED)).booleanValue()) {
                lastSelected.putClientProperty(SELECTED, Boolean.FALSE);
                setCursor(Cursor.getDefaultCursor());
                selectionChanged = true;
            if(selectionChanged)
                repaint();
        public void mouseEntered(MouseEvent e) { }
        public void mouseExited(MouseEvent e) { }
        protected void paintComponent(Graphics g){
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.scale(zoomFactor, zoomFactor);
            g2.drawImage(image, 0, 0, this);
            if(showLocations) {
                // show bounds of the actual JLabel children
                // components as they exist on this component
                AffineTransform at = AffineTransform.getScaleInstance(1.0/zoomFactor,
                                                                      1.0/zoomFactor);
                g2.setPaint(Color.blue);
                Component[] c = getComponents();
                for(int j = 0; j < c.length; j++)
                    g2.draw(at.createTransformedShape(c[j].getBounds()));
            // show selected label
            g2.setPaint(Color.red);
            for(int j = 0; j < labels.size(); j++) {
                JLabel label = (JLabel)labels.get(j);
                if(((Boolean)label.getClientProperty("selected")).booleanValue()) {
                    g2.draw(label.getBounds());
                    break;
        protected BufferedImage getImage(String path){
            try{
                URL imgURL = BackPanel3.class.getResource(path);
                if (imgURL == null &&
                       (path.indexOf(":\\") > 0 || path.indexOf(":/") > 0))
                    imgURL = new URL("file:///"+path);
                return getImage(imgURL);
            }catch(MalformedURLException mue){
                System.out.println("error "+mue);
            return null;
        protected BufferedImage getImage(URL url){
            try{
                if (url != null) {
                    BufferedImage source = ImageIO.read(url);
                    double xScale = (double)width / source.getWidth();
                    double yScale = (double)height / source.getHeight();
                    double scale = Math.min(xScale, yScale);
                    int w = (int)(scale*source.getWidth());
                    int h = (int)(scale*source.getHeight());
                    BufferedImage scaled = new BufferedImage(w, h, source.getType());
                    Graphics2D g2 = scaled.createGraphics();
                    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                        RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                    // scales faster than getScaledInstance
                    AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
                    g2.drawRenderedImage(source, at);
                    g2.dispose();
                    return scaled;
                }else{
                    return null;
            }catch(IOException ioe){
                System.out.println("read error "+ioe);
                return null;
    }

  • Problem with JPanel in a JScrollPane

    Hi all,
    I am devloping an application where in i insert the JPanel's object in the JScrollPane object. Intitially the size of the JPanel's object is more than the size of the JScrollPane object.At this point fo time i can drag the nob of the scrollpane to the extent of the size of the JPanel's object. Now When i move the mouse behond the size of the JPanel i am increasing the size of the JPanel's object but i cant move the nob of the scrollpane object behond the original limit.
    For example : when you open a notepad there will be scrollbar without the nob if you keep on pressing the enter key the size of the text area increases and we can see the scroll bar now. I what the similar functionality but
    instead of TextArea i need the panel.
    If any of you have solved this problem or know the solution please do inform. I need to solve this problem very urgently. Please do help me out.
    Thanks in Advance.
    regards
    Ravi

    Hi all,
    I got the solution.we need to revalidate the panel object.
    i.e JPanel.revalidate()
    regards
    Ravi Kumar

  • Problem with JPanel after rotation

    Hi,
    I am developing a graphics editor like mspaint. I have JPanel as my drawing canvas. now the problem is when I rotate the canvas, co-ordinates on the canvas are also getting rotate with it. for example if top-left corner is (0,0) initially then after rotating it 90 degree top-right corner becomes (0,0) and same for all the points on the canvas.
    the code i m using for rotation is
    contentPanel = new JPanel(){
    @Override
    protected void paintComponent(Graphics g) {                       
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    Rectangle rect=g2.getClipBounds();
    if(rotation!=0){
    double angle = rotation * Math.PI/2;
    g2.rotate(angle,getWidth()/2,getHeight()/2);
    rect=g2.getClipBounds();
    setPreferredSize(new Dimension(rect.width,rect.height));
    super.paintComponent(g);
    revalidate();
    };

    Whats your question?
    If you rotate it, of course the points will rotate, they have to.

  • Problem with JPanel on Mac

    Hi,
    I have a Jpanel with BorderLayout which has two components. First one is a JScrollpane which sits at CENTER and another is JEditorPane which sits at south. JScrollPane itself is over a JEditorPane ..... PROBLEM is I can't see the component sitting at SOUTH, any focus???

    Hi,
    I haven't seen this before.  Is it possible to get some sample code that illustrates the problem?  Feel free to email me at [email protected] (please remove any attachment extension) and I'll take a look.
    Moving discussion to the Problems & Bugs forum.
    Thanks,
    Chris

  • Problem with JPanel's mouse listener!

    I am developing a Windows Explorer-like program. I have an JPanel and added JLabels to that panel to reprensent the folders. I think, I kind of have to add mouse listener to JPanel to interact with mouse clicks, gaining and losing focus of JLabels etc. instead of adding every JLabel to mouse listener. So when I added to JPanel a mouse listener, it didn't work how I had expected. When I clicked on labels mouse click events didn't fire but when I clicked somewhere else in the panel it did fire. Is this a bug or am I using mouse listener incorrectly??
    Thank for advance :)
    Here is my JPanel's mouse listener ->
    public void mouseClicked(MouseEvent e) {
    int x = e.getX();
    int y = e.getY();
    System.out.println("Mouse Clicked");
    Component c = this.getComponentAt(x,y);
    if(c instanceof JLabel){
    JLabel label = (JLabel) c;
    label.setBackground(Color.LIGHT_GRAY);
    }

    My main problem is as in windows explorer (if CTRL or SHIFT not pressed) there is only one selected folder (in my case JLabel) and transfering "selection" to one label to another might need lots of extra code.. So I thought using JPanel's mouse listener can overcome this handling problem. But if you are saying, this is the way it has to be done, then so be it :D :D

  • Problem with JPanel.updateUI()

    Hello,
    i have a problem with updateUI(), here's a simple example what's wrong. just compile and run the following piece of code and look what happens after 2 seconds: the left panel will be decrease its width after calling updateUI(), but why? is it a bug of updateUI() or is it my fault?
    import java.awt.*;
    import javax.swing.*;
    public class Test extends JPanel
            private JList m_list;
            private DefaultListModel m_listModel;
            private JPanel m_buttons;
            public static GridBagConstraints creategbc (int x, int y, int w, int h, int wx, int wy, int f)
                    GridBagConstraints gbc = new GridBagConstraints();
                    gbc.gridx = x;
                    gbc.gridy = y;
                    gbc.gridwidth = w;
                    gbc.gridheight = h;
                    gbc.weightx = wx;
                    gbc.weighty = wy;
                    gbc.fill = f;
                    gbc.insets = new Insets(5, 5, 5, 5); // kleinen Rahmen ziehen
                    return gbc;
            public Test ()
                    GridBagLayout gbl = new GridBagLayout();
                    setLayout(gbl);
                    GridBagConstraints gbc;
                    initButtons();
                    gbc = creategbc(0, 0, 1, 1, 20, 100, GridBagConstraints.NONE);
                    gbc.anchor = GridBagConstraints.NORTH;
                    gbl.setConstraints(m_buttons, gbc);
                    add(m_buttons);
                    initList();
                    JScrollPane sp = new JScrollPane(m_list);
                    gbc = creategbc(1, 0, 1, 1, 100, 100, GridBagConstraints.BOTH);
                    gbl.setConstraints(sp, gbc);
                    add(sp);
            public void addItem (String item)
                    m_listModel.addElement(item);
            public void initList ()
                    m_listModel = new DefaultListModel();
                    m_list = new JList(m_listModel);
            public void initButtons ()
                    m_buttons = new JPanel();
                    m_buttons.setLayout(new GridLayout(4, 1, 0, 20));
                    m_buttons.add(new JButton("Neu"));
                    m_buttons.add(new JButton("Bearbeiten"));
                    m_buttons.add(new JButton("L�schen"));
                    m_buttons.add(new JButton("Abfrage"));
            public static void main (String[] args)
                    JFrame f = new JFrame();
                    Test t = new Test();
                    f.setContentPane(t);
                    f.setSize(600, 450);
                    f.setVisible(true);
                    try
                            Thread.sleep(2000);
                    catch (Exception e)
                    t.addItem("Hallo");
                    t.updateUI();

    Hello,
    i have a problem with updateUI(), here's a simple
    example what's wrong. just compile and run the
    following piece of code and look what happens after 2
    seconds: the left panel will be decrease its width
    after calling updateUI(), but why? is it a bug of
    updateUI() or is it my fault?updateUI() its called when the L&F is changed, there is
    rarely a case when you need to call updateUI().
    Why do you call updateUI() if you remove the call to updateUI()
    everything will work OK.
    merry xmas

  • Problem with JPanel, CardLayout and Applets

    Hello All,
    I have a JPanel with a CardLayout as layout manager. In this JPanel i'm gonna show a few applets.
    My problem is when i'm showing an applet for second time and try to click a button it does nothing... I think the action method is not called again...
    How can i solve this?
    Thanks in advance ; )

    Here is a few parts of my code...
    public class InitAll{
    JPanel cards = new JPanel( new CardLayout() );
    JComboBox selector = new JComboBox();
    Object objetosV[][] ={
         {"Ventas",venta.class},
         {"Compras",compras.class}, //These are applets.
         {"Traspasos",traspasos.class},
         {"Facturas",factura.class},
    public void load( Applet app ){
    cards.removeAll();
    selector.removeAll();
    cards.add( "Entrada", app );
    selector.addItem( "Entrada" );
    for ( int i=0; i < objetosV.length; i++ ){
         selector.addItem( (String)objetosV[0] );
         Applet temp=createPanel( ( Class ) objetosV[i][1] );
         temp.setSize( 800,750 );
         cards.add( ( String ) objetosV[i][0], temp );
    public void itemStateChanged(ItemEvent e) {
    ((CardLayout)cards.getLayout()).show(cards, selector.getSelectedItem().toString() );
    Applet tmp = (Applet)cards.getComponent(selector.getSelectedIndex() );
    tmp.start();
    After i show for second time an Applet and select a button from it. the button does nothing...
    Thanks...

  • Problem with jpanel and revalidate()

    i have made a calendar. on click on jlabel you can switch month/year and there is the problem. for example when i switch from february to march and back again, then the panel don�t update. but why?
    i hope you understand what i mean.(I am german and can�t englisch)
    here is the code(i have mixed german in english in the code, i hope you understand even so.)
    package organizer.gui;
    import organizer.*;
    import java.text.SimpleDateFormat;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Kalender extends JPanel {
    private Calendar calendar;
    private JPanel days;
    private JLabel monthLabel;
    private SimpleDateFormat monthFormat = new SimpleDateFormat("dd MMM yyyy");
    private TerminManager manger;
    public Kalender(TerminManager manager) {
       super();
       this.manger=manager;
       this.calendar=Calendar.getInstance();
       this.initializeJPanel();
       this.updatePanel();
    protected void updatePanel() {
       monthLabel.setText(monthFormat.format(calendar.getTime()));
       if(days!=null) {
         days.removeAll();
       }else {
         days = new JPanel(new GridLayout(0, 7));
       days.setOpaque(true);
       for (int i = 1; i <=7; i++) {
         int dayInt = ( (i + 1) == 8) ? 1 : i + 1;
         JLabel label = new JLabel();
         label.setHorizontalAlignment(JLabel.CENTER);
         if (dayInt == Calendar.SUNDAY) {
           label.setText("Son");
         else if (dayInt == Calendar.MONDAY) {
           label.setText("Mon");
         else if (dayInt == Calendar.TUESDAY) {
           label.setText("Die");
         else if (dayInt == Calendar.WEDNESDAY) {
           label.setText("Mit");
         else if (dayInt == Calendar.THURSDAY) {
           label.setText("Don");
         else if (dayInt == Calendar.FRIDAY) {
           label.setText("Fre");
         else if (dayInt == Calendar.SATURDAY) {
           label.setText("Sam");
         days.add(label);
       Calendar setupCalendar = (Calendar) calendar.clone();
       setupCalendar.set(Calendar.DAY_OF_MONTH, 1);
       int firstday = setupCalendar.get(Calendar.DAY_OF_WEEK);
       for (int i = 1; i < (firstday - 1); i++) {
         days.add(new JLabel(""));
       for (int i = 1; i <=setupCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
         int day = setupCalendar.get(Calendar.DAY_OF_MONTH);
         final Date d = setupCalendar.getTime();
         final JLabel label = new JLabel(String.valueOf(day));
         label.setOpaque(true);
         if(this.manger.isTerminAtDay(d)) {
           String s="<html><center>" + day + "<br>";
           if(this.manger.isBirthdayAtDay(d)) {
             s+="Geburtstag<br>";
           if(this.manger.isOtherTerminAtDay(d)) {
             s+="Termin";
           label.setText(s);
           label.addMouseListener(new MouseListener() {
              * mouseClicked
              * @param e MouseEvent
             public void mouseClicked(MouseEvent e) {
               Termin[] t = Kalender.this.manger.getTermineAtDay(d);
               if (t.length == 1) {
                 new TerminDialog(null, t[0]);
               else {
                 new TerminAuswahlDialog(null, t, d);
              * mouseEntered
              * @param e MouseEvent
             public void mouseEntered(MouseEvent e) {
              * mouseExited
              * @param e MouseEvent
             public void mouseExited(MouseEvent e) {
              * mousePressed
              * @param e MouseEvent
             public void mousePressed(MouseEvent e) {
              * mouseReleased
              * @param e MouseEvent
             public void mouseReleased(MouseEvent e) {
         final Color background=label.getBackground();
         final Color foreground=label.getForeground();
         label.setHorizontalAlignment(JLabel.CENTER);
         label.addMouseListener(new MouseAdapter() {
           public void mouseEntered(MouseEvent e) {
             label.setBackground(Color.BLUE);
             label.setForeground(Color.RED);
           public void mouseExited(MouseEvent e) {
             label.setBackground(background);
             label.setForeground(foreground);
         days.add(label);
         setupCalendar.roll(Calendar.DAY_OF_MONTH,true);
       this.add(days, BorderLayout.CENTER);
       this.revalidate();
    private JLabel createUpdateButton(final int field,final int amount) {
       final JLabel label = new JLabel();
       final Border selectedBorder = new EtchedBorder();
       final Border unselectedBorder = new EmptyBorder(selectedBorder
           .getBorderInsets(new JLabel()));
       label.setBorder(unselectedBorder);
       label.addMouseListener(new MouseAdapter() {
         public void mouseReleased(MouseEvent e) {
           calendar.add(field, amount);
           Kalender.this.updatePanel();
         public void mouseEntered(MouseEvent e) {
           label.setBorder(selectedBorder);
         public void mouseExited(MouseEvent e) {
           label.setBorder(unselectedBorder);
       return label;
    private void initializeJPanel() {
       JPanel header = new JPanel();
       JLabel label;
       label = this.createUpdateButton(Calendar.YEAR, -1);
       label.setText("<<");
       header.add(label);
       label = this.createUpdateButton(Calendar.MONTH, -1);
       label.setText("<");
       header.add(label);
       monthLabel=new JLabel("");
       header.add(monthLabel);
       label = this.createUpdateButton(Calendar.MONTH, 1);
       label.setText(">");
       header.add(label);
       label = this.createUpdateButton(Calendar.YEAR, 1);
       label.setText(">>");
       header.add(label);
       this.setLayout(new BorderLayout());
       this.add(header, BorderLayout.NORTH);
    }

    I got you code to compile and run and made a single change to get it to work; adding a call to repaint at the end of the updatePanel method.
            this.add(days, BorderLayout.CENTER);
            this.revalidate();
            repaint();
        }Whenever you change the size of a containers components or add/remove components you must ask the container to run through its component hierarchy and check the size requirements of all its children and lay them out again, ie, do a new layout. The JComponent method for this isrevalidate. If you are working in the AWT you must use the Component/(overridden in)Container method validate, sometimes preceded by a call to the invalidate method. Some people prefer the validate method over revalidate. These are methods used to update guis by asking for a renewed layout. For economy you can call one (sometimes with invalidate, but rarely) of these methods on the smallest component/container that includes all the containers needing the renewed layout, ie, keep the action as localized as possible.
    When the rendering of components has changed, things like colors, borders and text, we need to ask the components to repaint themselves. The easy way to do this is to call repaint on the gui. For economy you can call repaint on the smallest component that contains all the components needing repainting. Some classes like those in the JTextComponent group have their own internal repainting calls so they will repaint themselves when changes are made.
    In making guis, especially elaborate ones, it seems to take some playful experimentation to find out what is needed to get what you want. Sometimes it is a call to revalidate, sometimes a call to repaint, sometimes both. You just have to experiment.

  • Problem with jpanel and image

    i have a jinternalframe with gridbaglayout which has several jpanels. one of the jpanels has to display an image.
    i have searched through the forum and i have made a method to draw the image,
    but the problem is that when i added to the jpanel the last (jpanel) gets much bigger and as a result to break down the layout.
    any help is appreciated!

    i have searched through the forum and i have made a method to draw the image,Just add the image to a JLabel.
    when i added to the jpanel the last (jpanel) gets much bigger[url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use Layout Managers

Maybe you are looking for

  • Photoshop Elements 6 Uninstall & Reinstall

    In 2007 I bought Adobe Photoshop Elements 6.  Earlier this year a pop-up message told me one of my files was missing and that I should reinstall the program.  When I opened my "Add or Remove programs" tool, there was no listing for Photoshop elements

  • Exporting the reports in RoboHelp 7

    Hi, Can we export all the reports in the X7 to a single file. I can see the option to only eport one report at a time. Also is there any command line or script to export the reports to a text file.

  • How to Delete Unwanted Aperture Plug-ins

    I have installed a trial version of a plug-in that I don't want to use. How do I uninstall a plug-in? Thanks

  • All vm's in hyper-v 2012 core cannot initialize

    Hi, All vm's in hyper-v 2012 core cannot initialize. there is ram and space in drive. Tried to run windows update and restarted hyper-V. any suggestions? Thanks

  • How do I change media file size?

    I am trying to move some movies onto a portable hd but the files are too big. So I'm cutting them up into smaller iMovie HD files by using "split video at playhead" but when I do that, both files are still the same size. So I still can't move them. I