Mouse Pressed in a JTree

I have a JTree in my GUI and I have set up a mouse listener for this JTree - when I click anywhere in this JTree, I can print to the screen that an event has occurred, my problem is getting the source of the event ie; what JTree element has been clicked, any ideas???
public void mousePressed(MouseEvent m)
  System.out.println("Mouse pressed");
}

Here is the upper portion of my mouse pressed routine
public void mousePressed(MouseEvent e) {
  int selRow = completeTree.getRowForLocation(e.getX(), e.getY());
  TreePath selPath = completeTree.getPathForLocation(e.getX(), e.getY());
  if (selPath == null) {return;}
  // first force to node where right click occured
  completeTree.setSelectionPath(selPath);
  completeTree.scrollPathToVisible(selPath);
  final DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) completeTree.getLastSelectedPathComponent();
  if (currentNode == null) {return;}
  Object currentNodeInfo = currentNode.getUserObject();
  final NodeInfo nText = (NodeInfo)currentNodeInfo;It should give you the idea of what to do.
rykk

Similar Messages

  • How can I get mouse pressed and mouse released positions on the desktop whi

    Hello All,
    I am generating a Frame using Swing API. My requirement is I need to capture the mouse pressed and mouse released positions, whenever user drags the mouse on desktop region (i.e. outside of the Frame). I require these points to find the rectangle region user has generated starting from mouse pressed to mouse released position. I need to pass that rectangle to Robot class in order to capture that desktop region.
    Can anybody help me out how can I achieve this using java on MAC, Linux and Windows platforms?
    Thanks in advance.
    Regards,
    VPKVL

    VPKVL wrote:
    DarrylBurke wrote:
    Can't be done in Java.I don't think that there is something which can't be done using java. When searched over net, found few applications which are using java for implementing this feature but not free, asking for license fee. I checked by downloading the demo version.
    Just want to know the hint how it can be achieved so that I can move further on that lines.
    Your thoughts ?They use JNI with the OS API.

  • Specifying a circle with 2 mouse presses

    Hi,
    I'm trying to create an applet that allows the user to specify a circle with 2 mouse presses. I'd like the 1st point to represent the circle's centre and the 2nd to be any point on the periphery.
    Creating a mouse press event handler is a given obviously within the applet. I think I'm going to need to create a variable to store the count of the mouse presses (i.e. so that I know when there've been two and the circle can be created).
    Can anyone tell me what the basic logic would be to actually create the circle based on the 2 mouse presses?
    Thanks.

    Can anyone tell me what the basic logic would be to
    actually create the circle based on the 2 mouse
    presses?
    implements MouseListener{
      int centerX = 0;
      int centerY = 0;
      int radius = 0;
    public void paint(Graphics g){
      g.drawOval(centerX-radius, centerY-radius,
                 centerX+radius, centerY+radius);
    public void mousePressed(MouseEvent me){
      centerX = me.getX();
      centerY = me.getY();
    public void mouseReleased(MouseEvent me){
      //a line from the center
      //length of x
      int x = me.getX()-centerX;
      //length of y
      int y = me.getY()-centerY;
      //a2 + b2 = c2
      radius = sqrt(pow(x, 2)+pow(y, 2));
    }i think this will work.. I used mousePressed and mouseReleased instead of two clicks.. but you can alter this if you like of course.. im not that very sure of the radius calculation, but i hope you get my point :)

  • How can i populate the JComboBox upon mouse pressed on it?

    I have a question i don't know if this possible in swing.
    The question goes like this.
    I have three comboboxes (grand parent -> parent -> child) on Jtable this table has multiple rows from DB. I have to also explain the design before i go and present question. The grand parent combo box is the only one with multiple values in it (when the table is loaded) the parent and child comboboxes are initialized with one null value in it this was done by turning text field into combo box and populate with null array list. This is how it was done all of this done on initial table loading.
    Now working Scenario I:
    If user click on grand parent and choose a value then parent combo gets updated and same with child combo....this works fine.
    Issue i am having with Scenario:
    The issue is when a user click on parent or child then the respective combo box gets the related values and populate into the same combobox that the user has just clicked on. I wrote an event mouse pressed on these combo box and this fetches the values from the linked list and prints but not showing up in the combo box.
    Is there something i am doing wrong?
    Thanks in advance.

    I figured out the solution myself.
    Thanks

  • How to post an Event (mouse left click) to JTree node

    Hi,
    I am using JTree for my application just like the windows explorer tree. By default, Jtree node will got focus using left click. But, I'd like that my tree will detect a right click so that I can copy any file to the Jtree. I've added a mouselistener to it but the node is not selected by the right click. Anyboby can teach me how to post a mouse left click event to the Jtree so that it will become selected using left click.
    Thanks a million

    See if this is useful
    public void mouseClicked(MouseEvent event)
    Object object = event.getSource();
    if (object == mTree)
    mTree_mouseClicked(event);
    private void mTree_mouseClicked(MouseEvent event)
    if(event.getModifiers()==event.BUTTON3_MASK)
    //your logic goes here
    }//close method

  • How to post an Event (mouse left click) to JTree

    Hi,
    I am using JTree for my application just like the windows explorer tree. By default, Jtree node will got focus using left click. But, I'd like that my tree will detect a right click so that I can copy any file to the Jtree. I've added a mouselistener to it but the node is not selected by the right click. Anyboby can teach me how to post a mouse left click event to the Jtree so that it will become selected using left click.
    Thanks a million

    Hi
    In the class JTree there is a method getClosestPathForLocation(int, int). The parameters are the coordinates which you can get from the MouseEvent. If you have this TreePath you can select the Node.
    This should solve your problem.
    Regards
    Dieter

  • Move button by mouse pressed

    Hello guys.
    I'm new here.
    I have a problem with my java programming and i'm wondering if you can help.
    Write a class (called W6P1.java) that will create the following interface:
    3 buttons (one, two, three).
    Tips:
    - Set size to (300,100);
    - Use FlowLayout as the layout manager
    Add action listeners to the left button <one> and the right button <three> and add code to rotate the labels of the buttons every time a button is pressed. If the left button is pressed the labels rotate to the left (from <one>, <two>, <three> they will become <two>, <three>, <one>, press it again and they become <three>, <one>, <two>; press it for a third time and they become as before <one> <two> <three>.
    Similar operation is required when the right button (<three>) is clicked but this time the rotation will take place right-wise.
    I have done this:
    import javax.swing.*;           //for everything that is Jxxx
    import java.awt.*;                //for FlowLayout
    import java.awt.event.*;     //for the actionlistener
    public class W6P1 extends JFrame implements ActionListener
         private JButton btn1;
         private JButton btn2;
         private JButton btn3;
         public W6P1()
              super("Work6Part1");
              btn1 = new JButton("One");
              btn2 = new JButton("Two");
              btn3 = new JButton("Three");
              btn1 = new FlowLayout(FlowLayout.RIGHT);
              setLayout(new FlowLayout());
              add(btn1);
              add(btn2);
              add(btn3);     
              ButtonHandler handler = new ButtonHandler();
              btn1.addActionListener(handler);
              btn2.addActionListener(handler);
              btn3.addActionListener(handler);
         public static void main(String[] args)
              W6P1 window = new W6P1();
              window.setSize(300, 100);
              window.setVisible(true);
              window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         //create the inner class
         private class ButtonHandler implements ActionListener
              public void actionPerformed(ActionEvent e)
                   if (e.getSource() == btn1)I'm really confused what to do next.

    I already start my programm.
    on the top i wrote what i have to do (Add action listeners to the left button <one> and the right button <three> and add code to rotate the labels of the buttons every time a button is pressed. If the left button is pressed the labels rotate to the left (from <one>, <two>, <three> they will become <two>, <three>, <one>, press it again and they become <three>, <one>, <two>; press it for a third time and they become as before <one> <two> <three>.
    Similar operation is required when the right button (<three>) is clicked but this time the rotation will take place right-wise.)
    I made the window with my buttons, i set the visibility, i set the size but i cant understand how i'm gonna set the button 1 move on position left each time i'm pressing it.
    Can you please tell me how and where do i have to put the mousepressed or the mouseevent.
    something like that. Execuse me if i confused you but i am confused too.

  • Can you help me with mouse pressed method please?

    hi
    can you help me with my problem please, player label doesn't show up in the applet and the draw string method it doesn't draw any strings like X or O for the game I don't know what is the problem maybe it is with MousePressed method which is in Board class. I tried to write the code of the location many times I'm not sure if the problem comes from there.
    there is no error in my code, but it doesn't work.
    this is class Board which has the mouseListener
    class Board extends JPanel  implements MouseListener, MouseMotionListener
        private JLabel playerlabel; 
         private boolean play;
         private boolean start;
        private int turn; 
        private Square squares[][];
      private Player myplayer[][];
         public Board()
              setBackground( Color.WHITE );
              playerlabel = new JLabel( "X player first" );
              //playerlabel.setLayout(null);
         //     playerlabel.setLocation(500,500);
              add( playerlabel );
              play = true;
              turn = 1;
             squares = new Square[3][3];
             myplayer = new Player[3][3];
             int x = 40;
              int y = 40;
              for (int i=0; i<3; i++){
                   x = 40;
                   for (int j=0; j<3; j++){
                        Square s = new Square( x,y );
                        squares[i][j] = s;
                        x +=50;
                   y +=50;
                this.addMouseListener(this);
            this.addMouseMotionListener(this);
          public void mouseClicked( MouseEvent event ){}
          public void mouseMoved( MouseEvent event ){}
          public void mouseEntered( MouseEvent event ){}
          public void mouseExited( MouseEvent event ){}
          public void mousePressed( MouseEvent event )
          {int xPos = event.getX();
                  int yPos = event.getY();
                    if(play && turn ==1){
                    for (int i=0; i<3; i++){
                        for (int j=0; j<3; j++){
                             int x = squares[i][j].getX();
                             int y = squares[i][j].getY();
                             if(xPos> x && xPos<x+40&& yPos> y && yPos<y+40){
                                  if( squares[i][j].getOccupied() ==0 ){
                                       String ptext;
                                       ptext = "X";
                                       Player p = new Player(x, y,ptext);
                                       myplayer[i][j] = p;
                                       squares[i][j].setOccupied(1);
                                       playerlabel.setText( "O Player Turn" );
                                       turn = 2;
                                       repaint();
                                       Win();
                                  else{
                                       turn = 2;
                                       playerlabel.setText( "O Player Turn" );
                                       repaint();
              if ( play && turn ==2 )
    for (int i=0; i<3; i++){
                        for (int j=0; j<3; j++){
                             int x = squares[i][j].getX();
                             int y = squares[i][j].getY();
                             if(xPos> x && xPos<x+40&& yPos> y && yPos<y+40){
                                  if( squares[i][j].getOccupied() ==0 ){
                                       String ptext;
                                       ptext = "O";
                                       Player p = new Player(x, y,ptext);
                                       myplayer[i][j] = p;
                                       squares[i][j].setOccupied(2);
                                       playerlabel.setText( "X Player Turn" );
                                       turn = 1;
                                       repaint();
                                       Win();
                                  else{
                                       turn = 1;
                                       playerlabel.setText( "X Player Turn" );
                                       repaint();
          public void mouseReleased( MouseEvent event )
          public void mouseDragged( MouseEvent event )
         public void Win(){
              if(squares[0][0].getOccupied() == squares[0][1].getOccupied() &&squares[0][1].getOccupied()==squares[0][2].getOccupied() &&squares[0][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else if (squares[1][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[1][2].getOccupied() &&squares[1][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else      if(squares[2][0].getOccupied() == squares[2][1].getOccupied() &&squares[2][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
                   if(squares[0][0].getOccupied() == squares[0][1].getOccupied() &&squares[0][1].getOccupied()==squares[0][2].getOccupied() &&squares[0][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else if (squares[1][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[1][2].getOccupied() &&squares[1][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else      if(squares[2][0].getOccupied() == squares[2][1].getOccupied() &&squares[2][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              //Vertically win
               if (squares[0][0].getOccupied() == squares[1][0].getOccupied() &&squares[1][0].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else if (squares[0][1].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][1].getOccupied() &&squares[2][1].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else      if(squares[0][2].getOccupied() == squares[1][2].getOccupied() &&squares[1][2].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
               if (squares[0][0].getOccupied() == squares[1][0].getOccupied() &&squares[1][0].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else if (squares[0][1].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][1].getOccupied() &&squares[2][1].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else      if(squares[0][2].getOccupied() == squares[1][2].getOccupied() &&squares[1][2].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              //Diagonal win
                    if (squares[0][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else if (squares[0][2].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
               if (squares[0][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else if (squares[0][2].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
         }//end win
    public void setTurn(int t)
              turn = t;
              playerlabel.setText( "X Player Plays First" );
         public void paintComponent( Graphics g )
               super.paintComponent( g );
               this.setBackground( Color.WHITE );
              for (int i=0; i<3; i++){
                   for (int j=0; j<3; j++){
                        g.setColor( Color.BLACK );
                         g.drawRect( squares[i][j].getX(), squares[i][j].getY(), 50, 50 );     
               for (int i=0; i<3; i++){
                   for (int j=0; j<3; j++){
                         myplayer[i][j].draw(g);     
            //End of paintComponent   
    }and this is the whole code of my program.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    class Player{
         private int xCoordinate;
         private int yCoordinate;
        private String playerText;
      public   Player(int x, int y, String t)
            playerText = t;
            xCoordinate = x;
            yCoordinate = y;
        public void draw(Graphics g)
               g.drawString(playerText,  xCoordinate, yCoordinate);
         public void SetText(String t)
         { playerText = t;
    }//end player
    class Square
         private int x;
         private int y;
         private int occupied;
         public Square(int x1, int y1)
              x = x1;
              y= y1;
              occupied = 0;
         public void setX(int x1)
              x = x1;
         public int getX()
              return x;
         public void setY(int y1)
              y = y1;
         public int getY()
              return y;
         public void setOccupied(int o)
              occupied = o;
         public int getOccupied()
              return occupied;
    public class TicTac extends JApplet implements ActionListener
    { private JPanel panel;
         private JButton newgame;
         private Board B;
         public void init()
              B = new Board();
              add( B, BorderLayout.CENTER );
              panel = new JPanel();
               newgame = new JButton( "New Game" );
               panel.add( newgame);
               add( panel, BorderLayout.SOUTH );
               newgame.addActionListener(this);
              public void actionPerformed( ActionEvent ev)
               {     Object source = ev.getSource();
         if (source == newgame)
                    {remove(B);
                   repaint();
              B = new Board();
                   add( B, BorderLayout.CENTER );
         B.setTurn(1);
                   repaint();
                   validate();
            }//end class TicTac
    class Board extends JPanel  implements MouseListener, MouseMotionListener
        private JLabel playerlabel; 
         private boolean play;
         private boolean start;
        private int turn; 
        private Square squares[][];
      private Player myplayer[][];
         public Board()
              setBackground( Color.WHITE );
              playerlabel = new JLabel( "X player first" );
              //playerlabel.setLayout(null);
         //     playerlabel.setLocation(500,500);
              add( playerlabel );
              play = true;
              turn = 1;
             squares = new Square[3][3];
             myplayer = new Player[3][3];
             int x = 40;
              int y = 40;
              for (int i=0; i<3; i++){
                   x = 40;
                   for (int j=0; j<3; j++){
                        Square s = new Square( x,y );
                        squares[i][j] = s;
                        x +=50;
                   y +=50;
                this.addMouseListener(this);
            this.addMouseMotionListener(this);
          public void mouseClicked( MouseEvent event ){}
          public void mouseMoved( MouseEvent event ){}
          public void mouseEntered( MouseEvent event ){}
          public void mouseExited( MouseEvent event ){}
          public void mousePressed( MouseEvent event )
          {int xPos = event.getX();
                  int yPos = event.getY();
                    if(play && turn ==1){
                    for (int i=0; i<3; i++){
                        for (int j=0; j<3; j++){
                             int x = squares[i][j].getX();
                             int y = squares[i][j].getY();
                             if(xPos> x && xPos<x+40&& yPos> y && yPos<y+40){
                                  if( squares[i][j].getOccupied() ==0 ){
                                       String ptext;
                                       ptext = "X";
                                       Player p = new Player(x, y,ptext);
                                       myplayer[i][j] = p;
                                       squares[i][j].setOccupied(1);
                                       playerlabel.setText( "O Player Turn" );
                                       turn = 2;
                                       repaint();
                                       Win();
                                  else{
                                       turn = 2;
                                       playerlabel.setText( "O Player Turn" );
                                       repaint();
              if ( play && turn ==2 )
    for (int i=0; i<3; i++){
                        for (int j=0; j<3; j++){
                             int x = squares[i][j].getX();
                             int y = squares[i][j].getY();
                             if(xPos> x && xPos<x+40&& yPos> y && yPos<y+40){
                                  if( squares[i][j].getOccupied() ==0 ){
                                       String ptext;
                                       ptext = "O";
                                       Player p = new Player(x, y,ptext);
                                       myplayer[i][j] = p;
                                       squares[i][j].setOccupied(2);
                                       playerlabel.setText( "X Player Turn" );
                                       turn = 1;
                                       repaint();
                                       Win();
                                  else{
                                       turn = 1;
                                       playerlabel.setText( "X Player Turn" );
                                       repaint();
          public void mouseReleased( MouseEvent event )
          public void mouseDragged( MouseEvent event )
         public void Win(){
              if(squares[0][0].getOccupied() == squares[0][1].getOccupied() &&squares[0][1].getOccupied()==squares[0][2].getOccupied() &&squares[0][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else if (squares[1][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[1][2].getOccupied() &&squares[1][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else      if(squares[2][0].getOccupied() == squares[2][1].getOccupied() &&squares[2][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
                   if(squares[0][0].getOccupied() == squares[0][1].getOccupied() &&squares[0][1].getOccupied()==squares[0][2].getOccupied() &&squares[0][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else if (squares[1][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[1][2].getOccupied() &&squares[1][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else      if(squares[2][0].getOccupied() == squares[2][1].getOccupied() &&squares[2][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              //Vertically win
               if (squares[0][0].getOccupied() == squares[1][0].getOccupied() &&squares[1][0].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else if (squares[0][1].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][1].getOccupied() &&squares[2][1].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else      if(squares[0][2].getOccupied() == squares[1][2].getOccupied() &&squares[1][2].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
               if (squares[0][0].getOccupied() == squares[1][0].getOccupied() &&squares[1][0].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else if (squares[0][1].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][1].getOccupied() &&squares[2][1].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else      if(squares[0][2].getOccupied() == squares[1][2].getOccupied() &&squares[1][2].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              //Diagonal win
                    if (squares[0][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else if (squares[0][2].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
               if (squares[0][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else if (squares[0][2].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
         }//end win
    public void setTurn(int t)
              turn = t;
              playerlabel.setText( "X Player Plays First" );
         public void paintComponent( Graphics g )
               super.paintComponent( g );
               this.setBackground( Color.WHITE );
              for (int i=0; i<3; i++){
                   for (int j=0; j<3; j++){
                        g.setColor( Color.BLACK );
                         g.drawRect( squares[i][j].getX(), squares[i][j].getY(), 50, 50 );     
               for (int i=0; i<3; i++){
                   for (int j=0; j<3; j++){
                         myplayer[i][j].draw(g);     
            //End of paintComponent   
            Edited by: mshadows on May 18, 2008 7:53 AM

    I was playing with this a little bit and came up with this game model, something that I'm sure can be improved upon greatly:
    TttXO.java
    an enum to encapsulate X vs O. I could use a boolean here since it has 2 states, but this seems more intuitive to me
    package dy08.m05.ttt;
    * tic tac toe encapsulation of X vs O
    * @author Pete
    public enum TttXO
        X, O
    }TttCell.java
    encapsulates an individual cell in the tictactoe grid.
    package dy08.m05.ttt;
    * Tic Tac Toe Game cell
    * can be occupied or not
    * can hold TttXO X or O or null 
    * @author Pete
    public class TttCell
        private boolean occupied = false;
        private TttXO xo = null;
        public TttCell()
         * sets a Square for either x or o
         * @param TttXO
         * @return true if successful, false if already occupied
        public boolean setXO(TttXO xo)
            if (occupied)
                return false;
            else
                occupied = true;
                this.xo = xo;
                return true;
        public void reset()
            occupied = false;
            xo = null;
        public boolean isOccupied()
            return occupied;
        public TttXO getXO()
            return xo;
        // used to test and debug the class
        public String toString()
            if (occupied)
                return xo.toString();
            else
                return "-";
    package dy08.m05.ttt;
    * Tic Tac Toe game model
    * @author Pete
    public class TttGameModel
        private TttCell[][] cellGrid = new TttCell[3][3];
        private boolean xTurn = true;
        private boolean win = false;
        public TttGameModel()
            for (int i = 0; i < cellGrid.length; i++)
                for (int j = 0; j < cellGrid.length; j++)
    cellGrid[i][j] = new TttCell();
    public void reset()
    xTurn = true;
    win = false;
    for (int i = 0; i < cellGrid.length; i++)
    for (int j = 0; j < cellGrid[i].length; j++)
    cellGrid[i][j].reset();
    public boolean isXTurn()
    return xTurn;
    public boolean isWin()
    return win;
    * @param row
    * @param col
    * @return true if valid move, false if game already over or cell occupied
    public boolean takeTurn(int col, int row)
    TttXO currentXO = TttXO.O;
    TttCell cell = cellGrid[row][col];
    if (win)
    return false;
    if (cell.isOccupied())
    return false;
    if (xTurn)
    currentXO = TttXO.X;
    cell.setXO(currentXO);
    win = checkWin(col, row, currentXO);
    xTurn = !xTurn; // toggle xturn
    return true;
    public boolean checkWin(int col, int row, TttXO xo)
    boolean win = false;
    // first rows and columns
    boolean temp = true;
    for (int i = 0; i < 3; i++)
    temp &= cellGrid[row][i].getXO() == xo;
    win |= temp;
    temp = true;
    for (int i = 0; i < 3; i++)
    temp &= cellGrid[i][col].getXO() == xo;
    win |= temp;
    if (row == col) // if slash diagonal
    temp = true;
    for (int i = 0; i < 3; i++)
    temp &= cellGrid[i][i].getXO() == xo;
    win |= temp;
    if (row + col == 2) // if backslash diagonal
    temp = true;
    for (int i = 0; i < 3; i++)
    temp &= cellGrid[i][2 - i].getXO() == xo;
    win |= temp;
    return win;
    // used to test and debug the class
    public String toString()
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < cellGrid.length; i++)
    for (int j = 0; j < cellGrid[i].length; j++)
    sb.append(cellGrid[i][j] + " ");
    sb.append("\n");
    if (win)
    sb.append("win! Game over");
    else
    sb.append("No winner yet");
    return sb.toString();
    // test the class
    public static void main(String[] args)
    TttGameModel model = new TttGameModel();
    checkMove(model, 0, 0);
    checkMove(model, 1, 0);
    checkMove(model, 1, 1);
    checkMove(model, 2, 0);
    checkMove(model, 1, 0); // bad move
    checkMove(model, 2, 2);
    // to test the class
    private static void checkMove(TttGameModel model, int i, int j)
    System.out.println("OK move: " + model.takeTurn(i, j));
    System.out.println(model + "\n");

  • JTree select on mouse release

    How can I force a JTree to change selection on a mouse release rather than the mouse press?
    Background - I have a component that uses a JTree as a navigation device - click on a node in the tree and the right side of the GUI shows a particular panel. Some panels allow user to drag a node from the navigation tree into the panel on the right side. The drag and drop is working fine, except that when a node in the tree is clicked, it changes which panel is showing and the place that I wanted to drag to is no longer visible.
    I've temporarily worked around it by adding a "locked" checkbox to the navigation tree, so that if the checkbox is locked then I just set the tree selection back to what it was when the selection changes. This is not very user friendly. Ideally, I'd like the selection in the tree to change only when the mouse is released. Alternately, I could live with only starting a drag when the CTRL key was pressed or something similar.

    mclabo01 wrote:
    How can I force a JTree to change selection on a mouse release rather than the mouse press?This is what I might try:
    -- use getMouseListeners to save the array of MouseListener[] to an instance field
    -- iterate over the array and removeMouseListener all of them
    -- add a single MouseListener
    ---- in mouseReleased, construct a new MouseEvent from the ME received as parameter, changing the ID from MOUSE_RELEASED to MOUSE_PRESSED
    ---- iterate over the array and invoke mousePressed on each listener with the constructed event
    May work, may not. And you may have to collect the MouseListeners after the tree is made visible.
    db
    edit It appears there's no need to modify the MouseEvent. Proof of concept (may need some tuning for different treatment of each mouse button):import java.awt.event.*;
    import javax.swing.*;
    public class MouseReleaseSelectTree {
      MouseListener[] listeners;
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            new MouseReleaseSelectTree().makeUI();
      public void makeUI() {
        JTree tree = new JTree();
        listeners = tree.getMouseListeners();
        for (MouseListener listener : listeners) {
          tree.removeMouseListener(listener);
        tree.addMouseListener(new MouseAdapter() {
          @Override
          public void mouseClicked(MouseEvent e) {
            for (MouseListener listener : listeners) {
              listener.mouseClicked(e);
          @Override
          public void mousePressed(MouseEvent e) {
          @Override
          public void mouseReleased(MouseEvent e) {
            for (MouseListener listener : listeners) {
              listener.mousePressed(e);//pressed);
          @Override
          public void mouseEntered(MouseEvent e) {
            for (MouseListener listener : listeners) {
              listener.mouseEntered(e);
          @Override
          public void mouseExited(MouseEvent e) {
            for (MouseListener listener : listeners) {
              listener.mouseExited(e);
        JFrame frame = new JFrame();
        frame.add(new JScrollPane(tree));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }Edited by: DarrylBurke

  • Right mouse button click in a JTree leaf

    Hi,
    how can I add a mouse listener in a JTree leaf? I have DOM nodes wrapped and a JTree model adapter to set up the JTree. I want the popup menu to show everytime the user clicks on a leaf, but not on the tree itself.
    Thanks!

    Really you just have to add your listener to the tree itself, then use the Point to find the corresponding TreePath (getPathForLocation), from which you'll easily find the node.

  • Getting the time interval of a mouse being pressed

    Hai
    I am developing an image scrolling application .And i have a JButton to scroll the image . The problem is that i need to scroll the image proportional to the time the user presses the button.
    How can i do it ?
    Thanks in advance

    Hai
    I did it in a way which i am not sure to be apprpriate. I started a thread (defined in an innerclass) in the mouse pressed event of the button and stopped the thread in the mousereleased event .
    Any body with a different elegant idea kindly make me aware of it.
    Any one facing the same issue may try this method and give me a feedback
    Thank you

  • Popup JTree

    I created a subclass of JWindow which acts as a popup when the appropriate mousebutton is clicked. A JTree is shown in an etched border and when the user selects an item in the tree it updates the JTextField the popup is connected to. It is similar in concept to a JComboBox but rather then a list, it uses a tree. It is connected to two JTextFields in a subclass of JDialog. This works great when dialog box is run in the applet window under VAJ. However, when the dialog box is created (.show()) from within a JApplet in the browser it appears fine when the right mouse button is pressed in the appropriate JTextField but as soon as a mouse button is pressed within the popped up JTree, the popped up window (JWindow subclass) is forced behind the other window. If the roller on the microsoft mouse is used the jtree can be scrolled but if I try to manipulate the scrollbar the window disappears behind the parent window. How can I lock the window in place until I dispose of it??
    Thanks,
    Walt

    The problem is actually a problem in VAJ. The code generated by the VCE does not allow for creating the popup with a parent window. It is still unclear why when it was created on top of the 'parent' window and the scrollbar should have digested the mouse event, that the mouse event percolated through the popup to the underlying window, causing it to gain focus and be placed on top in the Z order. Anyone that can answer that one get the duke bucks too. What I did was modify the alternative constructors for the popup to initialize the window (set the listeners) which appears to be another bug in VAJ and then manually create the popup as invisible. Normally VAJ uses lazy construction to only construct the object upon first reference. Since that code is automatically regenerated by the VCE I couldn't modify it.
    Another question is why does the JWindow appear with the foolish "Java Applet Window" text in a status area. And why does a JWindow even have a status area? The drop down list of a JComboBox doesn't have one. And that was really all I wanted was a JComboBox with a tree instead of a list. So if anyone can address that, there are duke dollars available for it as well.
    So the questions are:
    1) why does the mouse action percolate through the popup window, which should have captured and digested it, even if only through the scrollbar logic?
    2) what does the JWindow based popup get stuck with the "Java Applet Window" text in an unwanted status area.
    3) how could this simply be like a JComboBox with a drop down JTree, as opposed to drop down list?
    Thanks,
    Walt

  • Multiple Selection in JTree, Drag & Drop

    Hi everybody,
    I was wondering if anyone knows how to implement Multiple Selection Drag and Drop in a JTree. I know that there used to be a bug in jdk 1.3 that would allow it, but I suspect 1.4 fixed that. I've implemented Single-selection just fine, but I'm trying do Multiple selection by drawing a selection rectangle and selecting whatever nodes are contained within that rectangle. So far I've implemented it by adding a MouseListener to my JTree, finding which rows are intersected by the rectangle and calling addSelectionRow() to add the TreePaths.
    Is there an easier way to multiple selection now that the bug of 1.3(I hope) has been fixed?

    Okay, now I've implemented the changes in the DragGestureListener, DragSourceListener and DragTargetListener in order to make Multiple Selection possible, however I want to select multiple items the same way Windows Explorer does by:
    1. pressing the left-mouse button & dragging a "selection" rectangle which selects all the nodes contained within that rectangle.
    2. then drag and drop is accomplished by pressing one of the selected nodes and dragging it (along with it's other selected siblings) to the destination.
    In order to accomplish this I added into the Constructor of my JTree extending class this code:
    public class MyTree extends JTree {
    private static int x1, y1, x2, y2;
    public MyTree(DefaultMutableTreeNode rootNode){
    // Other Constructor stuff...
    this.addMouseMotionListener( new MouseMotionListener() {
    public void mouseDragged(MouseEvent e) {  
    x2 = e.getX();
    y2 = e.getY();
    repaint();
    public void mouseMoved(MouseEvent e){     }
    this.addMouseListener(new MouseAdapter(){
    boolean dontRelease = false;
    public void mousePressed( MouseEvent e){
    x1 = e.getX();
    y1 = e.getY();
    int[] rows = getSelectionRows();
    boolean dropSel = true;
    if (rows != null){
    for (int i = 0; i < rows.length; i++){
    Rectangle rect3 = getRowBounds(i);
    if (rect3.contains(x1, y1)){
    dropSel = false;
    dontRelease = true;
    if (dropSel){
    for (int i =0; i < rows.length; i++)
    removeSelectionRow(i);
    public void mouseReleased( MouseEvent e){
    x2 = e.getX();
    y2 = e.getY();
    repaint();
    if (dontRelease == false) {
    Rectangle rect2 = new Rectangle(Math.min(x1, x2),
    Math.min(y1, y2), Math.abs(x1-x2), Math.abs(y1-y2));
    int rowCount = getRowCount();
    for (int i = 1; i < rowCount; i++) {
    Rectangle rect3 = getRowBounds(i);
    if ((rect2.contains(rect3)) || (rect2.intersects(rect3))){
    addSelectionRow(i);
    dontRelease = false;
    repaint();
    The idea was that for every press of the mouse the 1st set of x,y coords. are taken to be the starting corner of the "selection" rectangle, and every point passed over while dragging would be the ending corner of the rectangle (so that in paintComponents, you could actually draw the rectangle).
    Once the mouse is released it will check to see if the selection rectangle had contained or intersected any of the rows (basically I find how many rows are being shown in the tree and go through each one to see if there is intersection/containment). If a row is contained it becomes selected.
    The remaining code in MousePressed is used if node(s) were previously selected it goes through and checks to see if this mouse press is at the location of one of the previous selected nodes - if it is then you can drag that node along with all of its siblings to their destination. However if your mouse press is not on one of the selected nodes - all the nodes should be deselected (like in explorer if you press away from your selection, you lose it). If you select and begin to drag your selection dontRelease should not allow the creation of another "selection" rectangle to occur during the drag-n-drop process.
    -That's how I thought this code should work. Unfortunately as it does most of these things it does not correctly implement rule #2 of Windows Explorer (2. only by dragging one of the selected nodes can you drag them, otherwise you lose them)...currently as long as something is selected you can do a mouse press and drag from another location and as long as that location does not contain a node (like it is a blank area in the JTree), you can drag everything to the destination from when you start dragging.
    I looked around and saw that perhaps it is due to the BasicTreeUI interferring with it's own MouseInputHandler() so I wrote MyTreeUI that extends BasicTreeUI, basically changing only the MouseInputHandler to contain the functions above, and I blocked /**/ those functions from my MyTree Constructor.
    Then in my main class (the one of instantiate my MyTree and my DefaultMutableTreeNodes), I wrote:
    try
    String myTreeUI = "MyTreeUI";
    UIManager.put( "MyTreeUI", myTreeUI );
    UIManager.put( myTreeUI,
    Class.forName( myTreeUI ) );
    } catch( ClassNotFoundException cnfe ) {
    System.err.println( "My Tree UI class not found" );
    System.err.println( cnfe );
    ...thinking that that would be all I needed in order to set MyTreeUI as the JTree's UI, LooknFeel, etc. and although I did not get that ClassNotFoundException when running the program, it did not have any of the functionality that I had written ( I even wrote a System.out.println() in my MousePressed() function in MyTreeUI so that it would let me know that it is working and it never appeared). It was as if the MyTreeUI was not loaded or attached to the JTree. I also called:
    System.out.println("this is UI: " + jTree1.getUIClassID() );
    to see which UI my MyTree instantiate was using and it would printout TreeUI, not MyTreeUI. So I'm wondering what it is I'm doing wrong, I think I am very close to having this thing working but I want to know if anybody here would be able to let me know what I'm doing wrong or what would be the best way to go about implementing this Windows Explorer Multiple Selection JTree.
    Sorry for the long-winded explanation,
    -Meddev24.

  • JTree: Cell Editor takes few click to start editing

    I have a JTree and have set the user defined renender and cell editor.
    However, user has to click continuously for some time to start the editing operation. How can I start the edit operation immediately after one click only.
    TIA
    Sachin

    ((DefaultCellEditor)myTable.getCellEditor()).setClickCountToStart(1);
    Remember that a click is a mouse press and release without moving the mouse.

  • How to preven JButton of generated actions when the user keep pressing down

    How to preven JButton of generated actions when the user keep pressing down the key or the short cut
    The code below to show the issue when the user keep pressing Alt+ O
    We want to prevent the JButton from generating multi actions just one action only
    A sample of code shows the behaviour which has to be prevented. Continue pressing "Alt +O" and you will see the standard ouptput will print time stamps
    Please notice, I am NOT interested in Mouse press which has a solution by adding a threshold ( setMultiClickThreshhold(long threshhold) on the JButton  as an attribute.
    public class TestPanel extends JPanel
       private JButton btn;
       public TestPanel()
          btn = new JButton("Open");
          this.add(btn);
          registerCommand(new MyAction(), InputEvent.ALT_MASK,
                KeyEvent.VK_O, btn, btn.getText(), 0);
       public static void registerCommand(AbstractAction action,
             int mask,
             int shortCommand,
             JComponent component,
             String actionName,
             int mnemonicIndex)
          InputMap inputMap = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
          KeyStroke knappKombination = KeyStroke.getKeyStroke(shortCommand, mask);
          if ((component instanceof AbstractButton)
                && mnemonicIndex >= 0
                && mnemonicIndex < actionName.length()
                && (shortCommand >= KeyEvent.VK_A && shortCommand <= KeyEvent.VK_Z))
             ((AbstractButton) component).setDisplayedMnemonicIndex(mnemonicIndex);
          if (inputMap != null)
             ActionMap actionMap = component.getActionMap();
             inputMap.put(knappKombination, actionName);
             if (actionMap != null)
                actionMap.put(actionName, action);
       public static class MyAction extends AbstractAction
          private static final long serialVersionUID = 1L;
          @Override
          public void actionPerformed(ActionEvent e)
             System.out.println(System.currentTimeMillis());
       public static void main(String... args)
          SwingUtilities.invokeLater(new Runnable()
             public void run()
                JFrame frame = new JFrame("Testing");
                JPanel panel = new TestPanel();
                frame.getContentPane().add(panel);
                frame.setPreferredSize(new Dimension(500, 500));
                frame.setMinimumSize(new Dimension(500, 500));
                frame.pack();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
    }Edited by: user12130673 on 2013-feb-13 03:01

    Use KeyStroke getKeyStroke(int keyCode, int modifiers, boolean onKeyRelease) with onKeyRelease=true instead?

Maybe you are looking for