Assigning mouse listener to JTableHeader

Can anyone point me to an example or know how to assign a mouselistener to the individual column headers in JTable Header?

I haven't tried to set a mouse listener for individual columns, but here is how you can set a listener for the entire header and check which column was clicked:
JTableHeader tableHeader = table.getTableHeader();
tableHeader.addMouseListener( new MouseAdapter()
     public void mouseClicked(MouseEvent e)
          TableColumnModel columnModel = table.getColumnModel();
          int column = columnModel.getColumnIndexAtX( e.getX() );
          if (e.getClickCount() == 1 && column == 0)
               do something for column 0
});

Similar Messages

  • Changing the color of text while mouse listener.

    Hi all. working on an assignment for school and I need a little hint.
    I am creating an applet to basically input names in txt blocks, and then you hit a button that will move the names to a text area. Well the instructor asked us to use a mouse listener to change the color of the labels on the txt blocks. Basically when you hover your mouse over the button it is supposed to change the color of the button (for and back ground), and change the color of the labels on the txt blocks.
    I just did a general setForground(color.blue);
    for my labels default color and it seemed to do the trick, I used the following code to try to change the color of both the buttons and the txt block labels, but only the button works.
    Please assist..
    public class Assignment2 extends java.applet.Applet implements ActionListener, MouseListener {
    public void mouseExited(MouseEvent e){
    //Colors Back
    setForeground(Color.blue);
    btnAdd.setForeground(Color.red);
    btnAdd.setBackground(Color.yellow);
    //Clear Status bar
    showStatus("");
    public void mouseClicked(MouseEvent e) {
    //empty Method
    public void mousePressed(MouseEvent e){
    //empty method
    public void mouseReleased(MouseEvent e){
    //empty method

    HI,
    Sorry for delay. I was not on my seat.
    I've modified your code and the label colors are changing now on the mouse over or out events.
    I did this only for a single label i.e. "First Name". Just have a look on the code and do the same for the rest labels.
    If u feel any problem, then revert to me.
    Bye
    (Dhananjay Singh)
    Here's Your Code
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ColorText extends java.applet.Applet implements ActionListener, MouseListener {
        //Declare components
        TextField txtName = new TextField(25);
        TextField txtLast = new TextField(25);
        TextField txtAdd = new TextField(30);
        TextField txtCity = new TextField(15);
        TextField txtState = new TextField(2);
        TextField txtZip = new TextField(10);
        Label fName = null;
        Label lName = null;
        Label address = null;
        Label citi = null;
        Label state = null;
        Label zip = null;
        Button btnAdd = new Button("Display Address");
        TextArea txaAdd = new TextArea(10, 30);
        //Declare variables
        String strName;
        String strLast;
        String strAdd;
        String strCity;
        String strState;
        String strZip;
        public void init() {
            //Create labels
            fName = new Label("First Name");
            lName = new Label("Last Name");
            address = new Label("Address");
            citi = new Label("City");
            state = new Label("State");
            zip = new Label("Zip");
            fName.addMouseListener(new MouseListener() {
                public void mouseEntered(MouseEvent e) {
                    fName.setBackground(Color.RED);
                public void mouseClicked(MouseEvent e) {
                public void mouseExited(MouseEvent e) {
                    fName.setBackground(Color.YELLOW);
                public void mousePressed(MouseEvent e) {
                public void mouseReleased(MouseEvent e) {
            setForeground(Color.blue);
            Font g = new Font("Serif", Font.BOLD, 14);
            setFont(g);
            add(fName);
            add(txtName);
            add(lName);
            add(txtLast);
            add(address);
            add(txtAdd);
            add(citi);
            add(txtCity);
            add(state);
            add(txtState);
            add(zip);
            add(txtZip);
            add(btnAdd);
            add(txaAdd);
            txtName.requestFocus();
            //Colors and Fonts
            Font fntName = new Font("Serif", Font.BOLD, 14);
            setBackground(Color.lightGray);
            txtName.setFont(fntName);
            txtName.setForeground(Color.blue);
            txtAdd.setFont(fntName);
            txtAdd.setForeground(Color.blue);
            txtLast.setFont(fntName);
            txtLast.setForeground(Color.blue);
            txtCity.setFont(fntName);
            txtCity.setForeground(Color.blue);
            txtState.setFont(fntName);
            txtState.setForeground(Color.blue);
            txtZip.setFont(fntName);
            txtZip.setForeground(Color.blue);
            btnAdd.setForeground(Color.RED);
            btnAdd.setBackground(Color.yellow);
            //listeners
            btnAdd.addActionListener(this);
            txtName.addActionListener(this);
            txtLast.addActionListener(this);
            txtAdd.addActionListener(this);
            txtCity.addActionListener(this);
            txtState.addActionListener(this);
            txtZip.addActionListener(this);
            btnAdd.addMouseListener(this);
        public void actionPerformed(ActionEvent e) {
            //Actions
            String strOutputLine; //Declare local variable
            //Assign text fields
            strName = txtName.getText();
            strLast = txtLast.getText();
            strAdd = txtAdd.getText();
            strCity = txtCity.getText();
            strState = txtState.getText();
            strZip = txtZip.getText();
            //Move variables down
            strOutputLine = strName + ("\n") + strLast + ("\n") + strAdd + ("\n") + strCity + ("\n") + strState + ("\n") + strZip + ("\n") + ("\n") ;
            //Append
            txaAdd.append(strOutputLine);
            //Clear Text Fields
            txtName.setText("");
            txtLast.setText("");
            txtAdd.setText("");
            txtCity.setText("");
            txtState.setText("");
            txtZip.setText("");
            //set focus back to Lastname
            txtName.requestFocus();
        public void mouseEntered(MouseEvent e) {
            // Changing of Button colors
            setForeground(Color.red);
            btnAdd.setForeground(Color.magenta);
            btnAdd.setBackground(Color.green);
            //Status bar text
            showStatus("Format Address into Text Area");
        public void mouseExited(MouseEvent e){
            //Colors Back
            setForeground(Color.blue);
            btnAdd.setForeground(Color.red);
            btnAdd.setBackground(Color.yellow);
            //Clear Status bar
            showStatus("");
        public void mouseClicked(MouseEvent e) {
            //empty Method
        public void mousePressed(MouseEvent e){
            //empty method
        public void mouseReleased(MouseEvent e){
            //empty method
    }(Dhananjay Singh)

  • Remove mouse listener

    hey, im using an itemStateChanged assigned to a List() and then im using a mouse listener to listen for a double click on the List(). the problem is that every time the mouse it double clicked another listener is added on top. So i need to remove it after the event is executed. If you can suggest a better way, please do, but im only a novice.
    thanks
    Pedge
    class listItemListener implements ItemListener
    public void itemStateChanged(ItemEvent event)
    mainList.addMouseListener(new MouseAdapter()
    public void mouseClicked(MouseEvent e)
    if (e.getClickCount() == 2)
    doClick();
    }// end of inner class listItemListener

    Wouldn't you just move the addMouseListener outside the ItemListener? Are you saying you want to remove the listener and then add it right back? I would guess you want:
    class listItemListener implements ItemListener
    private MouseAdapater ma;
    public listItemListener()
    ma = new MyMouseAdapter();
    mainList.addMouseListener(ma);
    public void itemStateChanged(ItemEvent event)
    // do other stuff here
    }// end of inner class listItemListener
    class MyMouseAdapter extends MouseAdapter
    public void mouseClicked(MouseEvent e)
    if (e.getClickCount() == 2)
    doClick();
    }

  • Problem with JPanel's mouse listener!

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

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

  • Why does a JButton automatically have a mouse listener registered with it?

    If I instantiate a JButton, I find there's a mouse listener already registered (see code below). Does anyone know why?
    Looking at the source code for JButton, I can't see how this is. If a create a dummy subclass of AbstractButton (of which JButton is a direct subclass) and instantiate that, it has no mouse listeners, and likewize with Button. So what is it about JButton?
    The reason I ask is that I've seen in a book on swing that you must call enableEvents(AWTEvent.MOUSE_EVENT_MASK) on a JButton if you want processMouseEvent to get executed. But it actually gets executed even if enableEvents hasn't been called, and the only reason for this is surely that there is a mouse listener registered, which there is, but why?
    Might the reason be that JButton extends Accessible?
    Code:
    JButton jb = new JButton("Dummy");
    MouseListener[] mls = (MouseListener[])(jb.getListeners(MouseListener.class));
    JOptionPane.showMessageDialog(this, (new Integer(mls.length)).toString(), "Number of Mouse Listeners", JOptionPane.INFORMATION_MESSAGE);

    Hello,
    That listener is installed by the JButton's UI. You might want to have a look at the source code of BasicButtonUI and BasicButtonListener to understand what they are used for. For example, mousePressed in BasicButtonListener is used to call setArmed on the JButton.
    My best advice is for you not to worry about this at all.

  • Adding mouse listener to the column header of a column in a JTable

    Hi
    I want to add a mouse listener to the column header of the 3rd column in a JTable. I dont find any appropriate method to do this. The code I have written to do this is below. But on using this code, the mouselistener is invoked if I click on any column header. Can anyone please help me to fix this.
    table.getTableHeader().addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    /* some actions */
    }

          table.getTableHeader().addMouseListener(new MouseAdapter(){
               public void mousePressed(MouseEvent me) {
                   int tableColumn  =table.columnAtPoint(me.getPoint());//it returns the column index
            });

  • 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.

  • JTextField Mouse Listener

    Hello,
    I am having trouble adding a Mouse Listener to a JTextField. Basically when the JTextField is clicked some actions will take place. I thought it would be the same as a normal listener but my assumption is incorrect.
    Could someone see where i am going wrong.
    Thanks
    gf.addActionListener(new ActionListener()
             public void actionPerformed(MouseEvent event ){
      public void  gf_actionPerformed(MouseEvent event)
                     //tf.getActionListeners();
                        System.out.println("YO");
                  if(e.getSource().equals(tf)){
            System.out.println("YO");
         }

    gf.addMouseListener(new MouseListener() {
             public void mouseEntered(MouseEvent me) {}
             public void mouseExited(MouseEvent me) {}
             public void mousePressed(MouseEvent me) {}
             public void mouseReleased(MouseEvent me) {}
             public void mouseClicked(MouseEvent me) {
                 System.out.println("YO");
          });

  • Need a Mouse Listener

    I have a main menu with a series of buttons, when you press a
    button, it triggers an animation for a fly-out menu with a series
    of buttons to trigger other events. Everything works fine up to
    this point.
    What I need is an independent hit area underneath the buttons
    on the fly-out menu so that when the mouse leaves the area, the
    fly-out menu will retract. The current methods require that the
    mouse be down or released, but I need a mouse listener for an
    'over' and 'out' state so that when the mouse is over the hit area,
    the fly-out menu will show and when the mouse leaves the hit area,
    the fly-out menu will retract.
    I've have googled and read and am now totally confused. Can
    anyone point me in the right direction to solve this
    problem?

    you shouldn't need setInterval, and its incorrectly set up.
    If you wanted to use a setInterval call instead of the onMouseMove
    event then you could do it as follows (but its NOT good
    programming, just providing it for illustrative purposes)
    remove the line Mouse.addListener... etc (you wouldn't do
    both an onMouseMove check and a setInterval check)
    and put in
    var ML = setInterval(mouseListener,"onMouseMove",500);
    That should work... I haven't tested it. Nor do I recommend
    it. I think you're better off with onMouseMove.
    If you are going to use the setInterval its better to change
    the name of the
    onMouseMove everywhere that it appears to something like
    onIntervalCheck just so it makes more sense to you if you
    look at it later on (or for someone else too). Using onMouseMove
    shouldn't be too demanding on the CPU - and if its noticeable it
    should only be for very short bursts.
    BTW You can also delete or comment out the trace actions...
    they were just there to help you understand how it works. Best not
    to leave them in when you do a final publish (or exclude trace
    actions in your publish settings)

  • How to add Mouse Listener

    here is my code for my current project, it is to create a platform independent way to have a windows explore like window so far I have it displaying properly and all I need to do is when the user double clicks on a file itt should open up but thats where i need help, this is not homework
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.filechooser.*;
    import javax.swing.*;
    import sun.swing.*;
    import javax.swing.plaf.*;
    import java.io.*;
    import javax.swing.filechooser.*;
    import javax.swing.plaf.*;
    import javax.swing.plaf.basic.*;
    import java.lang.reflect.*;
    import java.beans.*;
    public class FileBrowserAttempt2  extends JFrame
         static FilePane Files;
         static JPanel Details;
         static JPanel list;
         static int activeView = 0;
         JFrame f;
        FileBrowserAttempt2 a = this;
        JPopupMenu pop;
        Action[] actions;
        JFileChooser toGetFileView;
         public  FileBrowserAttempt2(final JFileChooser toGetFileView) throws Exception
               try {
             // Set System L&F
            UIManager.setLookAndFeel(
                UIManager.getSystemLookAndFeelClassName());
             } catch(Exception e)
              Files = getFilePane(toGetFileView);               
                   view = Files.getViewMenu();
                   Details = Files.createDetailsView();
                   list = Files.createList();
                   pop = Files.getComponentPopupMenu();
                   actions = Files.getActions();
              pop.remove(view);
              for(Action Comp : actions)
                   System.out.println(Comp.getValue(Comp.NAME).toString());
              Component[] ary = toGetFileView.getComponents();
              setJMenuBar(createMenuBar());
              JPanel panel = new JPanel(new BorderLayout());
              panel.add(ary[0], BorderLayout.NORTH);
              panel.add(Files, BorderLayout.CENTER);     
              add(panel);
              setDefaultCloseOperation(3);
              pack();
              show();
         // THIS IS THE MOUSE LISTENER
         private class open extends  AbstractAction
                   public void actionPerformed(ActionEvent e)
                        try{
                        Class FileBrowser = FileBrowserAttempt2.this.Files.getClass();
                        Method a = FileBrowser.getMethod("getSelectedFile");
                        System.out.println("Action");
                        File open =(File) a.invoke(null);
                        Runtime.getRuntime().exec("cmd.exe start " + open.toString());
                        }catch(Exception ex)
                             ex.printStackTrace();
         public static void main (String[] args) throws Exception
               new FileBrowserAttempt2(new JFileChooser(new File("C:/")));
         public void printAry(Object[] ary)
              for(Object Comp : ary)
                   System.out.println(Comp.toString());
         private FilePane getFilePane(JFileChooser toGetFileView)
              Component[] components = toGetFileView.getComponents();
              for(Object Comp : components)
                   if(Comp instanceof FilePane)
                        return ((FilePane)Comp);
              return null;
         final JMenu view;
        private JMenuBar createMenuBar()
             JMenuBar menuBar = new JMenuBar();
             JMenu FileMen = new JMenu("File");        
             JMenuItem Exit = new JMenuItem("Exit");
             Exit.addActionListener(new ExitListener());
             FileMen.add(Exit);
             menuBar.add(FileMen);
             menuBar.add(view);
             return menuBar;
    class ExitListener implements ActionListener
         public void actionPerformed(ActionEvent e)
                  System.exit(0);
    }and here are the methods of FilePane
    public static final java.lang.String ACTION_APPROVE_SELECTION;
        public static final java.lang.String ACTION_CANCEL;
        public static final java.lang.String ACTION_EDIT_FILE_NAME;
        public static final java.lang.String ACTION_REFRESH;
        public static final java.lang.String ACTION_CHANGE_TO_PARENT_DIRECTORY;
        public static final java.lang.String ACTION_NEW_FOLDER;
        public static final java.lang.String ACTION_VIEW_LIST;
        public static final java.lang.String ACTION_VIEW_DETAILS;
        public static final int VIEWTYPE_LIST;
        public static final int VIEWTYPE_DETAILS;
        int lastIndex;
        java.io.File editFile;
        int editX;
    javax.swing.JTextField editCell;
        protected javax.swing.Action newFolderAction;
        public sun.swing.FilePane(sun.swing.FilePane$FileChooserUIAccessor);
        public void uninstallUI();
        protected javax.swing.JFileChooser getFileChooser();
        protected javax.swing.plaf.basic.BasicDirectoryModel getModel();
        public int getViewType();
        public void setViewType(int);
        public javax.swing.Action getViewTypeAction(int);
        public void setViewPanel(int, javax.swing.JPanel);
        protected void installDefaults();
        public javax.swing.Action[] getActions();
        protected void createActionMap();
        public static void addActionsToMap(javax.swing.ActionMap, javax.swing.Action[]);
        public javax.swing.JPanel createList();
        public javax.swing.JPanel createDetailsView();
        public javax.swing.event.ListSelectionListener createListSelectionListener();
        public javax.swing.Action getNewFolderAction();
        void setFileSelected();
        public void propertyChange(java.beans.PropertyChangeEvent);
        public void ensureFileIsVisible(javax.swing.JFileChooser, java.io.File);
        public void rescanCurrentDirectory();
        public void clearSelection();
        public javax.swing.JMenu getViewMenu();
        public javax.swing.JPopupMenu getComponentPopupMenu();
        protected sun.swing.FilePane$Handler getMouseHandler();
        protected boolean isDirectorySelected();
        protected java.io.File getDirectory();
        public static boolean canWrite(java.io.File);any help would be appreciated

    Its better you create your own panel to display each of the files, than to display the first element of the 'toGetFileView.getComponents()' In this way, you can add a mouse listener to each of those elements.

  • Attaching several buttons to one mouse listener

    Attaching several buttons to one mouse listener
    I have an application which consists of a GUI form, "EntryForm," and "DataForm," a collection of variables.
    Clicking EntryForm's submit button sends the entries to DataForm.
    The submit button is attached to a mouse listener "SubmitButtonHandler"
    My Question: How can I attach an arbitrary number, up to five instances of EntryForm to ONE mouse listener?
    I have tried this:
         final SubmitButtonHandler sbh = new SubmitButtonHandler( ...
         entryForm1 = new EntryForm();
         dataForm1 = new DataForm();
              entryForm1.submitButton.addMouseListener( sbh );
         entryForm2 = new EntryForm();
         dataForm2 = new DataForm();
              entryForm2.submitButton.addMouseListener( sbh );
         entryForm3 = new EntryForm();
         dataForm3 = new DataForm();
              entryForm3.submitButton.addMouseListener( sbh );
         entryForm4 = new EntryForm();
         dataForm4 = new DataForm();
              entryForm4.submitButton.addMouseListener( sbh );
         entryForm5 = new EntryForm();
         dataForm5 = new DataForm();
              entryForm5.submitButton.addMouseListener( sbh );
         ...In the mouse listener I have tried these approaches:
         public void mouseClicked( MouseEvent e ) {
              if ( e.getSource() == entryForm1.submitButton ) {
                   System.out.println( "Clicked: entryForm1.submitButton" );
                   // send the data to dataform1
              } else if( e.getSource() == entryForm2.submitButton ) {
                   System.out.println( "Clicked: entryForm2.submitButton" );
                   // send the data to dataform2
         public void mouseClicked( MouseEvent e ) {
              if ( e.getSource() == submitButton ) {
                   if( e.getSource() == entryForm1.submitButton ) {
                   // send the data to dataform1
                   } else if( e.getSource() == entryForm2.submitButton ) {
                   // send the data to dataform2
              } else if ( e.getSource() == anotherButton ) {
                   ...In both cases, only ONE form's button registers and even that is screwy.
    Can this approach be fixed so that the mous listener can discern between the various forms, or do I have to use five sets of forms and mouse listeners?
    Many thanks in advance.

    Hi,
    Button1.addMouseListener(ourMouseListener);
    Button1.setActionCommande("This is button 1");
    Button2.addMouseListener(ourMouseListener);
    Button2.setActionCommande("This is button 2");
    In the "ourMouseListener" event method, you use this...
    if((((JButton)event.getSource()).getActionCommand()).equals("This is button 1"))
    Source code for Button1
    if((((JButton)event.getSource()).getActionCommand()).equals("This is button 2"))
    Source code for Button2
    JRG

  • Help Needed for Mouse Listener

    Ive created an item in a JPanel with a mouse listener for when it is clicked, I have a JFrame class called ScoreWindow(). What do i put into the mouse listener so that it will open up an instance of ScoreWindow().
    class MouseListener extends MouseAdapter{
            public void mouseClicked(MouseEvent e) {
        }Is the extent of my mouse listener so far (i know nearly nothing).
    The class i am adding this to is a shape drawn on a JPanel if this effects things, can you tell me what class type i need to make the item.
    Edited by: IInferno on Apr 23, 2009 3:49 PM
    Edited by: IInferno on Apr 23, 2009 4:18 PM

    So id add something like
    ScoreWindow window = new ScoreWindow;in the thing?
    this is my Network class so far which is the object i want to click to open the ScoreWindow class. I have run the ScoreWindow class already and it runs
    fine.(as far as ive coded it)
    package jeismus;
    import java.awt.*;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.Color;
    * @author Ben
    public class Network {
        public Network(JPanel s) {
            playArea = s;
            paintNetwork();
        public void paintNetwork() {
             Graphics g = playArea.getGraphics();
             Graphics2D g2 = (Graphics2D)g;
             sqr.setFrame(c, d, rectWidth, rectHeight);
             g2.draw(sqr);
             g2.dispose();
        private static class ScoreData {
          int x, y, NoteID, Octave;
          String Key, NoteDuration;
        class MouseListener extends MouseAdapter{
            public void mousePressed(MouseEvent e) {
            public void mouseClicked(MouseEvent e) {
        class MouseMotionListener extends MouseAdapter{
            public void mouseDragged(MouseEvent e) {
            public void mouseMoved(MouseEvent e) {
        public int getNetID(){
             return NetID;
        private int NetID;
        private ScoreData[] stringData;
        private double c = 200;
        private double d = 200;
        private double rectHeight = 30;
        private double rectWidth = 30;
        private double a = c + rectHeight;
        private double b = d + rectWidth;
        private int count = 0;
        private JPanel playArea;
        private Rectangle2D.Double  sqr = new Rectangle2D.Double();
        private Point2D startpoint = new Point2D.Double(a, b);
        private Point2D endpoint = new Point2D.Double(c, d);
    }

  • How to Call action Listener from Mouse Listener event

    One class (class 1)implements mouse listener and responds to a mouse events.
    As part of that response it needs to call a variable set method in another class (class 2)and also have that setMethod call it's own ActionPerformed.
    Seems the problem is I don't have aaction event to pass
    I only have a mouse event. As follows:
    class 1
    public void mousePressed(MouseEvent e) {
    int y1=Math.abs(e.getY()-y);
    this.sourceReference.setVar(y1);
    repaint();
    class 2
    int var;
    public void setVar(int y)
    var=y;
    this.ActionPerformed(?? ); //This is what I want to do
    Same question slightly different.
    From class 1 I scould first call the setVar method
    and then issue a call to class 2's ActionPerformed.
    But again I don't seem to have the proper action event e to pass it.
    Thanks

    Do you need any information from an ActionEvent that you'd be calling from the MouseEvent (ie the action command, or somethig) or can you just have the actionPerformed method just call a different method that doesn't need an ActionEvent?
    public void actionPerformed(ActionEvent e) {
    this.doActionStuff();
    public void doActionStuff() {
    // does what you want the action event to do
    Then from the mousePressed method you can just call the doActionStuff method.
    I'm not sure if this helps or not, hope it does.
    Scott

  • Hmm Mouse Listener to not be instantiated?

    I currently have 15 JButtons in my Swing Applet.
    for every JButton I added a mouse listener so I could change the foreground/background of a JTextPane on my applet depending on whether or not someone left clicked/right clicked on one of the colorized JButtons.
    how ever the result is 15 Instantiated Classes.
    is there any way to do this with out creating any instantied classes at all?
    Example of 1 of the 15 mouselisteners in my applet:
    cyanb.addMouseListener(new MouseAdapter() {
              public void mouseClicked(MouseEvent e) {
                   if (e.getModifiers() == InputEvent.BUTTON3_MASK) {
                        paneBackground.setBackground(Color.cyan);
                        MutableAttributeSet attr = new SimpleAttributeSet();
                        StyleConstants.setBackground(attr, Color.cyan);
                        inputPane.setCharacterAttributes(attr, false);
                   } else  {
                        paneForeground.setBackground(Color.cyan);
                        MutableAttributeSet attr = new SimpleAttributeSet();
                        StyleConstants.setForeground(attr, Color.cyan);
                        inputPane.setCharacterAttributes(attr, false);
         });any help on this matter would be greatly appreciated.
    thanx.

    but is there any way to do this with out creating an instantiation class? Don't worry so much about creating Objects. Creating an Action object to perform a function is perfectly valid. Here is some code from the DefaultEditorKit:
    private static final Action[] defaultActions = {
    new InsertContentAction(), new DeletePrevCharAction(),
    new DeleteNextCharAction(), new ReadOnlyAction(),
    new WritableAction(), new CutAction(),
    new CopyAction(), new PasteAction(),
    new VerticalPageAction(pageUpAction, -1, false),
         new VerticalPageAction(pageDownAction, 1, false),
    new VerticalPageAction(selectionPageUpAction, -1, true),
         new VerticalPageAction(selectionPageDownAction, 1, true),
    new PageAction(selectionPageLeftAction, true, true),
         new PageAction(selectionPageRightAction, false, true),
    new InsertBreakAction(), new BeepAction(),
    new NextVisualPositionAction(forwardAction, false, SwingConstants.EAST),
    new NextVisualPositionAction(backwardAction, false, SwingConstants.WEST),
    new NextVisualPositionAction(selectionForwardAction, true, SwingConstants.EAST),
    new NextVisualPositionAction(selectionBackwardAction, true, SwingConstants.WEST),
    new NextVisualPositionAction(upAction, false, SwingConstants.NORTH),
    new NextVisualPositionAction(downAction, false, SwingConstants.SOUTH),
    new NextVisualPositionAction(selectionUpAction, true, SwingConstants.NORTH),
    new NextVisualPositionAction(selectionDownAction, true, SwingConstants.SOUTH),
    new BeginWordAction(beginWordAction, false),
    new EndWordAction(endWordAction, false),
    new BeginWordAction(selectionBeginWordAction, true),
    new EndWordAction(selectionEndWordAction, true),
    new PreviousWordAction(previousWordAction, false),
    new NextWordAction(nextWordAction, false),
    new PreviousWordAction(selectionPreviousWordAction, true),
    new NextWordAction(selectionNextWordAction, true),
    new BeginLineAction(beginLineAction, false),
    new EndLineAction(endLineAction, false),
    new BeginLineAction(selectionBeginLineAction, true),
    new EndLineAction(selectionEndLineAction, true),
    new BeginParagraphAction(beginParagraphAction, false),
    new EndParagraphAction(endParagraphAction, false),
    new BeginParagraphAction(selectionBeginParagraphAction, true),
    new EndParagraphAction(selectionEndParagraphAction, true),
    new BeginAction(beginAction, false),
    new EndAction(endAction, false),
    new BeginAction(selectionBeginAction, true),
    new EndAction(selectionEndAction, true),
    new DefaultKeyTypedAction(), new InsertTabAction(),
    new SelectWordAction(), new SelectLineAction(),
    new SelectParagraphAction(), new SelectAllAction(),
    new UnselectAction(), new ToggleComponentOrientationAction(),
    new DumpModelAction()
    and I'm not quite so sure that my above procedure is thread safe?You are creating a chat client. You are the only person typing data into your inputPane, so it is not a multi threaded application, so you shouldn't need to worry.

  • Tooltip/mouse listener question

    Hi all-
    I have a panel that contains various components that a user can move around. This is done by attaching a mouse listener and determining which component is currently being clicked/dragged.
    For a particular panel, I would like to display the x,y coordinates of a component in a tooltip, preferably while the user is moving it (which may not be possible with tool tips), but at least so that a user can see the updated coordinates after the component has been moved.
    However, when I setToolTipText for the component, it seems to override the mouse clicked events, and I can no longer even detect a click on the component.
    Is there a way that I can use tooltips and detect mouse clicks on the same component? Am I missing something simple, or do I need to find another way to do what I want to?
    Thanks
    Greg

    I searched posts last night but not today...oops.
    Found one today where a suggestion to something similar by mpmarrone was to use a Popup. It's now working, although I'm still not sure why tool tip text seems to take control of the mouse listener...

Maybe you are looking for