Mouse clicks in a GridLayout JPanel

Hi. I have a JPanel set as a GridLayout (3 columns, infinite rows) I am populating this panel with thumbnail images and need to be able to identify when a user clicks on a thumbnail image and respons accordingly. The thumbnail images are not the same size as the grid squares. How can i alter the mouseclicked event to act in this way?

Put the Images in a Collection and assign anonymous Listeners to them:
GridLayout gl = new GridLayout(3);
JPanel jp = new JPanel();
jp.setLayout(gl);
String[] imageNames = new String[50];
Image[] images = new Image[imageNames.length];
ImageIcon buttonIcons = new ImageIcon[imageNames.length];
JButton buttons = new JButton[imageNames.length];
for ( int i = 0; i < imageNames.length; i++ ) {
  URL url = getClass().getResource( imageName[i] );
  images[i] = Toolkit.getDefaultToolkit().getImage( url );
  buttonIcons[i] = new ImageIcon( images[i] );
  buttons[i] = new JButton(buttonIcons);
buttons[i].setBorderPainted(false);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println("You clicked on "+imageName[i]);
jp.add(buttons[i]);

Similar Messages

  • Multiple JButtons inside JTable cell - Dispatch mouse clicks

    Hi.
    I know this subject has already some discussions on the forum, but I can't seem to find anything that solves my problem.
    In my application, every JTable cell is a JPanel, that using a GridLayout, places vertically several JPanel's witch using an Overlay layout contains a JLabel and a JButton.
    As you can see, its a fairly complex cell...
    Unfortunately, because I use several JButtons in several locations inside a JTable cell, sometimes I can't get the mouse clicks to make through.
    This is my Table custom renderer:
    public class TimeTableRenderer implements TableCellRenderer {
         Border unselectedBorder = null;
         Border selectedBorder = null;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                   boolean hasFocus, int row, int column) {
              if (value instanceof BlocoGrid) {
                   if (isSelected) {
                        if (selectedBorder == null)
                             selectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getSelectionBackground());
                        ((BlocoGrid) value).setBorder(selectedBorder);
                   } else {
                        if (unselectedBorder == null)
                             unselectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getBackground());
                        ((BlocoGrid) value).setBorder(unselectedBorder);
              return (Component) value;
    }and this is my custom editor (so clicks can get passed on):
    public class TimeTableEditor extends AbstractCellEditor implements TableCellEditor {
         private TimeTableRenderer render = null;
         public TimeTableEditor() {
              render = new TimeTableRenderer();
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
             if (value instanceof BlocoGrid) {
                  if (((BlocoGrid) value).barras.size() > 0) {
                       return render.getTableCellRendererComponent(table, value, isSelected, true, row, column);
             return null;
        public Object getCellEditorValue() {
            return null;
    }As you can see, both the renderer and editor return the same component that cames from the JTable model (all table values (components) only get instantiated once, so the same component is passed on to the renderer and editor).
    Is this the most correct way to get clicks to the cell component?
    Please check the screenshot below to see how the JButtons get placed inside the cell:
    http://img141.imageshack.us/my.php?image=calendarxo9.jpg
    If you need more info, please say so.
    Thanks.

    My mistake... It worked fine. The cell span code was malfunctioning. Thanks anyway.

  • Mouse clicks not detected on JTabbedPane

    Hi all,
    I have a JPanel placed inside a JTabbedPane. I want to double-click on the JPanel and bring up a JDialog. This works fine if the JPanel is not in a JTabbedPane, but if it is on a JTabbedPane, then the mouse clicks are not detected. I'd greatly appreciate any help you can give me.

    Here is a sample program that seems to work:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    public class TestInternalFrame extends JFrame
         public TestInternalFrame()
              JDesktopPane desktop = new JDesktopPane();
              setContentPane( desktop );
              JInternalFrame internal = new JInternalFrame( "Internal Frame" );
              desktop.add( internal );
              internal.setLocation( 50, 50 );
              internal.setSize( 300, 300 );
              internal.setVisible( true );
              JTabbedPane tabbedPane = new JTabbedPane();
              internal.getContentPane().add(tabbedPane);
              tabbedPane.setPreferredSize( new Dimension(300, 200) );
              JPanel panel = new JPanel();
              tabbedPane.add( "Empty Panel", panel );
              panel.addMouseListener( new MouseAdapter()
                   public void mouseClicked(MouseEvent e)
                        System.out.println(e.getClickCount());
         public static void main(String args[])
    TestInternalFrame frame = new TestInternalFrame();
    frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
    frame.setSize(400, 400);
    frame.setVisible(true);

  • Mouse clicks inside image in applet

    How can I respond to mouse clicks inside particular regions in an image loaded as part of an applet in a browser? ie, I want to send these clicks onto the server for the server to handle it and the server should change the image according to the mouse clicks.
    Thanks,

    /*  <applet code="ImageMouse" width="400" height="400"></applet>
    *  use: >appletviewer ImageMouse.java
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class ImageMouse extends JApplet
        JLabel label;
        public void init()
            ImageMousePanel panel = new ImageMousePanel();
            ImageMouser mouser = new ImageMouser(panel, this);
            panel.addMouseMotionListener(mouser);
            getContentPane().add(panel);
            getContentPane().add(getLabel(), "South");
        private JLabel getLabel()
            label = new JLabel(" ");
            label.setHorizontalAlignment(JLabel.CENTER);
            label.setBorder(BorderFactory.createTitledBorder("image coordinates"));
            Dimension d = label.getPreferredSize();
            d.height = 35;
            label.setPreferredSize(d);
            return label;
        public static void main(String[] args)
            JApplet applet = new ImageMouse();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(applet);
            f.setSize(400,400);
            f.setLocation(200,200);
            applet.init();
            f.setVisible(true);
    class ImageMousePanel extends JPanel
        BufferedImage image;
        Rectangle r;
        public ImageMousePanel()
            loadImage();
            r = new Rectangle(getPreferredSize());
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth();
            int h = getHeight();
            int imageWidth = image.getWidth();
            int imageHeight = image.getHeight();
            r.x = (w - imageWidth)/2;
            r.y = (h - imageHeight)/2;
            g2.drawImage(image, r.x, r.y, this);
            //g2.setPaint(Color.red);
            //g2.draw(r);
        public Dimension getPreferredSize()
            return new Dimension(image.getWidth(), image.getHeight());
        private void loadImage()
            String s = "images/greathornedowl.jpg";
            try
                URL url = getClass().getResource(s);
                image = ImageIO.read(url);
            catch(MalformedURLException mue)
                System.err.println("url: " + mue.getMessage());
            catch(IOException ioe)
                System.err.println("read: " + ioe.getMessage());
    class ImageMouser extends MouseMotionAdapter
        ImageMousePanel panel;
        ImageMouse applet;
        boolean outsideImage;
        public ImageMouser(ImageMousePanel imp, ImageMouse applet)
            panel = imp;
            this.applet = applet;
            outsideImage = true;
        public void mouseMoved(MouseEvent e)
            Point p = e.getPoint();
            if(panel.r.contains(p))
                int x = p.x - panel.r.x;
                int y = p.y - panel.r.y;
                applet.label.setText("x = " + x + "  y = " + y);
                if(outsideImage)
                    outsideImage = false;
            else if(!outsideImage)
                outsideImage = true;
                applet.label.setText("outside image");
    }

  • Multiple Buttons in JTable Headers:  Listening for Mouse Clicks

    I am writing a table which has table headers that contain multiple buttons. For the header cells, I am using a custom cell renderer which extends JPanel. A JLabel and JButtons are added to the JPanel.
    Unfortunately, the buttons do not do anything. (Clicking in the area of a button doesn't appear to have any effect; the button doesn't appear to be pressed.)
    Looking through the archives, I read a suggestion that the way to solve this problem is to listen for mouse clicks on the table header and then determine whether the mouse clicks fall in the area of the button. However, I cannot seem to get coordinates for the button that match the coordinates I see for mouse clicks.
    The coordinates for mouse clicks seem to be relative to the top left corner of the table header (which would match the specification for mouse listeners). I haven't figured out how to get corresponding coordinates for the button. The coordinates returned by JButton.getBounds() seem to be relative to the top left corner of the panel. I hoped I could just add those to the coordinates for the panel to get coordinates relative to the table header, but JPanel.getBounds() gives me negative numbers for x and y (?!?). JPanel.getLocation() gives me the same negative numbers. When I tried JPanel.getLocationOnScreen(), I get an IllegalComponentStateException:
    Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    Can someone tell me how to get coordinates for the button on the JTableHeader? Or is there an easier way to do this (some way to make the buttons actually work so I can just use an ActionListener like I normally would)?
    Here is relevant code:
    public class MyTableHeaderRenderer extends JPanel implements TableCellRenderer {
    public MyTableHeaderRenderer() {
      setOpaque(true);
      // ... set colors...
      setBorder(UIManager.getBorder("TableHeader.cellBorder"));
      setLayout(new FlowLayout(FlowLayout.LEADING));
      setAlignmentY(Component.CENTER_ALIGNMENT);
    public Component getTableCellRendererComponent(JTable table,
                                                     Object value,
                                                     boolean isSelected,
                                                     boolean hasFocus,
                                                     int row,
                                                     int column){
      if (table != null){
        removeAll();
        String valueString = (value == null) ? "" : value.toString();
        add(new JLabel(valueString));
        Insets zeroInsets = new Insets(0, 0, 0, 0);
        final JButton sortAscendingButton = new JButton("1");
        sortAscendingButton.setMargin(zeroInsets);
        table.getTableHeader().addMouseListener(new MouseAdapter(){
          public void mouseClicked(MouseEvent e) {
            Rectangle buttonBounds = sortAscendingButton.getBounds();
            Rectangle panelBounds = MyTableHeaderRenderer.this.getBounds();
            System.out.println(Revising based on (" + panelBounds.x + ", "
                               + panelBounds.y + ")...");
            buttonBounds.translate(panelBounds.x, panelBounds.y);
            if (buttonBounds.contains(e.getX(), e.getY())){  // The click was on this button.
              System.out.println("Calling sortAscending...");
              ((MyTableModel) table.getModel()).sortAscending(column);
            else{
              System.out.println("(" + e.getX() + ", " + e.getY() + ") is not within "
                                 + sortAscendingButton.getBounds() + " [ revised to " + buttonBounds + "].");
        sortAscendingButton.setEnabled(true);
        add(sortAscendingButton);
        JButton button2 = new JButton("2");
        button2.setMargin(zeroInsets);
        add(button2);
        //etc
      return this;
    }

    I found a solution to this: It's the getHeaderRect method in class JTableHeader.
    table.getTableHeader().addMouseListener(new MouseAdapter(){
      public void mouseClicked(MouseEvent e) {
        Rectangle panelBounds = table.getTableHeader().getHeaderRect(column);
        Rectangle buttonBounds = sortAscendingButton.getBounds();
        buttonBounds.translate(panelBounds.x, panelBounds.y);
        if (buttonBounds.contains(e.getX(), e.getY()) && processedEvents.add(e)){  // The click was on this button.
          ((MyTableModel) table.getModel()).sortAscending(column);
    });

  • Detecting mouse click on a line

    I'm learning making GUI apps in Java.
    Here is my problem. Suppose I draw a line on a JPanel. If I want to find out if the line is clicked or not, what is the best way to do it?
    I did some research, looked at API. If I suppose my line is Line2D, then since its a line it doesn't have an area, so its contains method always returns false (..from API). So i dig around some more and came up with the solution of getting the shape from the stroke and calling its contains method.
    This is a code for what i mean..
    private Line2D.Double testLine;
    //mouse clicked event
    public void mouseClicked(MouseEvent e) {
            int x = e.getX();
            int y = e.getY();
            BasicStroke stroke = new BasicStroke(4);
            Shape testShape = stroke.createStrokedShape(testLine);
            if(testShape.contains(x,y)){
                System.out.println("this will be printed if clicked on line");
        }Well, the above solution works fine.
    Is it the right way of doing it or is there a better way around for this?
    Any help will be appreciated.
    Thanks.

    When trying to test if a line was pressed I usually test if the distance between the mouse coordinates and the line is smaller than some constant (usually 5 pixels).
    For this you have to write your own code to calculate the distance between a point and a line.

  • Why does the ALT key disable mouse clicks on some machines?

    I have a drawing program, the main Window of which extends JFrame and contains a Canvas, which extends JPanel. The Canvas has a MouseAdapter, KeyAdapter and JMenuBar. It also has a Tools palette, which extends JDialog and has Buttons, which extend JToggleButtons.
    One button is called Zoom. After pressing this button, you can Zoom In and Zoom Out by clicking the mouse on a point of the illustration. It differs from pressing Ctrl Plus and Ctrl Minus, because the point where you click is kept in place, and only all the other points move.
    Zooming In is done by clicking the mouse and Zooming Out is done by pressing the ALT key and clicking the mouse. The Zooming In works on all computers, but for some strange reason, the Zooming Out doesn't work on all computers. The computer where it doesn't work, after pressing the ALT key and clicking the mouse, it does not recognize the mouse click, and never reaches the mousePressed method in my debugger.
    The computer where it doesn't work has the Windows XP Professional operating system. But some computers where it does work have the same operating system. The problem also does not depend on the keyboard or mouse, because I tried a different keyboard and mouse, and it still didn't work.
    I wonder if the reason why it doesn't work on some computers has to do with that the ALT key is also used differently (which might depend on the operating system)? Pressing the ALT key and clicking the mouse Zooms In a picture by keeping the point in place and only moving all the other points
    I do not want to use a different key, since one release of my program is a plugin for Photoshop, and Photoshop also uses the ALT key to achieve the same thing.
    Thanks for checking on this! I will appreciate your help!

    Ok, I did apply KeyBindings. Since the AnanyaCurves class extends JFrame, I couldn't apply KeyBindings there, but I could apply KeyBindings to my CurveCanvas class, which extends JPanel, which extends JComponent. However I still have my first two problems:
    1) After pressing the ALT key, clicking the mouse doesn't get recognized. You never reach the mousePressed method, where it's supposed to exit the program.
    2) After opening a menu, such as the Nothing menu by pressing ALT and N, pressing a key which is not an accelerator key of a menu doesn't get recognized, such as pressing the E key. You never reach the actionPerformed method of the exitF action, where it's supposed to exit the program.
    Here is my SSCCE with the KeyBindings:
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;
    import java.lang.reflect.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.plaf.*;
    public class AnanyaCurves extends JFrame
      CurveCanvas canvas;
      JMenuBar menuBar;
      Command quitCmd;
      JMenu fileMenu, nothingMenu;
      JMenuItem quitItem, nothingItem;
      boolean alt;
      public AnanyaCurves(Dimension windowSize)
        Font boldFont = new Font("Verdana", Font.BOLD, 12);
        Font plainFont = new Font("Verdana", Font.PLAIN, 12);
        Object top;
        Basics.ananyaCurves = this;
        alt = false;
        try
          UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
          SwingUtilities.updateComponentTreeUI(this);
        catch(Exception e)
        UIManager.put("MenuItem.acceleratorFont", new FontUIResource(UIManager.getFont("MenuItem.acceleratorFont").decode("Verdana-PLAIN-12")));
        Basics.ananyaCurves = this;
        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        setTitle("Ananya Curves");
        Dimension docSize = new Dimension(274, 121);
        canvas = new CurveCanvas(docSize);   
        menuBar = new JMenuBar();
        setJMenuBar(menuBar);
        fileMenu = new JMenu("File");
        fileMenu.setMnemonic('F');
        fileMenu.setFont(boldFont);
        quitCmd = new Command("quit", "ctrl Q");
        quitCmd.putValue(Action.NAME, "Quit");
        quitItem = new JMenuItem(quitCmd);
        quitItem.setFont(plainFont);
        fileMenu.add(quitItem);
        menuBar.add(fileMenu);
        //fileMenu.setVisible(false);
        /*JMenuBar hiddenMenuBar = new JMenuBar();
        hiddenMenuBar.add(fileMenu);
        getContentPane().add(hiddenMenuBar, BorderLayout.CENTER);
        getContentPane().add(new JPanel(), BorderLayout.CENTER);*/
        nothingMenu = new JMenu("Nothing");
        nothingMenu.setMnemonic('N');
        nothingMenu.setFont(boldFont);
        nothingItem = new JMenuItem("NoAction");
        nothingItem.setFont(plainFont);
        nothingMenu.add(nothingItem);
        menuBar.add(nothingMenu);
        addMouseListener(new MouseAdaption());
        addKeyListener(new KeyAdaption());
      public static void main(String[] args)
        Dimension windowSize = new Dimension(300, 200);
        AnanyaCurves ananyaCurves = new AnanyaCurves(windowSize);
        ananyaCurves.pack();
        ananyaCurves.setBounds(0, 0, windowSize.width, windowSize.height);
        ananyaCurves.setVisible(true);
        ananyaCurves.requestFocus();
      public void exit()
        this.dispose();
        System.exit(0);
      class MouseAdaption extends MouseAdapter
        public void mousePressed(MouseEvent e)
          if (AnanyaCurves.this.alt == true)
            AnanyaCurves.this.exit();
      class KeyAdaption extends KeyAdapter
        public void keyPressed(KeyEvent event)
          /*int keyCode = event.getKeyCode();
          if (keyCode == KeyEvent.VK_ALT)
            AnanyaCurves.this.alt = true;
          else if (keyCode == KeyEvent.VK_E)
            AnanyaCurves.this.exit();
        public void keyReleased(KeyEvent event)
          AnanyaCurves.this.alt = false;
    class Basics extends java.lang.Object
      public static AnanyaCurves ananyaCurves;
      public Basics()
    class Command extends AbstractAction
      String name; // the command name (not the menu item string)
      String accelerator;
      public Command(String name, String accelerator)
        super();
        this.name = name;
        if (accelerator != null && !accelerator.equals(""))
          this.accelerator = accelerator;
          KeyStroke k = KeyStroke.getKeyStroke(accelerator);
          putValue(Action.ACCELERATOR_KEY, k);
      public void quit()
        Basics.ananyaCurves.dispose();
        System.exit(0);
      public void actionPerformed(ActionEvent actionEvent)
        try
          Method f = getClass().getMethod(this.name, (Class[])null);
          f.invoke(this, (Object[])null);
        catch (NoSuchMethodException e)
        catch (InvocationTargetException e)
        catch (IllegalAccessException e)
    class CurveCanvas extends JPanel
      public CurveCanvas(Dimension docSize)
        super();
        Action altF = new AbstractAction()
          public void actionPerformed(ActionEvent e)
            Basics.ananyaCurves.alt = true;
        Action exitF = new AbstractAction()
          public void actionPerformed(ActionEvent e)
            Basics.ananyaCurves.exit();
        this.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ALT"), "alt");
        this.getActionMap().put("alt", altF);
        this.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("E"), "exit");
        this.getActionMap().put("exit", exitF);
    In the getInputMap method I was trying to use the condition WHEN_IN_FOCUSED_WINDOW, hoping that the bound key would be recognized, but it didn't work. And, by the way, I still used the KeyAdapter so that the alt attribute of AnanyaCurves can be set to false when the ALT key is released.
    I will appreciate your help very much! Thanks for your time!

  • Figuring out where a mouse click is under an image

    I want to create a JFrame (or JPanel) where the whole area is one big gif (or icon etc) and I want to make some areas of this panel react to mouse clicks and other areas display messages.
    There are two ways that I can think of doing this.
    The first is that I figure out the x and y coordinates of each area and check to see if each mouse click is within that area.
    The second way is to see if I can figure out how to put something like transparent JButtons over the areas that I want to accept mouse clicks (all the areas will be rectangular) and just do what JButtons do normally.
    The second way sounds easier but I don't know how to do that.
    Does anyone have opinions on which way I should do it?
    Thanks

    To me the first method sounds eaiser.
    A third possible idea? Add a bunch of JPanels to the frame and have split the image into several pieces that are painted by each JPanel. Then use a mouse listener to detect clicks. (Seems easier than trying to make JButton transparent and placing it at the correct point).

  • Detecting a mouse click on any (all) child components...

    Hey All,
    I am writing a number of compound GUI elements that i want to make focusable when you click any part of them. (i.e. a JTextArea inside a JScrollPane, coupled to a JTextField to provide input to the JTextArea).
    Is there an easy way to detect mouse clicks on child components of a JPanel?
    My current code is:
    m_oInputBox.addMouseListener(this);
    m_oOutputBox.addMouseListener(this);
    m_oScrollPane.getVerticalScrollBar().addMouseListener(this);
    This detects most of the mouse clicks, but not those on the buttons that form the scroll bar ends or the scroll bar slider when it is present.
    Any way tou can detect clicks on these too??
    Iso

    P.S. It does actually detect clicks on the scroll bar slider - just not onthe buttons that form the slider end caps (up/down).
    Iso

  • Mouse click in JTable

    Hi All,
    I want to force mouse click when right clicking on a JTable. I mean when the right click is done in the mouse, the left click should be forced. I have a JTable with some values in it. I want to select the particular column in the table when right click mouse action. How can I do it?
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class TableDemo extends JFrame
        private JTable table;
        private JScrollPane jsp;
        private JPanel jp;
        public TableDemo()
            initComponents();
        private void initComponents()
            jp = new JPanel();
            String columnNames[] = { "Column 1", "Column 2", "Column 3" };
            String dataValues[][] =
                { "12", "234", "67" },
                { "-123", "43", "853" },
                { "93", "89.2", "109" },
                { "279", "9033", "3092" }
            table = new JTable(dataValues, columnNames);
            jsp = new JScrollPane(table);
            jsp.setViewportView(table);
            jp.add(jsp);
            table.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent evt) {
                    if(evt.getButton() == 3) {
                        System.out.println("Right Click........");
                        // Mouse left click should be forced here to select the row.
                    if(evt.getButton() == 1) {
                        System.out.println("Mouse LEFT CLICK FORCED.....");
            getContentPane().add(jp);
            pack();
            setVisible(true);
        public static void main(String args[])
            new TableDemo();
    }

    There may be a better way, but you could just use java.awt.Robot to perform the left click. I've changed your code around a bit: it shouldn't extend JFrame as it is in no way a special type of JFrame. And a GUI should always be launched on the EDT.**import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ForceLeftClick {
       private JTable table;
       private void makeUI() {
          String columnNames[] = {"Column 1", "Column 2", "Column 3"};
          String dataValues[][] = {
             {"12", "234", "67"},
             {"-123", "43", "853"},
             {"93", "89.2", "109"},
             {"279", "9033", "3092"}
          table = new JTable(dataValues, columnNames);
          JScrollPane scrollPane = new JScrollPane(table);
          scrollPane.setViewportView(table);
          table.addMouseListener(new MouseAdapter() {
             @Override
             public void mouseClicked(final MouseEvent evt) {
                if (evt.getButton() == MouseEvent.BUTTON3) {
                   System.out.println("Right Click........");
                   // Mouse left click should be forced here to select the row.
                   //final Point point = evt.getLocationOnScreen();
                   SwingUtilities.invokeLater(new Runnable() {
                      @Override
                      public void run() {
                         try {
                            Robot robot = new Robot();
                            //robot.mouseMove(point.x, point.y);
                            robot.mousePress(InputEvent.BUTTON1_MASK);
                            robot.mouseRelease(InputEvent.BUTTON1_MASK);
                         } catch (AWTException ex) {
                            ex.printStackTrace();
                if (evt.getButton() == MouseEvent.BUTTON1) {
                   System.out.println("Mouse LEFT CLICK FORCED.....");
          JFrame frame = new JFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.add(scrollPane);
          frame.pack();
          frame.setVisible(true);
       public static void main(String args[]) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new ForceLeftClick().makeUI();
    }If there are issues of Robot clicking in the wrong location because the user moves the mouse before the robot does its stuff (not likely, but..), uncomment the two commented lines.
    db
    **edit And always use constant fields by name, not magic numbers. MouseEvent.BUTTON1, not 1. That keeps your code implementation independent.
    Edited by: Darryl.Burke

  • Mouse clicking in blank area destroying all button display

    Hello,
    I have created one small application using JFrame, Jbutton and Panel. whenever i click on root button it create one more button etc etc.. and display properly but when i click on blank page it on the panel it destroy the display and not show more created button.. i have tried with panel.repaint() but it is not working... code goes like...
    JFrame frame = new JFrame("MouseEventDemo");
    JButton button = new JButton("Test");
    panel.add(button);
    applic.getContentPane().add(panel);
    frame.pack();
    frame.setSize(600,400);
    frame.setVisible(true);
    // call subclass for creating button.. and in subclass i also set the frame
    Please help
    R's
    Binny

    here is the code.... JButton, JPanel, ButtonViewer all this classes are resize into com.tree package i m trying to create root -> child button tree
    import java.awt.AWTEvent;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Frame;
    import java.awt.Image;
    import java.awt.Event;
    import java.awt.event.MouseEvent;
    import java.awt.Container;
    import java.awt.FlowLayout;
    import com.tree.*
    import java.sql.*;
    import java.util.ArrayList;
    import javax.swing.JApplet;
    //import javax.swing.*;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JComponent;
    public class ButtonTestViewer extends Object implements MouseListener
         JFrame frame;
         ButtonViewer viewer = new ButtonViewer();
         JButton root;
         Panel panel;
         ButtonTestViewer()
              //super();
              frame = new JFrame("MouseEventDemo");
              viewer.setOrientation(Orientation.VERTICAL);
              viewer.setAlignment(Alignment.CENTER);
              panel = viewer.getPanel();
              panel.setBorder(BorderFactory.createTitledBorder("Visualizer Button"));
              root = new JButton("1");
              panel.add(root);
              JScrollPane jScrollPane1 = new JScrollPane();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              jScrollPane1.setAutoscrolls(true);
              jScrollPane1.setViewportView(panel);
              frame.getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
              //panel.addMouseListener(this);
              viewer.add(root, null );
              root.addButton( JButton.ACTIVATE_CALLBACK, new ButtonChild(viewer,null,frame,root.getText()) );
              frame.pack();
              frame.setSize(600,400);
              frame.setVisible(true);
              viewer.getPanel().repaint();
              viewer.getPanel().validate();
         public static void main(String argv[])
              new ButtonTestViewer();
    public void mousePressed(MouseEvent e) {
              //frame.repaint();
              //repaint();
         public void mouseReleased(MouseEvent e) {
              //frame.repaint();
              //repaint();
         public void mouseEntered(MouseEvent e) {
              //frame.repaint();
              //repaint();
         public void mouseExited(MouseEvent e) {
              //frame.repaint();
              //repaint();
         public void mouseClicked(MouseEvent e) {
              System.out.println("mouse clicked");
              //panel.repaint();
    class ButtonChild extends CallButton
    static private int count = 0;
    private ButtonViewer viewer;
    private Image image;
    private JFrame frame;
    private int node;
    private ArrayList nodeList = new ArrayList();
    private ResultSet rs = null;
    private String sql = "";
    private int nodeid;
    private int position;
    private boolean nodeFlag = false;
    public ButtonChild( ButtonViewer viewer, Image image, JFrame frame, String label )
         System.out.println("label is:"+label);
    this.viewer = viewer;
    this.image = image;
    this.frame = frame;
    this.node = Integer.parseInt(label);
    this.nstmt = stmt;
    //this.container = container;
    //frame.show();
         public boolean activate(Event event)
              System.out.println("b");
              return false;
         public boolean activate(MouseEvent me)
              System.out.println("c");
              JButton child;
              try
                   for(int i=0; i<nodeList.size(); i++)
                        if(node == Integer.parseInt(nodeList.get(i).toString()))
                             nodeFlag = true;
                             break;
                   if(nodeFlag == false)
                        int k=3;
                        for(int i=2; i<=k; i++)
                             String name = ""+i;
                             //node = i
                             viewer.add(child = new JButton(name), (Widget)me.getSource() );
                             child.addButton( JButton.ACTIVATE_CALLBACK, new ButtonChild(viewer,image,frame,name) );
                             //container.add(child);
                             nodeList.add(name);
                        nodeList.add(""+node);
                        frame.repaint();
              }catch(Exception e)
                   e.printStackTrace();
              return true;
    }

  • A New Thread With Each Mouse Click

    Dear Java Programmers,
    The following code gives a bouncing ball inside of a panel. With each click, I need to have a different ball added and the previous ball to keep on bouncing. This part is a larger question of multitreading. When I have an action listener for mouse clicks, and I need to have a new thread with each click, how do I do this and where do I put it?
    Thank you in advance.
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.awt.BorderLayout;
    import java.awt.Graphics;
    import java.awt.*;
    import java.awt.Color;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    public class Multiball extends JPanel implements Runnable, MouseListener {
    Thread blueBall;
    boolean xUp, yUp;
    int x= -10, y= -10, xDx, yDy;
    public Multiball()
    xUp = false;
    yUp = false;
    xDx = 1;
    yDy = 1;
    addMouseListener( this );
    public void mousePressed( MouseEvent e )
    x = e.getX();
    y = e.getY();
    blueBall = new Thread( this );
    blueBall.start();
    public void paint( Graphics g )
    super.paint( g );
    g.setColor( Color.blue );
    g.fillOval( x, y, 10, 10 );
    public void run()
    while ( true ) {
    try {
    blueBall.sleep( 10 );
    catch ( Exception e ) {
    System.err.println( "Exception: " + e.toString() );
    if ( xUp == true )
    x += xDx;
    else
    x -= xDx;
    if ( yUp == true )
    y += yDy;
    else
    y -= yDy;
    if ( y <= 0 ) {
    yUp = true;
    yDy = ( int ) ( Math.random() * 1 + 2 );
    else if ( y >= 183 ) {
    yDy = ( int ) ( Math.random() * 1 + 2 );
    yUp = false;
    if ( x <= 0 ) {
    xUp = true;
    xDx = ( int ) ( Math.random() * 1 + 2 );
    else if ( x >= 220 ) {
    xUp = false;
    xDx = ( int ) ( Math.random() * 1 + 2 );
    repaint();
    public void mouseExited( MouseEvent e ) {}
    public void mouseClicked( MouseEvent e ) {}
    public void mouseReleased( MouseEvent e ) {}
    public void mouseEntered( MouseEvent e ) {}
    public static void main(String args[])
    JFrame a = new JFrame("Ball Bounce");
    a.add(new Multiball(), BorderLayout.CENTER);
    a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    a.setSize(240,230);
    a.setVisible(true);
    }

    Thank you very much for your replies. As for the multithreading, I have created 20 threads in the main method. With each click, one of these 20 threads starts in order. Now, how do I get a ball to paint with each one? How do I reference them in the paintComponent method?
       public void mousePressed( MouseEvent e )
             x = e.getX();
             y = e.getY();
             blueBall = new Thread( this );
             blueBall.start();
             count ++;
             System.out.print ("count is " + count);
          MyThread[] threads = new MyThread[20];
                for ( int ball = 0;ball < count; ball ++){
                threads[ball] = new MyThread ("" + ball);
                threads[ball].start ();
       }

  • Double value of mouse click

    hi, I am making a program in which I need to get the Double value of the point where I clicked on my JPanel. Is it possible to get the Double or float value of the point at which mouse click event occur.

    The mouse pointer is always exactly on one physical pixel, hence the integer coordinates are most accurate. You could pretend that the user means some other point (like the center of the pixel instead of the upper left corner) than the one s/he is pointing, that's your own business.
    You may actually lose accuracy when you cast the ints to doubles or floats.

  • JEditorPane - mouse click simulation doesn't work

    Hi all,
    I have a little problem with my JEditorPane. I want to implement the posibility to put signs on a document loaded in a jeditorpane and save them. One solution is to save the position of the scrollbar, but because the font size can be changed it will not be working. So I want to simulate a cmouse click on the first row of text from viewport to put there the caret and take after that his position. The problem is that the simulation for the mouse click donesn,t work. The event is simulated, but the caret position is not changing.
    I tried also using Robot class, but this implementation give me a serie a mouse events and it moves the cursor to the requested position and it's not the behaviour that I want.
    Here is my code:import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JButton;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.text.BadLocationException;
    public class Reader {
         JEditorPane jEditorPane;
         JScrollPane editorScrollPane;
         private JFrame frame;
         private JPanel readerPane;
         private JPanel commandsPane;
          * @param args
         public static void main(String[] args) {
              new Reader();
         public Reader() {
              frame = new JFrame();
              createReader();
              createCommands();
              addPanes();
              frame.setSize(1000, 850);
              // frame.setExtendedState(frame.MAXIMIZED_BOTH);
              frame.setVisible(true);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              loadHtml();
         private void addPanes() {
              GridBagLayout layout = new GridBagLayout();
              frame.setLayout(layout);
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.BOTH;
              c.gridx = 1;
              c.gridy = 0;
              c.ipadx = 0;
              c.ipady = 0;
              c.weightx = 1;
              c.weighty = 2;
              frame.add(readerPane, c);
              c = new GridBagConstraints();
              c.fill = GridBagConstraints.HORIZONTAL;
              c.gridx = 1;
              c.gridy = 1;
              c.ipadx = 0;
              c.ipady = 10;
              c.weightx = 0;
              c.weighty = 0;
              c.gridwidth = 1;
              c.gridheight = 1;
              frame.add(commandsPane, c);
         private void createCommands() {
              commandsPane = new JPanel();
              commandsPane.setBackground(Color.white);
              JButton backButton = new JButton("PUSH");
              commandsPane.add(backButton);
              backButton.addMouseListener(new MouseListener() {
                   @Override
                   public void mouseClicked(MouseEvent e) {
                        // TODO Auto-generated method stub
                   @Override
                   public void mouseEntered(MouseEvent e) {
                        // TODO Auto-generated method stub
                   @Override
                   public void mouseExited(MouseEvent e) {
                        // TODO Auto-generated method stub
                   @Override
                   public void mousePressed(MouseEvent e) {
                        MouseEvent click = new MouseEvent(jEditorPane,
                                  MouseEvent.MOUSE_CLICKED, System.currentTimeMillis(),
                                  16, 10, 200, 1, false, 1);
                        MouseListener[] listeners = jEditorPane.getMouseListeners();
                        for (int i = 0; i < listeners.length; i++) {
                             listeners.mouseClicked(click);
                   @Override
                   public void mouseReleased(MouseEvent e) {
                        // TODO Auto-generated method stub
         private void createReader() {
              jEditorPane = new JEditorPane();
              jEditorPane.setEditable(false);
              jEditorPane.setSelectionColor(Color.green);
              jEditorPane.addMouseListener(new MouseListener(){
                   @Override
                   public void mouseClicked(MouseEvent e) {
                        System.out.println("clicked");
                        System.out.println("caret pos = "
                                  + jEditorPane.getCaretPosition());
                   @Override
                   public void mouseEntered(MouseEvent e) {
                        // TODO Auto-generated method stub
                   @Override
                   public void mouseExited(MouseEvent e) {
                        // TODO Auto-generated method stub
                   @Override
                   public void mousePressed(MouseEvent e) {
                        // TODO Auto-generated method stub
                   @Override
                   public void mouseReleased(MouseEvent e) {
                        // TODO Auto-generated method stub
              editorScrollPane = new JScrollPane(jEditorPane);
              editorScrollPane.setBorder(null);
              editorScrollPane.getVerticalScrollBar().setPreferredSize(
                        new Dimension(0, 0));
              readerPane = new JPanel();
              readerPane.setBackground(Color.black);
              readerPane.setLayout(new GridBagLayout());
              JPanel spacePane = new JPanel();
              spacePane.setBackground(Color.white);
              GridBagConstraints c = new GridBagConstraints();
              c = new GridBagConstraints();
              c.fill = GridBagConstraints.NONE;
              c.ipadx = 500;
              c.ipady = 650;
              c.weighty = 1;
              c.weightx = 1;
              c.gridx = 1;
              c.gridy = 1;
              c.gridwidth = 1;
              c.gridheight = 1;
              readerPane.add(spacePane, c);
              spacePane.setLayout(new GridBagLayout());
              c = new GridBagConstraints();
              c.fill = GridBagConstraints.BOTH;
              c.weighty = 1;
              c.weightx = 1;
              c.gridx = 0;
              c.gridy = 0;
              c.gridwidth = 1;
              c.gridheight = 1;
              c.insets = new Insets(20, 20, 20, 20);
              spacePane.add(editorScrollPane, c);
         private void loadHtml() {
              System.out.println("load html file");
              jEditorPane.setContentType("text/html");
              jEditorPane.setText("<html><body>" +
                        "<p>some text here for testing some text here for testing some text here for testing some text here for testing " +
                        "some text here for testing some text here for testing some text here for testing some text here for testing " +
                        "some text here for testing some text here for testing some text here for testing some text here for testing " +
                        "some text here for testing some text here for testing some text here for testing some text here for testing " +
                        "some text here for testing some text here for testing some text here for testing some text here for testing </p>" +
                        "</body></html>");
              jEditorPane.revalidate();
    If tou run this code you can observe that when the "PUSH" button is pressed the jeditorpane receives a mouseclick event, but the caret position is not changing.
    Strange is that when you click with the mouse over the editor pane the caret position is changed and I don't understand what is wrong.
    Can you help me please?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    You can use viewToModel() method to get caret position for x, y location. No need to click.
    Regards,
    Stas

  • Catching mouse click on an irrigular shape image

    Is it possible to catch the mouse click on an irrigular shape image on a JPanel? Can I simply attach a mouse listener to the image?

    Hi,
    you should use a mouseListener, and test the coordinates of the click in the mouseClicked() method, then you can use the inside() method of the Shape to see if the click occured in the shape.
    Hope this will help,
    Regards.

Maybe you are looking for