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);
});

Similar Messages

  • At runtime, can it be determined if multiple overlapping objects/layers exist beneath a mouse click?

    Hi folks - total nube here. I am trying to find out whether I can determine if multiple objects exist beneath a usr's mouse click coordinates. The objects will be either shaded areas under a LineSeries in a chart or possibly overlayed images representing such areas (not sure which approach would be better). I know that I can probably determine alebraically whether the coordinates selected b a mouse click belong under one series or another or multiple and if this is the best option, then I will proceed with it. But possibly, there is a way for me to determine whether a shaded area under a series or a grpahical element exists under those coordinates. Any hints? Thanks in advance.

    Yes, export it for your reference first. make it delete and create new one.
    hope it should work fine.
    thx
    Deep

  • Listening for bubble-clicked event on trayicon

    i'm trying to listen to mouse clicks on balloon messages that are displayed when you call TrayIcon#displayMessage.
    i added an action listener (TrayIcon#addActionListener), which gets called, but it also gets called when you double-click
    on the tray icon itself, so i want to differentiate between clicking on a balloon message and double-clicking on the tray icon.
    its basically the same question as in two previous threads, but one of the administrators (DarrylBurke) said i needed to create a new thread.
    http://forums.sun.com/thread.jspa?threadID=5284529&tstart=0
    http://forums.sun.com/thread.jspa?threadID=5403857&tstart=0
    any ideas appreciated.

    a code sample doesn't help when the functionality of a balloon action listener doesn't exist.
    anyhow, it looks like the original jdesktop project had the concept of adding a balloon listener:
    http://download.java.net/javadesktop/swinglabs/releases/0.8/docs/api/org/jdesktop/jdic/tray/TrayIcon.html
    specifically method TrayIcon#addBalloonActionListener, which lets one listen for interaction with a balloon message.
    looks like that functionality was lost/not added to the java.awt version of the system tray class.

  • Adobe plugin For Mouse Click Event Handler

    Hi All, How to write plugin For Mouse Click Event Handler? Please reply quickly..
    Thanks in Advance

    AS has already been replied to you on the other threads.
    THE ACROBAT SDK has all the information you need to implement your solution. If you investigate the SDK and find a specific part of implementing your solution that is causing a problem. Then post that specific problem on the forum so that Leonard/PDL/ Aandi/Everyone else, can help you with specific problems.
    This question is too open ended for it to be easily answered with out doing a lot of work.
    Please download the SDK.
    Investigate the Documentation/Samples.
    Start developing your plug-in. ( I would recommend the Acrobat-plug-in wizard)
    And if you hit a specific problem we will be happy to try and help.
    Please note MULTIPLE POSTS just annoy.
    HTH
    Malky

  • Integrating code for mouse click!

    Hello!
    I'm trying to get this code working where I want to integrate a shortcut for clicking an button made in Egde Animate.
    The code snippets you see is just some copied areas of the whole working code,
    Serial.print(c);
            if (c == '\n') {
              if (readString.indexOf("?") <0)
                //do nothing
              else
                 if(readString.indexOf("UP=UP") >0)
                     movetiltupstep();
    // now output HTML data starting with standard header
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/html");
              client.println();
              //set background to green
              client.print("<body style=background-color:green>");
              client.println("<hr />");
              client.println("<center>");
              client.println("<h1>Servo control</h1>");
              client.println("<form method=get name=SERVO>");
              client.println("<input type=submit value=UP name=UP style=\"width:100px\"><br>");
              client.println("<input type=submit value=LT name=LT style=\"width:100px\"><input type=submit value=CN name=CN style=\"width:100px\"><input type=submit value=RT name=RT style=\"width:100px\"><br>");
              client.println("<input type=submit value=DN name=DN style=\"width:100px\">");
              client.println("</form>");
              client.println("</center>");
              client.println("</body></html>");
              //clearing string for next read
              readString="";
              //stopping client
              client.stop();
    void movetiltupstep(){
      tiltpos = tilt.read();
      Serial.println(tiltpos);
      if (tiltpos >= 66)
      tilt.write(tiltpos - 2);
    This is just an overview of my setup for a webpage, where I can move a servo with a button and this is called movetiltupstep();
    The button is made here, ("<input type=submit value=UP name=UP style=\"width:100px\"><br>"); and I want to use this with the button in Edge Animate.
    For a button this is the setup, function(sym, e) and I tried to integrate something like this:
    // insert code for mouse click here
    sym.$("<input type=submit value=UP name=UP>")  but not working.
    How would i proceed with this problem, ideas anyone?
    Regards, Tor

    import javax.swing.*;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import java.awt.*;
    public class MouseTracker extends JFrame implements MouseListener, MouseMotionListener
        private JLabel statusBar;
        public MouseTracker()
            super("Demonstrating Mouse Events");
            statusBar = new JLabel();
            getContentPane().add(statusBar, BorderLayout.SOUTH);
            addMouseListener(this);
            addMouseMotionListener(this);
            setSize(275, 100);
            setVisible(true);
        public static void main(String[] args)
            MouseTracker application = new MouseTracker();
            application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public void mouseClicked(MouseEvent e)
            statusBar.setText("Clicked at [" + e.getX() + ", " + e.getY() + "]");
        public void mouseReleased(MouseEvent e)
            statusBar.setText("Released at [" + e.getX() + ", " + e.getY() + "]");
        public void mouseEntered(MouseEvent e)
            statusBar.setText("Clicked at [" + e.getX() + ", " + e.getY() + "]");
            getContentPane().setBackground(Color.GREEN);
        public void mousePressed(MouseEvent e)
            statusBar.setText("Pressed at [" + e.getX() + ", " + e.getY() + "]");
        public void mouseExited(MouseEvent e)
            statusBar.setText("Mouse outside window");
            getContentPane().setBackground(Color.WHITE);
        public void mouseDragged(MouseEvent e)
            statusBar.setText("Dragged at [" + e.getX() + ", " + e.getY() + "]");
        public void mouseMoved(MouseEvent e)
            statusBar.setText("Moved at [" + e.getX() + ", " + e.getY() + "]");
    }

  • How do you go to marker  when there is a wait for mouse click between the markers?

    I cant seem to get by the wait for mouse click, when using                          go to (marker)
    I have a game that I have 2 push buttons one is
    on mouseUp me
      go to frame 9
    end
    on mouseUp me
       go to frame  29
    end
    There is a wait to click in between these 2  frames and when I click on the  2nd button to go to frame 29  it stops at the wait to click?
    I have tried  all these below and cant get past the click to wait?????
    go
    go to frame
    go to marker
    _movie.go
    _movie.marker
    _nextMarker=

    Think this issue is resolved but to ensure the full answer is available, here it is.
    First, it's a bad idea to use the Tempo channel at all. You can use a script to do anything that you can do there. I have Lingo alternates to the Tempo channel at:
    http://www.deansdirectortutorials.com/Lingo/tempoLingo.htm
    (think I need to update this page though)
    So - DO NOT USE the Tempo Channel setting - Wait for Mouse Click or Key Press.
    The above setting creates a type of pause that interferes with other interactivity.
    Instead - use a 'Hold on Frame' behavior (from the Library Palette - Navigation category) or it could be written as:
    on exitFrame
    go the frame
    end
    Once you have the above behaviour in you desired frame, you can attach a sprite behaviour to your buttons / links. A good one to use is the ‘Jump to Marker Button’ behaviour in the Controls category of the Library Palette. You can attach this behavior to different sprites and just change the marker setting of the behavior, removing the need to have individual hard-coded scripts for each button.
    Next – DO NOT link to frame numbers. Always link to a marker. You may insert or remove frames. This would cause your incorrect links since the frame number would no longer the right point.
    Next – the following all do the same thing:
    go to frame “markername”
    go to “markername”
    go “markername”
    So, you can leave out ‘frame’ or even ‘to’ as they are not needed. I still use ‘go to’ as it feels more natural to me (just history).
    or you could use:
    _movie.go("dean")
    Don’t use
    go to marker “markername”
    I think that did work at some point but not anymore.
    marker can be used as follows:
    go marker (-1)
    Where -1 is the amount of markers back (could be forward as well).
    Well, that gives the detailed answer to your question.
    Dean

  • How to Select  a Row in a JTable, on a right mouse click?

    Hi all!
    I need to know the Row index in a JTable, on a right mouse click?
    Executing following code, I get the "Column Number" on a mouse click
    TableColumnModel columnModel = tableView.getColumnModel();
    int viewColumn = columnModel.getColumnIndexAtX(e.getX());
    int columnIdx = tableView.convertColumnIndexToModel(viewColumn);
    Dows any body know the code that gets "rowIdx" on a mouse e.getY() method??
    Hope early response!

    int row = table.rowAtPoint( e.getPoint() );
    int column = table.columnAtPoint( e.getPoint() );

  • Jtable cell listening to mouse event source

    Hi, I have a JTable with single cell selections enabled.
    I can also get the mouseClicked event working, but the cure is worse than the illness, because every cell I click on will cause a jframe to pop-up.
    Ideally only column 0 or 1 listens to the mouseClicked event.
    Can someone please tell mehow to work that into the JTable cell (sorry for the tediously long code, its only a small part)
    import javax.swing.JComponent;
    ...lots of import...
    public class CCYTable extends JPanel
      JTable newtable;
      JLabel tableHeader;
      public CCYFrame NewFrame;
      private boolean DEBUG = false;
      private int showInfoTimer = 10000; // info tip box will pop up for this period of time...
      // if both column and row selection are enabled, then individual cell selection
      // is also enabled.
      private boolean ALLOW_COLUMN_SELECTION = true;
      private boolean ALLOW_ROW_SELECTION = true;
      private boolean clickForDetail = true; // click on cell to launch frame with detail
      protected String[] colHeaderInfo =
        {"Name of Instrument, move mouse to instrument for general detail of service.",
          ...lots of text...
      // get values from database, use an "invisible column" for unique key
      // description, conditions etc from Oracle...
      String LoC = "Letter of Credit";
       ...more variable...
      public void init()
        //setSize(300,300);
        tableHeader = new JLabel("uy or Sell", JLabel.CENTER);
        setLayout(new BorderLayout());
        newtable = new JTable(new TableDefinition())
          //Put cell info here, from Oracle CellInfo varchar2
          public String getToolTipText (MouseEvent mevt)
            String info = null;
            java.awt.Point p = mevt.getPoint();
            int rowIndex = rowAtPoint(p);
            int colIndex = columnAtPoint(p);
            int realColIndex = convertColumnIndexToModel(colIndex);
            Object currentValue = getValueAt(rowIndex, colIndex);
            if (realColIndex == 0)
            { if (currentValue.equals(LoC))
              { info = "Click to read general description of our \"" + LoC + "\" service." ;
              ... ideally I would like to work the mouseClicked listener in here but... 
            return info;
          } // end of JComponent's method getToolTipText
          //Put table header info
          protected JTableHeader createDefaultTableHeader()
            return new JTableHeader(columnModel)
              public String getToolTipText(MouseEvent mevt)
                String tip = null;
                java.awt.Point p = mevt.getPoint();
                int index = columnModel.getColumnIndexAtX(p.x);
                int realIndex = columnModel.getColumn(index).getModelIndex();
                return colHeaderInfo[realIndex];
        if (clickForDetail)
          newtable.addMouseListener(new MouseAdapter()
            public void mouseClicked(MouseEvent mevt)
              { // ...but JTable wants it like this...
                // launch a new pop-up to replace the tool tip box
                NewFrame = new CCYFrame("blabla");
        ToolTipManager.sharedInstance().setDismissDelay(showInfoTimer);
        newtable.setPreferredScrollableViewportSize(new Dimension(770, 350));
        JScrollPane scrollpane = new JScrollPane(newtable);
        initColumnSizes(newtable);
        enableCellSelection(newtable);
        add("North", tableHeader);
        add("Center", scrollpane);
       * For sizing columns. If all column heads are wider than the column-cells'
       * contents, then just use column.sizeWidthToFit().
      private void initColumnSizes(JTable newtable)
        TableDefinition tblmodel = (TableDefinition)newtable.getModel();
        TableColumn column = null;
        Component comp = null;
        int headerWidth=0, cellWidth=0;
        Object[] longValues = tblmodel.longValues;
        TableCellRenderer headerRenderer = newtable.getTableHeader().getDefaultRenderer();
        TableCellRenderer rightRenderer = new RightRenderer();
        for (int i = 0; i < 7; i++)
          column = newtable.getColumnModel().getColumn(i);
          comp = headerRenderer.getTableCellRendererComponent(
                                 null, column.getHeaderValue(),
                                 false, false, 0, 0);
          headerWidth = comp.getPreferredSize().width;
          comp = newtable.getDefaultRenderer(tblmodel.getColumnClass(i)).
                          getTableCellRendererComponent(
                                 newtable, longValues,
    true, true, 0, i);
    cellWidth = comp.getPreferredSize().width;
    column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    TableColumn col2 = newtable.getColumnModel().getColumn(2);
    col2.setCellRenderer( rightRenderer );
    TableColumn col2Width = newtable.getColumnModel().getColumn(2);
    col2Width.setPreferredWidth(2);
    TableColumn col6 = newtable.getColumnModel().getColumn(6);
    col6.setCellRenderer( rightRenderer );
    TableColumn col6Width = newtable.getColumnModel().getColumn(6);
    col6Width.setPreferredWidth(2);
    }// end of method initColumnSizes
    private void enableCellSelection(JTable newtable)
    if (ALLOW_COLUMN_SELECTION)
    if (ALLOW_ROW_SELECTION) {newtable.setCellSelectionEnabled(true);}
    newtable.setColumnSelectionAllowed(true);
    ListSelectionModel colSM = newtable.getColumnModel().getSelectionModel();
    colSM.addListSelectionListener(new ListSelectionListener()
    public void valueChanged(ListSelectionEvent lsevt)
    if (lsevt.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)lsevt.getSource();
    if (lsm.isSelectionEmpty()) {}
    else
    //int selectedCol = lsm.getMinSelectionIndex();
    //NewFrame = new CCYFrame("more blabla!");
    }//end of method enableCellSelection
    ...a lot of code follows...
    TIA :-)

    Hi, thanks for the tip, but I get following compile-time error:
    <identifier> expected
    newtable.addMouseListener(new MouseAdapter()
    .............................................^
    package newtable does not exist
    newtable.addMouseListener(new MouseAdapter()
    ...............^
    2 errors
    And here is how I've modified the code :
    public class CCYTable extends JPanel
      JTable newtable;
      ...lots of variables...
      private boolean ALLOW_COLUMN_SELECTION = true;
      private boolean ALLOW_ROW_SELECTION = true;
      private boolean clickForDetail = true; // click on cell to launch frame with detail
      protected String[] colHeaderInfo =
        {"Name of Instrument, move mouse to instrument for general detail of service.",
          ...lots of text for tooltipbox...
      // get values from database, use an "invisible column" for unique key
      // description, conditions etc from Oracle...
       ...lots more String variables...
      public void init()
        //setSize(300,300);
        tableHeader = new JLabel("Bids and Offers", JLabel.CENTER);
        setLayout(new BorderLayout());
        newtable = new JTable(new TableDefinition())
          //Put cell info here, from Oracle CellInfo varchar2
          public String getToolTipText (MouseEvent mevt)
            String info = null;
            java.awt.Point p = mevt.getPoint();
            int rowIndex = rowAtPoint(p);
            int colIndex = columnAtPoint(p);
            int realColIndex = convertColumnIndexToModel(colIndex);
            Object currentValue = getValueAt(rowIndex, colIndex);
            if (realColIndex == 0)
            { if (currentValue.equals(LoC))
              { info = "Click to read general description of our \"" + LoC + "\" service." ;
            return info;
          } // end of JComponent's method getToolTipText
          newtable.addMouseListener(new MouseAdapter()  //  HELP: compiler throws error here !!!!!!!!
            public void mouseClicked(MouseEvent e)
              java.awt.Point p = mevt.getPoint();
              int rowIndex = rowAtPoint(p);
              int colIndex = columnAtPoint(p);
              int realColIndex = convertColumnIndexToModel(colIndex);
              Object currentValue = getValueAt(rowIndex, colIndex);
              if ((rowIndex == 0) and (colIndex == 0))
                // do stuff for this particular JTable cell ...
          //Put table header info
          protected JTableHeader createDefaultTableHeader()
            return new JTableHeader(columnModel)
              public String getToolTipText(MouseEvent mevt)
                String tip = null;
                java.awt.Point p = mevt.getPoint();
                int index = columnModel.getColumnIndexAtX(p.x);
                int realIndex = columnModel.getColumn(index).getModelIndex();
                return colHeaderInfo[realIndex];
        ToolTipManager.sharedInstance().setDismissDelay(showInfoTimer);
        newtable.setPreferredScrollableViewportSize(new Dimension(770, 350));
        JScrollPane scrollpane = new JScrollPane(newtable);
        initColumnSizes(newtable);
        enableCellSelection(newtable);
        add("North", tableHeader);
        add("Center", scrollpane);
      }On the other hand, this code works after a fashion but it is not what is needed because it listens to every JTable cell :
    public class CCYTable extends JPanel
      JTable newtable;
      ...unbelievably more variable definitions, etc...
      public void init()
        //setSize(300,300);
        tableHeader = new JLabel("Bids and Offers", JLabel.CENTER);
        setLayout(new BorderLayout());
        newtable = new JTable(new TableDefinition())
          //Put cell info here, from Oracle CellInfo varchar2
          public String getToolTipText (MouseEvent mevt)
            String info = null;
            java.awt.Point p = mevt.getPoint();
            int rowIndex = rowAtPoint(p);
            int colIndex = columnAtPoint(p);
            int realColIndex = convertColumnIndexToModel(colIndex);
            Object currentValue = getValueAt(rowIndex, colIndex);
            if (realColIndex == 0)
            { if (currentValue.equals(LoC))
              { info = "Click to read general description of our \"" + LoC + "\" service." ;
                if (rowIndex == 0)  // HELP:  compiles okay but won't specifically select rowIndex == 0 and colIndex == 0
                {this.addMouseListener(new clickListener(newtable, rowIndex, colIndex));
            return info;
          } // end of JComponent's method getToolTipText
         ... lots more code...
      // ==============================
      class clickListener extends MouseAdapter
        private JTable newtable;
        private int rowIndex;
        private int colIndex;
        public clickListener(JTable newtable, int rowIndex, int colIndex)
          this.newtable = newtable;
          this.rowIndex = rowIndex;
          this.colIndex = colIndex;
        public void mouseClicked(MouseEvent mevt)
          NewFrame = new CCYFrame("blablabla");
      }// end of method clickListenerIdeally I should be able to use a selection criteria like this :
    java.awt.Point p = mevt.getPoint();
    rowIndex = rowAtPoint(p);
    colIndex=colAtPoint(p);
    if ((rowIndex == 0) && (colIndex == 0)) {//do something}but this is going to be a bad Chrissy for me?

  • Listening for mouse move from JFrame?

    Hi
    I'm facing a problem when I wanted to use the JFrame's method: addMouseListener( ) to listening for the mouse whether it moves from a JFrame.
    In my code the JFrame containts three components:
    public class NFrame extends JFrame{
    JPanel contentPane = (JPanel)super.getContentPane();
    contentPane.setLayout(new BorderLayout());
    JMenuBar jMenubar=new jMenuBar();
    JTabbedPane jTabPane=new JTabbedPane(JTabbedPane.LEFT,JTabbedPane.WRAP_TAB_LAYOUT);
    JPanel bottonPane=new JPanel();
    contentPane.add(jMenuBar,BorderLayout.NORTH);
    contentPane.add(jTabPane,BorderLayout.CENTER);
    contentPane.add(bottomPane,BorderLayout.SOUTH);
    addMouseListener(new MouseAdapter() {
    public void mouseExited(MouseEvent e) {
    System.out.println("Mouse remove from JFrame");
    Because the JTabbedPane has a default mouse Listener, thus the mouse event is caught by jTabPane and the application does not print the above message when mouse moves from jTabPane.
    Could anybody give me some hints?
    Thanks!

    In this case there should probably not be a sleep()
    at all. You might want to do that sort of thing when
    you have a new thread whose job is to have
    non-GUI-related functionality (like a clock ticking,
    or sprites moving in a game independently). For
    standard GUI interaction, the GUI thread takes care
    of things and you don't need to wait at all. You're
    already waiting, basically.Oh, I see! The OP is doing quite useless things!
    I didn't see such f**lish things in the past!
    The OP should learn the basics for GUI and event mechanism.
    http://java.sun.com/docs/books/tutorial/uiswing/

  • JTable Document Listener for JTextField editor

    hello, how can I tell if removeUpdate in DocumentListener has been triggered by the user performing a delete in a JTextField or by the user cancelling a previous edit?
    example table
    | abc | def | ghi |<- user clicks in this cell which puts it in editmode
    | jkl | mno | pqr |<- user then clicks here which triggers removeUpdate for previous cell but how do I know this?
    Regards,
    b

    hello, how can I tell if removeUpdate in DocumentListener has been triggered by the user performing a delete in a JTextField or by the user cancelling a previous edit?
    example table
    | abc | def | ghi |<- user clicks in this cell which puts it in editmode
    | jkl | mno | pqr |<- user then clicks here which triggers removeUpdate for previous cell but how do I know this?
    Regards,
    b

  • Advice to implement a mouse listener for card game

    Hi,
    I am wondering about the best way to apply a mouselistener in my card game.
    - i only want to listen for 'clicks'
    - I have a JFrame with a JPanel inside. The JPanel has a null layout and many JLabels. The JLabels are the cards, i want to listen for mouse clicks on these 'cards'
    I have seen it is not possible to apply a mouse listener to a JPanel or JLabel so is the most efficient way to apply the listener to the JFrame and then use getComponent () to determine which JLabel has been clicked ? or is there a better way ?
    any thoughts appreciated . .

    hey dubai, thanks for your quick help today, it is much appreciated !
    i know the event should provide a reference to the source, i use the toString to overide the methods in the mouseEvent object and im printing this string to the console. It gives me the correct dimensions within my JPanel of where i clicked but the source is always given as the panel name. Have you any idea why it does not return the name of the JLabel ? I checked out the Action interface, thanks, it cud be very useful to seperate the code by using this.

  • 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 ();
       }

  • Multiple buttons on a single slide each connecting to a different url

    Using a trial version of Captivate 7.  I have a handful of slides where the customer wants to open different forms via url.  I tried using a button for each link, inserting the url and using the "enter" key for each of the multiple buttons.  Works fine with the mouse but for 508 folks who tab to the URL and hit the enter key ......... I get many instances where the incorrect url is activated.  Is there a way around this without assicning a different shortcut key for buttons where thare are more than one on a single slide?     Thanks

    Welcome to AD!
    Here is an article on using multiple ipods. I suggest method 1 and steer clear of method 3.
    http://support.apple.com/kb/HT1495
    For your point #1, sharing music on same PC between users, put it in a shared library & set permissions as directed here
    http://support.apple.com/kb/HT1203
    For #2, itunes doesn't have the capability to monitor folders for new content. You'll need to get something like the free program 'itunes folder watch'.

  • Listening for click event

    I am curious, how can you have a child mxml page listen for
    an event from the parent?
    Let's say you have a button, call it 'btn1' on page1.mxml and
    you want to listen for the click event on page2.mxml. So far this
    is what I have:
    page1.mxml:
    <mx:Button id="btn1" />
    page2.mxml:
    <mx:Script>
    <![CDATA[
    private function btnListener(e:MouseEvent){
    Application.application.btn.addEventListener(MouseEvent.CLICK,
    setState(1));
    ]]>
    </mx:Script>

    "spacehog" <[email protected]> wrote in
    message
    news:glljts$g04$[email protected]..
    >I am curious, how can you have a child mxml page listen
    for an event from
    >the
    > parent?
    >
    > Let's say you have a button, call it 'btn1' on
    page1.mxml and you want to
    > listen for the click event on page2.mxml. So far this is
    what I have:
    >
    > page1.mxml:
    >
    > <mx:Button id="btn1" />
    >
    > page2.mxml:
    >
    > <mx:Script>
    > <![CDATA[
    >
    >
    > private function btnListener(e:MouseEvent){
    >
    Application.application.btn.addEventListener(MouseEvent.CLICK,
    > setState(1));
    > }
    > ]]>
    > </mx:Script>
    Check out Q3:
    http://www.magnoliamultimedia.com/flex_examples/Amys_Flex_FAQ.pdf

  • How to make component listen for a specific event of another component

    for example, i have several buttons and want them listen for a TreeSelectionEvent... in case anything selected they become active
    i don't want a JTree component activate these buttons...

    here's an overkill,
    import java.util.*;
    abstract class DoWhatever {
        public static Hashtable ht = null;
        public static Object DoWhat( String s, Object obj ) {
         if( null == ht ) {
             ht = new Hashtable();
             ht.put( ThisDoWhatever.NAME, new ThisDoWhatever() );
             ht.put( ThatDoWhatever.NAME, new ThatDoWhatever() );        
         return ( (DoWhatever) ht.get( s ) ).doWhatever( obj );
        public abstract Object doWhatever( Object obj );
    class ThisDoWhatever extends DoWhatever {
        public final static String NAME = "this";
        public Object doWhatever( Object obj ) {
         System.out.println( NAME );
         return null;
    class ThatDoWhatever extends DoWhatever {
        public final static String NAME = "that";
        public Object doWhatever( Object obj ) {
         System.out.println( NAME );
         return null;
    public class DoThisOrThat {
        public static void main( String[] args ) {
         DoWhatever.DoWhat( args[ 0 ], null );
    }

Maybe you are looking for

  • Audigy 2 ZS Platinum Pro - Not reading line 1 or any external input po

    I had my soundcard installed, but then I had to reformat a few weeks later. After I reformated, everything worked fine, I can listen to my music through the same speakers, I can use Creative Player and all that good stuff...but when I open the surrou

  • My macbook pro runs slow after install of lion

    i was wondering if anyone is having any issues after installing lion and doing the 10.7.3 update? i noticed a slow performance after i did the  update. i also added 8 gigs of memory hoping this would help, but it didnt i also formatted the drive inst

  • Inconsistencies between Balance and Line items

    Hello masters! I found some inconsistencies betwen balance and line items. I tried to solve the problem using  FAGLF03 and RFINDEX (when executing SAP retrieved: "New GL is active. GLT0 can not be adjusted") but both did not work. We have never gone

  • A/P Down Payment Invoice Item/Service Type

    Dear Experts, Just wondering why in A/P Down Payment Invoice for the Item Type, the G/L Account i can view and select the G/L Account in a List. However, in A/P Down Payment Invoice for the Service Type i ONLY can view and select the only one G/L Acc

  • Lock particular warehouse for particular item via code

    hi all, i need particular warehouse locked for particular item via code. i designed one form   header have item code and warehouse. when i press the add button warehouse locked for that particular item. Thanks & Regards Sudhir.B