Adding a MouseListener to a JFrame

I want my JFrame to be notified when a cell in a JTable is double clicked (so I can do some processing and then close the frame).
I thought I could add a MouseListener to the JFrame. However, the JTable processes, then consumes, the mouse event so the JTable never receives the MouseEvent. I attempted to override the processMouseEvent method of JTable to dispatch an event to the JFrame, but it didn't work as the event was sent back to the JTable.
Here is the simple program I am using to test my problem. (Note, in the real application the JFrame, contains class1, which contains class2, which contains the JTable, so it not simply a matter of the JTable invoking a method in the JFrame class.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class MouseTable extends JFrame
     JFrame frame;
     public MouseTable()
          frame = this;
          JTable table = new JTable(4, 3)
               protected void processMouseEvent(MouseEvent e)
                    System.out.println( "Click count: " + e.getClickCount() );
                    super.processMouseEvent(e);
                    //  this event is dispatched back to here, not the frame
                    if (e.getClickCount() == 2)
                         MouseEvent me =
                         new MouseEvent(frame, e.getID(), 0, 0, 0, 0, 9, false);
                         frame.dispatchEvent(me);
          JScrollPane scrollPane = new JScrollPane( table );
          getContentPane().add( scrollPane );
          frame.addMouseListener( new MouseAdapter()
               public void mouseClicked(MouseEvent e)
                    System.out.println("Clicked: " + e);
     public static void main(String[] args)
          MouseTable frame = new MouseTable();
          frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
          frame.pack();
          frame.setVisible(true);
}1) Click on the viewport, the JFrame receives the mouse event
2) Click on the JTable, the JFrame does not receive the mouse event
Any ideas on why the dispatchEvent doesn't work?
Any other better approaches?

I did read the documentation correctly. The ID field should represent the mouse event you want to generate. Here are the ids:
MOUSE_CLICKED = 500
MOUSE_PRESSED = 501
MOUSE_RELEASED = 502
MOUSE_MOVED = 503
MOUSE_ENTERED = 504
MOUSE_EXITED = 505
In my simple example I used the following condition to dispatch an event to the JFrame:
if (e.getClickCount() == 2)
When I changed the condition to the following (which is what I really want), the program stops working:
if (e.getID() == MouseEvent.MOUSE_CLICKED && e.getClickCount() == 2)
The bottom line is that it appears the mouse event is still dispatched to the JTable even though the JFrame is specified as the object source. I gave up trying to figure out why.
However, all is not lost as I have found a better(?) way to accomplish what I want. In the constructor of my JFrame I add an AWTListener to listen for double click events:
//  Listen for mouse double clicks directly from the AWT Event Queue
Toolkit.getDefaultToolkit().addAWTEventListener( new AWTEventListener()
     public void eventDispatched(AWTEvent e)
          if (e.getID() == MouseEvent.MOUSE_CLICKED)
               MouseEvent me = (MouseEvent)e;
               if (me.getClickCount() == 2)
                    doProcessingHere();
}, AWTEvent.MOUSE_EVENT_MASK  );

Similar Messages

  • Problem adding a component into a JFrame

    public DVD_VIDEO_CLUB() {
    mainFrame = new JFrame("DVD-VIDEO CLUB");
    mainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
    aDesktopPane = new JDesktopPane();
    aDesktopPane.setBackground(Color.LIGHT_GRAY);
    aDesktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    mainFrame.setContentPane(aDesktopPane);
    mainFrame.getContentPane().add(internalPanels.MainInternalPanel());
    atoolkit = Toolkit.getDefaultToolkit();
    mainFrame.addKeyListener(new MainFrameKeyListener());
    mainFrame.addWindowListener(new FrameListener());
    mainFrame.setIconImage(createFeatures.getImage());
    mainFrame.setSize(atoolkit.getScreenSize());
    mainFrame.setJMenuBar(aMenubar.MakeMenuBar(new ItemActListener()));
    mainFrame.setVisible(true);
    mainFrame.setDefaultCloseOperation(3);
    }//end constructor
    The argument internalPanels.MainInternalPanel() is a class (internalPanels) which have various jpanels
    that i want to display under certain events.
    But i don't know why the command
    mainFrame.getContentPane().add(internalPanels.MainInternalPanel());
    doesn't work? I look into the java tutorial and i have read that in order to add a component you have to
    call the command
    jframe.getContentPane().add(component);
    any help is appreciated!

    my problem isn't how to add internalframes but how to add a jpanel.Did you set the size of the JPanel?
    import java.awt.*;
    import javax.swing.*;
    public class Example {
        public static void main(String[] args) {
            JFrame mainFrame = new JFrame("DVD-VIDEO CLUB");
            mainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
            JDesktopPane aDesktopPane = new JDesktopPane();
            mainFrame.setContentPane(aDesktopPane);
            JPanel p = new JPanel();
            p.add(new JLabel("here is your panel"));
            p.setLocation(100, 200); //as you like
            p.setSize(p.getPreferredSize()); //this may be what you are missing
            p.setVisible(true);
            mainFrame.getContentPane().add(p);
            mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mainFrame.setVisible(true);
    also i have tried not write 3 but JFrame.EXIT_ON_CLOSE but i was getting an error exception continiously.Do you mean a syntax error? That constant was introduced in 1.3 -- what version are you using?

  • One JPanel is missing after adding two JPanels to a JFrame

    I have two classes, ScoreTableView and CardView, which both extends the JPanel class. ScoreTableView is used to show one table only, and CardView is to show a set of cards for a memory game. My objective is to separate the development of the panels, so that it will easier to modify either of them later. I add instances of these two class to the contentPane of my top level JFrame object. However, I can only see the ScoreTableView(which is supposed to show me a table only) on the top part of the frame, and the CardView panel never show up.
    ScoreTableView.java
      public ScoreTableView(int numberOfPlayer){
    //      Create a model of the data.
            scoreTable = new JTable();//this scoreTable is a JTable object
            scoreTable.setModel(scoreTableData);  //scoreTableData is my data    
            JScrollPane jsp = new JScrollPane(scoreTable);          
            p = this;
            p.setLayout(new BorderLayout());
            p.add(jsp, BorderLayout.CENTER);
        }CardView.java
    public CardView(int w, int h){
            cardWidth = w;
            cardHeight = h;
            JPanel cardPanel = new JPanel();
            cardPanel.setLayout(new GridLayout(cardWidth,cardHeight)); 
            CardImageButton[][] cardsButtons = new CardImageButton[cardWidth][cardHeight];
          // ... more other none GUI coiding 
             }Here's what I have in my main
            Container contentPane = jf.getContentPane();//jf is the JFrame object          
            contentPane.setLayout(new BorderLayout()); 
    //      create the score panel                 
            ScoreTableView scoreTableView = new ScoreTableView(4);
          contentPane.add( scoreTableView, BorderLayout.NORTH);
            //create the cards panel
            CardView cardPanel = new CardView(4,4);
            contentPane.add(cardPanel, BorderLayout.CENTER);
            jf.pack();
            jf.setVisible(true);      

    Sorry, but I copied the wrong files. Now both panels can show up, but the score table is on the NORTH, and the card panel is on the SOUTH(although I set it to CENTER and wish it can occupy the rest of the window), but the center part of the window has nothing. How can I get rid of the white space, so that the score panel can can 30% of the top part of the window(even after resize), and the card panel can occupy the remaining 70%? I can't attach pictures here, otherwise I can upload some screenshot to show you what's the problem I have. Thank you in advance.
    This is my CardView class, I didnt' copy all of them upstair.
    public class CardView extends JPanel{
        private int cardWidth;
        private int cardHeight;
        private CardModel cm;
        private JPanel cardPanel;
        public CardView(int w, int h){
            cardWidth = w;
            cardHeight = h;
            cardPanel = this;
            cardPanel.setLayout(new GridLayout(cardWidth,cardHeight)); 
            CardImageButton[][] cardsButtons = new CardImageButton[cardWidth][cardHeight];
            int[][] list  = init(cardWidth, cardHeight);       
            cm = new CardModel(list);
            int count = 0;
            for(int i=0;i<cardWidth;i++){
                for(int j=0;j<cardWidth;j++){
                    cardsButtons[i][j] = new CardImageButton("Press me"+count, cm, i, j, 0);
                    cardPanel.add(cardsButtons[i][j]);
                    count++;               
    public int[][] init(int n, int m){
            int[][] list  = {
                    {1, 2, 1, 1},
                    {2, 1, 2 , 2},
                    {1, 2, 1, 1},
                    {2, 1, 2 , 2} };
            return list;
        }This is from my main.
           //setup the content panel
            Container contentPane = jf.getContentPane();          
            contentPane.setLayout(new BorderLayout()); 
    //      create the score panel                 
            ScoreTableView scoreTableView = new ScoreTableView(4);
          contentPane.add( scoreTableView, BorderLayout.NORTH);
            //create the cards panel
            CardView cardPanel = new CardView(4,4);
            contentPane.add(cardPanel, BorderLayout.CENTER);
            jf.pack();
            jf.setVisible(true);   ScoreTableView.java
      public ScoreTableView(int numberOfPlayer){
    //      Create a model of the data.
    scoreTable = new JTable();//this scoreTable is a JTable object       
    scoreTable.setModel(scoreTableData);  //scoreTableData is my data            
    JScrollPane jsp = new JScrollPane(scoreTable);                  
    p = this;       
    p.setLayout(new BorderLayout());       
    p.add(jsp, BorderLayout.CENTER);   
    }

  • Error in adding a Tab to a JFrame

    Hi.. I am getting this error when I compile the following piece of code.. Could anyone help me with the error plz..
    C:\Documents and Settings\Ravaboli\Desktop\new testing\CopyDetectionFrame.java:24: addTab(java.lang.String,javax.swing.JPanel) in CopyDetectionFrame cannot be applied to (java.lang.String,InternetPlagiarismTab)
              addTab("Internet Plagiarism Detector", new InternetPlagiarismTab());
    ^
    C:\Documents and Settings\Ravaboli\Desktop\new testing\CopyDetectionFrame.java:25: addTab(java.lang.String,javax.swing.JPanel) in CopyDetectionFrame cannot be applied to (java.lang.String,CollusionDetectorTab)
              addTab("Collusion Detection", new CollusionDetectorTab());
    ^
    2 errors
    Tool completed with exit code 1
    CollusionDetectorTab and InternetPlagiarismTab are already functioning..which I have already created
    The code:
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    public class CopyDetectionFrame extends JFrame
         private ArrayList tabs;
         private JTabbedPane jtb;
         public CopyDetectionFrame()
              // set JFrame stuff
              setLocation(200,200);
              setSize(800, 600);
              setTitle("Copy Detector");
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              // Make tabs
              jtb = new JTabbedPane();
              tabs = new ArrayList();
              if("true".equals(Config.read("showhome")))
              addTab("Internet Plagiarism Detector", new InternetPlagiarismTab());
              addTab("Collusion Detection", new CollusionDetectorTab());
              getContentPane().add(jtb);
              // create some basic menus
              JMenuBar jmb = new JMenuBar();
              setJMenuBar(jmb);
              JMenu file = new JMenu("File");
              JMenuItem quit = new JMenuItem("Quit");
              quit.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        cleanup();
                        System.exit(0);
              file.add(quit);
              jmb.add(file);
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent we) {
                        cleanup();
         public void addTab(String title, JPanel ot)
              jtb.add(title, ot);
              tabs.add(ot);
         private void cleanup()
              for(int i = 0; i < tabs.size(); i++)
              try
    //               ((OptionTab)tabs.get(i)).cleanup();
              catch(Exception e) {}
         public static void main(String[] args)
              JFrame.setDefaultLookAndFeelDecorated(true);
              JDialog.setDefaultLookAndFeelDecorated(true);
              try
                   UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
              catch (Exception ex)
                   System.out.println("Failed loading L&F: ");
                   System.out.println(ex);
              new CopyDetectionFrame().show();
    }

    For that code to work, your two Tabs (InternetPlagiarismTab and CollusionDetectionTab) would need to extend JPanel. Do they?
    i.e.:
    class InternetPlagiarismTab extends JPanel { ... }

  • Adding .jpg image to the JFrame

    I want to add an image in the JFrame
    My code is as follows:
    import java.awt.*;
    import javax.swing.*;
    public class test extends JPanel
         JProgressBar pb1 = new JProgressBar(JProgressBar.HORIZONTAL,0,100);
    public test(String image)
    ImageIcon imgIco = new ImageIcon(image);
    JLabel imgLbl = new JLabel(imgIco);
    imgLbl.setPreferredSize(new Dimension(500,500));
    JPanel p1 = new JPanel();
    p1.add(pb1);
    setLayout(new GridLayout(1,1));
    add(imgLbl);
    add(p1);
    public void salman()
              int i=0;
              while(i<=100)
                   try
                        pb1.setValue(i);
                        pb1.setForeground(Color.lightGray);
                        pb1.setBackground(Color.blue);
                        pb1.setBorderPainted(true);
                        pb1.setStringPainted(true);
                        Thread.sleep(55);
                   catch(Exception e)
                        System.out.println("Exception Occured!!!");
                   i++;     
    public static void main(String[] args)
    JFrame f = new JFrame();
    test img = new test("pills.jpg");
    f.getContentPane().add(img);
    f.setSize(450,470);
    f.setVisible(true);
    img.salman();
    Thanks for you co-operation.
    Regards
    Salman Pirzada

    you use
    test img = new test("pills.jpg");where it finds pills.jpg????
    try something like this:
    String imageName = "pills.jpg";
    img = Toolkit.getDefaultToolkit().getImage(Test.class.getResource(imageName));And make sure, pills.jpg is in the same directory where Test class is

  • Adding a mouseListener to the tabs in a tabbedPane.

    What I would like is a listener that listens to mouse clicks on the tabs in a tabbed pane.
    How would I go about creating this? The changeListener will not work for my purpose.

    The changeListener will not work for my purposeWhy? What is your purpose?
    If its related to you other question, then of course a changelistener will work.

  • Mouse click event on window edge?

    Hi,
    I have a JFrame and I need to detect a mouseclick when the window is maximised and when the mouse is clicked at the extreme left edge of the window.
    How can I achieve this? Adding a mouselistener for the JFrame doesn't work either. Adding mouselisteners to the JFrame's glasspane, rootpane layeredpane also doesn't work. Please give me some pointers.
    regards

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    class Testing
      public Testing()
        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame f = new JFrame();
        f.setSize(300,200);
        f.setLocation(350,200);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new JPanel());
        f.setVisible(true);
        f.addMouseListener(new MouseAdapter(){
          public void mousePressed(MouseEvent me){
            System.out.println("me.getX() = "+me.getX()+"\nme.getY() = "+me.getY());
      public static void main(String[] args){new Testing();}
    }

  • Removing and adding panels to a jframe

    i have tried using remove all to remove a panel which is on my mainpanel which is on the jframe. when i do though, only the area where the menu was is removed. The components on the frame are not accessible. i want to then add another frame. this does not seem to work. i have tried using removeAll(), validate(), repaint(). i am probably not using them correctly or in the right order, so can anyone help me out?????????

    If you have added the JPanel to the JFrame and the components to the JPanel the removeAll() should work.
    public void actionPerformed(ActionEvent e){
       if(e.getSource()==myButton){
           content.removeAll();
           content.add(panel2);
      }

  • Editable Title Bar in a JFrame?

    I have a standalone application that launches a JFrame. Is there some way to allow the user to set the title of the JFrame?

    Well, no word from the OP, but since I had some time in between compiles, I was able to fix both problems from my earlier code:
    1) By adding the MouseListener, the frame is now unmovable and unresizable. I wasn't expecting that.I've now added the MouseListener to the frame instead of the titleComponent.
    2) The code above uses a double-click to activate the text entry. If you can resolve problem #1, then you'd want to convert this into a right-click menu item or something similar.I made a right-click menu popup to activate the rename.
    New code for anyone interested:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class RenameFrameDemo implements Runnable
      private JFrame frame;
      private JPopupMenu renamePopup;
      private JPopupMenu renameMenu;
      private JTextField text;
      private Component titleComponent;
      public void run()
        text = new JTextField();
        text.setBorder(null);
        text.addActionListener(new ActionListener()
          public void actionPerformed(ActionEvent event)
            applyTitle();
        JMenuItem menuItem = new JMenuItem("Rename");
        menuItem.addActionListener(new ActionListener()
          public void actionPerformed(ActionEvent event)
            editFrameTitle();
        renameMenu = new JPopupMenu();
        renameMenu.add(menuItem);
        renamePopup = new JPopupMenu();
        renamePopup.setBorder(new MatteBorder(1, 1, 1, 1, Color.DARK_GRAY));
        renamePopup.add(text);
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 200);
        frame.setLocationRelativeTo(null);
        frame.setTitle("My Application");
        frame.setVisible(true);
        titleComponent = frame.getLayeredPane().getComponent(1);
        frame.addMouseListener(new MouseAdapter()
          public void mousePressed(MouseEvent event)
            showRenameMenu(event);
          public void mouseReleased(MouseEvent event)
            showRenameMenu(event);
      private void showRenameMenu(MouseEvent event)
        if (event.isPopupTrigger())
          Rectangle bounds = titleComponent.getBounds();
          if (bounds.contains(new Point(event.getX(), event.getY())))
            renameMenu.show(event.getComponent(), event.getX(), event.getY());
      private void editFrameTitle()
        Rectangle bounds = titleComponent.getBounds();
        text.setText(frame.getTitle());
        renamePopup.setPreferredSize(
            new Dimension(bounds.width - bounds.height,  bounds.height));
        renamePopup.show(titleComponent, bounds.x + bounds.height, bounds.y);
        text.requestFocusInWindow();
        text.selectAll();
      private void applyTitle()
        frame.setTitle(text.getText());
        renamePopup.setVisible(false);
      public static void main(String[] args) throws Exception
        JFrame.setDefaultLookAndFeelDecorated(true);
        SwingUtilities.invokeLater(new RenameFrameDemo());
    }

  • MouseListener is not working for JComboBox

    hi
    i've added a mouseListener to a JComboBox, but i don't see the messages the events should print. can anyone tell me what i've missed?
    package test;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JComboBox;
    public class testmain {
    public testmain() {
    JFrame frame = new JFrame();
    frame.setBounds(50, 50, 200, 200);
    JComboBox cbox = new JComboBox();
    cbox.addItem("ai1");
    cbox.addItem("ai2");
    cbox.addMouseListener(new MouseAdapter(){
    public void mouseReleased(MouseEvent e){
    System.out.println("released");
    public void mousePressed(MouseEvent e){
    System.out.println("pressed");
    public void mouseClicked(MouseEvent e){
    System.out.println("clicked");
    frame.getContentPane().add(cbox, "North");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.show();
    public static void main(String[] args) {
    testmain testmain1 = new testmain();
    thanks

    yeah, i don't like this, it's nasty, but i got it to work. try this:
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    public class Test implements MouseListener{
         public Test() {
              JFrame frame = new JFrame();
              frame.setBounds(50, 50, 200, 200);
              JComboBox cbox = new JComboBox();
              cbox.addItem("ai1");
              cbox.addItem("ai2");
              cbox.getComponent(0).addMouseListener(this);
              frame.getContentPane().add(cbox, "North");
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.show();
         public static void main(String[] args) {
              Test testmain1 = new Test();
         public void mouseEntered(MouseEvent e) {
              System.out.println("entered");
         public void mouseReleased(MouseEvent e) {
              System.out.println("released");
         public void mousePressed(MouseEvent e) {
              System.out.println("pressed");
         public void mouseClicked(MouseEvent e) {
              System.out.println("clicked");
         public void mouseExited(MouseEvent e) {
              System.out.println("exited");
    }...perhaps someone can provide a more elegant solution and/or explain why i have to do a getComponent(0), which stinks if you ask me.

  • Moving a shape randomly through a JFrame

    I'm trying to make a rectangle move to an arbitrary position when the mouse is clicked. I can't get the mouseClicked method to call the fillRect one. Does anyone know what I should do?
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.util.Random;
    import javax.swing.JApplet;
    import javax.swing.JFrame;
    public class ex4 extends JFrame implements MouseListener {
    Random numGen = new Random();
             Color getRandomColor() {
                return new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
    Random generator = new Random();
    int randomIndex = generator.nextInt( 400 );
         private String message = new String ("");
         private Color myColor = Color.WHITE;
         public ex4() {
              setSize(400,400);
              setTitle("ex4");
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              addMouseListener(this);
              setVisible(true);
              this.setBackground(Color.WHITE);
         public void paint(Graphics g) {
              super.paint(g);
              int x = generator.nextInt();
              int y = generator.nextInt();
                 g.setColor(getRandomColor());
              g.fillRect( x, y, x/2, y/2);
         public void mouseClicked(MouseEvent arg0) {
         public void mouseEntered(MouseEvent arg0) {
         public void mouseExited(MouseEvent arg0) {
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
          * @param args
         public static void main(String[] args) {
              new ex4();
         public void setMyColor(Color myColor) {
              this.myColor = myColor;
         public Color getMyColor() {
              return myColor;
         

    scheng12 wrote:
    this is an entirely different code than my other thread.and yet yet you're still committing the same error of trying to draw directly to the JFrame and adding a MouseListener directly to the JFrame.

  • JButton Adding Problem

    Hi everyone,
    First, like to say I appreciate all your help. I have come here for help before and I always get my questions answered. Thanks.
    Here is my problem:
    I've created a JPanel and added this panel to a JFrame. The JPanel has a MouseListener and a MouseMotionListener. I am tryin to add JButtons to the JPanel at positions passed from the MouseMotionListener, but everytime I attempt this, the JButton pops to the top left corner of the screen. I don't know if I should use a layout manager on the JPanel and if I do, I don't know which one to use. I've tried using the SpringLayout, but was unsuccessful at deploying it.
    Appreciate any help.
    Thanks again.

    Null layout is not recommended, see my earlier post. Here is a simple SpringLayout that does the same thing.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TestSpring extends JFrame
         Container cp;
         int mpx, mpy;
         int MINX= 80;
         int MINY=20;
         JLabel txt = new JLabel("use mouse to position buttons, drag to set size");
         SpringLayout slay = new SpringLayout();
         MouseInputAdapter mia = new MouseInputAdapter()
              public void mousePressed(MouseEvent evt){mousePress(evt);}
              public void mouseReleased(MouseEvent evt){mouseRelease(evt);}
         TestSpring()
              super("TestSpring");
              cp = getContentPane();
              addWindowListener(new WindowAdapter()
              {public void windowClosing(WindowEvent evt){System.exit(0);}});
              cp.addMouseListener(mia);
              cp.setLayout(slay);
              cp.add(txt);
              setBounds(0,0,700,400);
         void mousePress(MouseEvent evt)
              mpx = evt.getX();
              mpy = evt.getY();
         void mouseRelease(MouseEvent evt)
              int x,y,dx,dy;
              x = evt.getX();
              y=evt.getY();
              dx = x-mpx;
              dy = y-mpy;
              if(dx < 0){dx = -dx; mpx = x;}
              if(dy < 0){dy = -dy; mpy = y;}
              JButton jb = new JButton(mpx+","+mpy);
              cp.add(jb);
              setCPosition(jb,mpx,mpy);
              if(dx < MINX)dx = MINX;
              if(dy < MINY)dy = MINY;
              setCSize(jb, dx, dy);
              cp.validate();
         void setCPosition(Component c, int x, int y)
              slay.getConstraints(c).setX(Spring.constant(x));
              slay.getConstraints(c).setY(Spring.constant(y));
         void setCSize(Component c, int w, int h)
              slay.getConstraints(c).setWidth(Spring.constant(w));
              slay.getConstraints(c).setHeight(Spring.constant(h));
         // the main startup function
         public static void main(String[] args)
              new TestSpring().show();
    }

  • Getting MouseListener on panel containing canvas'

    Hi.
    I'm using Java 1.2 and AWT, and have created a simple colour scale.
    At the moment, I am trying to code it so that clicking on one square within the scale will highlight it. To do this I tried adding a MouseListener to the scale itself --- but this didn't seem to work.
    Any help would be much appreciated!
    public class ColourScale extends java.awt.Panel {
        private ColourSquare cs[];
        private int csNum;
        private boolean squareNum;
        private java.awt.GridBagConstraints gridBagConstraints;
        /** Creates a new instance of ColourScale */
        public ColourScale(int cn) {
            int i = 0;
            csNum = 0;
            squareNum = true;
            cs = new ColourSquare[6];
            for (i = 0; i < 6; i++) {
                cs[i] = new ColourSquare();
            addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    java.awt.Point pt = evt.getPoint();
                    for(int i = 0; i < csNum; i++) {
                        if (cs.contains(pt)) {
    cs[i].setMyBorder(true);
    } else {
    if(squareNum) {
    cs[i].setMyBorder(false);
    if (cn > 6 || cn < -1) {
    cn = 6;
    setCsNum(cn);
    setLayout(new java.awt.GridLayout());
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridy = 0;
    for(i = 0; i < cn; i++) {
    gridBagConstraints.gridx = i;
    gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
    add(cs[i]);
    class ColourSquare extends java.awt.Canvas {
    private int bgColour;
    private boolean border;
    ColourSquare() {
    super();
    bgColour = 0;
    border = false;
    setSize(new java.awt.Dimension(15, 15));
    // addMouseListener(new java.awt.event.MouseAdapter() {
    // public void mouseClicked(java.awt.event.MouseEvent evt) {
    // ColourSquare c = (ColourSquare) evt.getSource();
    // c.setMyBorder(!c.getMyBorder());
    public int getBgColour() {
    return bgColour;
    public void setBgColour (int newC) {
    bgColour = newC;
    repaint();
    public boolean getMyBorder() {
    return border;
    public void setMyBorder(boolean newB) {
    border = newB;
    repaint();
    public void paint(java.awt.Graphics g) {
    // changes square colours, and draws border around square...

    Here's something:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame {
        public Test () {
            setContentPane (new TestPanel ());
            setDefaultCloseOperation (EXIT_ON_CLOSE);
            setTitle ("Test");
            pack ();
            setLocationRelativeTo (null);
            setVisible (true);
        public static void main (String[] parameters) {
            new Test ();
        private class TestPanel extends JPanel {
            private final int cx = 3;
            private final int cy = 3;
            private ClickablePanel[][] clickablePanels;
            private ClickablePanel selectedPanel;
            public TestPanel () {
                setLayout (new GridLayout (cx, cy));
                clickablePanels = new ClickablePanel[cy][cx];
                for (int r = 0; r < cy; r ++) {
                    for (int c = 0; c < cx; c ++) {
                        clickablePanels[r][c] = new ClickablePanel ();
                        add (clickablePanels[r][c]);
                selectedPanel = null;
                addMouseListener (new MouseAdapter () {
                    public void mouseClicked (MouseEvent event) {
                        selectedPanel = (ClickablePanel) findComponentAt (event.getPoint ());
                        for (int r = 0; r < cy; r ++) {
                            for (int c = 0; c < cx; c ++) {
                                clickablePanels[r][c].setSelected (clickablePanels[r][c] == selectedPanel);
                                clickablePanels[r][c].repaint ();
            public Dimension getPreferredSize () {
                return new Dimension (cx * 50, cy * 50);
            private class ClickablePanel extends JPanel {
                private boolean selected;
                public ClickablePanel () {
                    selected = false;
                public void setSelected (boolean selected) {
                    this.selected = selected;
                public void paintComponent (Graphics g) {
                    super.paintComponent (g);
                    int w = getWidth ();
                    int h = getHeight ();
                    g.drawLine (0, 0, 0, h);
                    g.drawLine (0, h, w, h);
                    g.drawLine (w, h, w, 0);
                    g.drawLine (w, 0, 0, 0);
                    if (selected) {
                        g.drawLine (0, 0, w, h);
                        g.drawLine (0, h, w, 0);
    }Kind regards,
      Levi

  • Problem with insets and placement within a JFrame.

    I have written some code that actively renders (at about 100 fps) to a JPanel contained within a JFrame. The size of the frame and the size of the panel are both set to 1000 by 700 (odd i know..)
    Everything seems to work fine and I have encountered insets before so when I am rendering I have been adjusting accordingly. However I have started to try and draw my own menu bar at the bottom of the panel and this is where I am having problems. Whatever I draw seems to be too low and disappears off the bottom. To solve this I tried getting the insets from the JFrame:
    Insets insets = getInsets();
    xAdjustmentLeft = insets.left;
    xAdjustmentRight = insets.right;
    yAdjustmentTop = insets.top;
    yAdjustmentBottom = insets.bottom;When I do this on my vista machine I get insets of 3, 3, 23, 3 accordingly. When I print out the coordinates of mouse clicks I find that at the top left corner i get 3, 23 as you would expect. When I click in the bottom right corner of my screen I get 996 (ish), 716.
    The 996 can be explained by the left inset and my bad clicking however the 716 bears no relation to the top inset of 23 or the bottom inset of 3 in any way .... I am doing something wrong or have I missed something such as by adding the JPanel to the JFrame I have added or subtracted a distance somehow?
    I ran the program on my xp machine and got similar insets of 3,3,29,3. However when I click in the bottom right of the page I get exactly the same coordinates as on the vista machine .. this just doesn't seem to make sense?
    I should probably also mention how the rendering works just incase ... I'm drawing to a VolatileImage which I then draw onto the JPanel using its own graphical context. Interestingly anything I render on the image at y coord of 0 appears correctly at the top of the screen .... which it shouldn't because of the inset ... I'm so confused.
    I hope someone can help / understand my babblings. If you need more code I can post it.. just there's rather alot of it.

    Sorry, my bad I realised I was doing some rather stupid calculations elsewhere in the program. I have now managed to get my drawn bar where I need it to be on both machines.
    However, if I am rendering a picture of 1000 by 700 and the actual screen you are seeing is something along the lines of 993 by 674 (values minus the insets) this means I am wasting time rendering a picture larger than I am actually displaying, how to be normally interpret the sizes, do they go to the very outside of the panel or the visual element inside it? I could easily just increase the JFrame itself to be larger say 1006 by 726 and have the image the exact size within that.
    Whichever way I have solved my original problem so no worries.

  • How to change the cursor type when a TableView class was added to a Swing application?

    We can resize column width by dragging the column divider in the table header. This is a built-in feature of the TableView class.
    Normally, the cursor will become to east-resize (or west-resize) type with positioning the cursor just to the right of a column header.
    However, I found that the cursor is remaining the default type at the same position if I integrate JavaFX into Swing Application. That is adding the TableView to a Scene, and then adding this Scene to a JFXPanel, finally, adding this JFXPanel to the JFrame.
    The sample codes are listing below:
    public class Run extends JFrame {
        Run() {
            setSize(600, 450);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            initComponents();
        private void initComponents() {
            final JFXPanel fxPanel = new JFXPanel();
            this.getContentPane().add(fxPanel);
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    initFX(fxPanel);
        private void initFX(JFXPanel fxPanel) {
            Scene scene = null;
            try {
                scene = FXMLLoader.load(
                    new File("res/fxml_example.fxml").toURI().toURL()
            } catch (Exception ex) {
                ex.printStackTrace();
            fxPanel.setScene(scene);
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new Run().setVisible(true);
    fxml_example.fxml:
    <?xml version="1.0" encoding="UTF-8"?>
    <?import javafx.scene.Scene?>
    <?import javafx.scene.control.TableView?>
    <?import javafx.scene.control.TableColumn?>
    <Scene xmlns:fx="http://javafx.com/fxml">
        <TableView fx:id="tableView"
                   editable="true">
            <columns>
                <TableColumn text="COL1">
                </TableColumn>
                <TableColumn text="COL2">
                </TableColumn>
                <TableColumn text="COL3">
                </TableColumn>
                <TableColumn text="COL4">
                </TableColumn>
                <TableColumn text="COL5">
                </TableColumn>
            </columns>
        </TableView>
    </Scene>
    So, are there anyone can advise how to fix these codes; make the cursor can change to east-resize (or west-resize) type when this TableView class was added to a Swing application?

    Thanks for the report. I've just filed a JIRA issue: https://javafx-jira.kenai.com/browse/RT-34009
    //Anton.

Maybe you are looking for