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.

Similar Messages

  • How to add mouse listener for a single row alone

    I have a requirement. In a JTable when I double click a particular row the cells in the row should set to the width which I have provided.
    The problem with my code is when I click fourth row in the table, the first row gets adjusted.
    So how I need help is
    only if I click the first row, the first row cell size should get adjusted not when I click fourth row.
    Similarly if I give some cell width and height for fourth row cells, then when I double click the fourth row, the fourth should alone get adjusted and not the other rows.
    Hope I have explained clearly.
    How can it be achieved?
    Please find below my code. Everything is hardcoded. So it may look messy. Please excuse.
    // Imports
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    class SimpleTableExample extends JFrame {
    // Instance attributes used in this example
    private JPanel topPanel;
    private JTable table;
    private JScrollPane scrollPane;
    String data1 = "";
    String data2 = "123456789ABCDEFGHIJKLMNOPQRSTUVQWXYZabcdefghijklmnopqrstuvwxyzaquickbrownfoxjumpedoverthelazydog";
    int size = data2.length();
    // Constructor of main frame
    public SimpleTableExample() {
         // Set the frame characteristics
         setTitle("Simple Table Application");
         setSize(400, 200);
         setBackground(Color.gray);
         // Create a panel to hold all other components
         topPanel = new JPanel();
         topPanel.setLayout(new BorderLayout());
         getContentPane().add(topPanel);
         // Create columns names
         String columnNames[] = { "SEL", "DESIGN DATA", "PART NUMBER" };
         // Create some data
         String dataValues[][] = { { data1, data2, "67", "77" },
              { "", "43", "853" }, { "", "89.2", "109" },
              { "", "9033", "3092" } };
         DefaultTableModel model = new DefaultTableModel(dataValues, columnNames);
         model.addColumn("PART TITLE");
         model.addColumn("SPECIAL INSTRUCTIONS");
         table = new JTable(model) {
         public boolean isCellEditable(int rowIndex, int colIndex) {
              return false;
         // set specific row height
         table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
         int colInd = 0;
         TableColumn col = table.getColumnModel().getColumn(colInd);
         int width = 50;
         col.setPreferredWidth(width);
         int colInd2 = 1;
         TableColumn col2 = table.getColumnModel().getColumn(colInd2);
         int width2 = 100;
         col2.setPreferredWidth(width2);
         int colInd3 = 2;
         TableColumn col3 = table.getColumnModel().getColumn(colInd3);
         int width3 = 10;
         col3.setPreferredWidth(width3);
         int colInd4 = 3;
         TableColumn col4 = table.getColumnModel().getColumn(colInd4);
         int width4 = 10;
         col4.setPreferredWidth(width4);
         int colInd5 = 4;
         TableColumn col5 = table.getColumnModel().getColumn(colInd5);
         int width5 = 10;
         col5.setPreferredWidth(width5);
         table.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
              if (e.getClickCount() == 2) {
              JTable target = (JTable) e.getSource();
              int row = target.getSelectedRow();
              int column = target.getSelectedColumn();
              TableColumn col1 = table.getColumnModel().getColumn(0);
              col1.setPreferredWidth(50);
              TableColumn col2 = table.getColumnModel().getColumn(1);
              col2.setPreferredWidth(400);
              table.getColumnModel().getColumn(1).setCellRenderer(
                   new TableCellLongTextRenderer());
              table.setRowHeight(50);
              TableColumn col5 = table.getColumnModel().getColumn(4);
              col5.setPreferredWidth(200);
         // Create a new table instance
         // table = new JTable(dataValues, columnNames);
         // Add the table to a scrolling pane
         scrollPane = new JScrollPane(table);
         topPanel.add(scrollPane, BorderLayout.CENTER);
    // Main entry point for this example
    public static void main(String args[]) {
         // Create an instance of the test application
         SimpleTableExample mainFrame = new SimpleTableExample();
         mainFrame.setVisible(true);
    class TableCellLongTextRenderer extends JTextArea implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value,
         boolean isSelected, boolean hasFocus, int row, int column) {
         this.setText((String) value);
         this.setWrapStyleWord(true);
         this.setLineWrap(true);
         // set the JTextArea to the width of the table column
         setSize(table.getColumnModel().getColumn(column).getWidth(),
              getPreferredSize().height);
         if (table.getRowHeight(row) != getPreferredSize().height) {
         // set the height of the table row to the calculated height of the
         // JTextArea
         table.setRowHeight(row, getPreferredSize().height);
         return this;
    Edited by: 915175 on Aug 3, 2012 4:24 AM

    Hi
    Try below code. Hope this will help
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    public class SimpleTableExample extends JFrame {
    private JPanel topPanel;
    private JTable table;
    private JScrollPane scrollPane;
    String data1 = "";
    String data2 = "123456789ABCDEFGHIJKLMNOPQRSTUVQWXYZabcdefghijklmnopqrstuvwxyzaquickbrownfoxjumpedoverthelazydog";
    int size = data2.length();
    // Constructor of main frame
    public SimpleTableExample() {
    // Set the frame characteristics
    setTitle("Simple Table Application");
    setSize(400, 200);
    setBackground(Color.gray);
    // Create a panel to hold all other components
    topPanel = new JPanel();
    topPanel.setLayout(new BorderLayout());
    getContentPane().add(topPanel);
    // Create columns names
    String columnNames[] = { "SEL", "DESIGN DATA", "PART NUMBER" };
    // Create some data
    String dataValues[][] = { { data1, data2, "67", "77" },
    { "", "43", "853" }, { "", "89.2", "109" },
    { "", "9033", "3092" } };
    DefaultTableModel model = new DefaultTableModel(dataValues, columnNames);
    model.addColumn("PART TITLE");
    model.addColumn("SPECIAL INSTRUCTIONS");
    table = new JTable(model) {
    public boolean isCellEditable(int rowIndex, int colIndex) {
    return false;
    // set specific row height
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    int colInd = 0;
    TableColumn col = table.getColumnModel().getColumn(colInd);
    int width = 50;
    col.setPreferredWidth(width);
    int colInd2 = 1;
    TableColumn col2 = table.getColumnModel().getColumn(colInd2);
    int width2 = 100;
    col2.setPreferredWidth(width2);
    int colInd3 = 2;
    TableColumn col3 = table.getColumnModel().getColumn(colInd3);
    int width3 = 10;
    col3.setPreferredWidth(width3);
    int colInd4 = 3;
    TableColumn col4 = table.getColumnModel().getColumn(colInd4);
    int width4 = 10;
    col4.setPreferredWidth(width4);
    int colInd5 = 4;
    TableColumn col5 = table.getColumnModel().getColumn(colInd5);
    int width5 = 10;
    col5.setPreferredWidth(width5);
    // Cell Render should apply on each column -- add by Rupali
    for(int i=0; i< table.getColumnModel().getColumnCount(); i++){
    table.getColumnModel().getColumn(i).setCellRenderer( new TableCellLongTextRenderer());
    table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    if (e.getClickCount() == 2) {
    JTable target = (JTable) e.getSource();
    int row = target.getSelectedRow();
    int column = target.getSelectedColumn();
    setTableCellHeight(table,row,column); //Added by Rupali
    TableColumn col1 = table.getColumnModel().getColumn(0);
    col1.setPreferredWidth(50);
    TableColumn col2 = table.getColumnModel().getColumn(1);
    col2.setPreferredWidth(400);
    TableColumn col5 = table.getColumnModel().getColumn(4);
    col5.setPreferredWidth(200);
    // Create a new table instance
    // table = new JTable(dataValues, columnNames);
    // Add the table to a scrolling pane
    scrollPane = new JScrollPane(table);
    topPanel.add(scrollPane, BorderLayout.CENTER);
    * Created By Rupali
    * This will set cell's height and column's width
    * @param table
    * @param row
    * @param column
    public void setTableCellHeight(JTable table, int row, int column) {
    // set the JTextArea to the width of the table column
    setSize(table.getColumnModel().getColumn(column).getWidth(),
    getPreferredSize().height);
    if (table.getRowHeight(row) != getPreferredSize().height) {
    // set the height of the table row to the calculated height of the
    // JTextArea
    table.setRowHeight(row, getPreferredSize().height);
    // Main entry point for this example
    public static void main(String args[]) {
    // Create an instance of the test application
    SimpleTableExample mainFrame = new SimpleTableExample();
    mainFrame.setVisible(true);
    class TableCellLongTextRenderer extends JTextArea implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    this.setText((String) value);
    this.setWrapStyleWord(true);
    this.setLineWrap(true);
    return this;
    }

  • How to know which leaf node i click and how to add a listener to each node?

    hi! hello to all members, i have a problem i know how to create a listener, but i dont know how to add a listener to each leaf node. here is the scenario i want to do, i have a JTree where theres a topic that you can select on each leaf node, so when the user click the specific topic it will open another JFrame,which i dont know how to do it also, that its! the next problem will be how do i know which leaf node i select, so that i can open a right topic before the JFrame will open?please, i am very need this to solve quickly as possible. thanks again to all members.

    What you have to do is to add a mouse listener on your JTree. Try something like this:
    tree.addMouseListener(new java.awt.event.MouseAdapter() {
             public void mouseReleased(MouseEvent e) {
                tree_mouseReleased(e);
    private void tree_mouseReleased(MouseEvent e) {
          TreePath selPath = tree.getSelectionPath();
          // Check If the click is the Right Click
          if (e.isPopupTrigger() == true) {
          // This is your right Click
           else {
                     // This is your Left Click
    }Your other problem: Set the userObject on nodes and on left click compare it with your object, if it matches, display the appropriate file. Alternatively, if your nodes are unique, you can match the names to open the file.
    Hope this Helps
    Regard
    Raheel

  • How to add event listener?

    i want to add event listener when i click on a button in mxml, the event listener should be added in the action script file, how to do this?
    can anyone help? urgent!!!

    Hi Lakshmi,
    You can do this just put all the script in the mxml block in seperate AS file as shown below... Observe that I have included an AS file named Script.as and removed the script block form mxml and moved to this Script.as file. Place the Script.as file in your src folder ....
    // Main mxml file....
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="onCreationComplete()">
        <mx:Script source="Script.as"/>
    <mx:TextArea id="textArea" width="300" height="100" />
    <mx:Button id="myButton" label="Click ME"/>
    </mx:Application>
    //Script.as file
    import mx.controls.Alert;
                private function onCreationComplete():void
                 myButton.addEventListener(MouseEvent.CLICK, onButtonClick);
                private function onButtonClick(event:MouseEvent):void
                 Alert.show("Button is Clicked");
    Thanks,
    Bhasker

  • How to add a Listener to the JLabel

    Hi,
    I am doing a Designer module in which i want to Listen Focus gained event on JLabel. For that i have added FocusListener to the JLabel but it does not listen to this event. (i think because of JLabels extraodinary property).
    So How to add listener to the JLabel?

    Set the label to be focusable. This will allow it to gain focus from the
    keyboard (from pressing TAB, for example), but not from being clicked on.
    It's easy to give some demo code than to explain it:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class LabelListening extends MouseAdapter implements FocusListener {
        private static final String TEXT_KEY = "jlabel_text_key";
        public void focusGained(FocusEvent e) {
            JLabel label = (JLabel) e.getComponent();
            String text = (String) label.getClientProperty(TEXT_KEY);
            label.setText("<html><u>" + text + "</u></html>");
        public void focusLost(FocusEvent e) {
            JLabel label = (JLabel) e.getComponent();
            String text = (String) label.getClientProperty(TEXT_KEY);
            label.setText(text);
        public void mousePressed(MouseEvent e) {
            e.getComponent().requestFocusInWindow();
        public static void main(String[] args) {
            LabelListening app = new LabelListening();
            JPanel contentPane = new JPanel();
            for(int i=0; i<4; ++i) {
                String text = "label " + i;
                JLabel label = new JLabel(text);
                label.putClientProperty(TEXT_KEY, text);
                label.setFocusable(true);
                label.addFocusListener(app);
                label.addMouseListener(app);
                contentPane.add(label);
            JButton btn = new JButton("a button");
            btn.setBorderPainted(false);
            btn.setContentAreaFilled(false);
            btn.setMargin(new Insets(0,0,0,0));
            contentPane.add(btn);
            final JFrame f = new JFrame("");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(contentPane);
            f.pack();
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
    }In this example, I have the focused label underlined. I don't
    know what your context is, but it may be simpler just to work with
    buttons instead. I "undecorate" a button in this example to make it look
    similar to a label.

  • How to set mouse listener for title bar of JFrame ?

    Hi, all
    How to we can set mouse listener for title bar of JFrame ?
    Please help

    Again, why did you not state this in your original
    question? Do we have to ask you every time what your
    actual requirement is?
    As I said in your last posting, if you don't give us
    the reuqirement in you question we can't help you.
    Sometimes your solution may be on the right track
    sometimes it isn't. We waste time guessing what your
    are trying to do if you don't give us the
    requirement.
    I gave you the answer in your other posting on this
    topic. The AWTEventListener can listen to events
    other than MouseEvents.
    The Swing tutorial has a list of most of the events.
    Pick the events you want to listen for:
    http://java.sun.com/docs/books/tutorial/uiswing/events
    /handling.htmlthe first, i am sory because my requirement not clear so that it wasted everybody time.
    The second, thank for your answer
    The third, AWTEvenListener do not support listener event on title bar
    but ComponentListener can know when we can change frame position.
    please see below that ComponentListener can handle action:
    public void componentHidden(ComponentEvent e) {
            displayMessage(e.getComponent().getClass().getName() + " --- Hidden");
        public void componentMoved(ComponentEvent e) {
            displayMessage(e.getComponent().getClass().getName() + " --- Moved");
        public void componentResized(ComponentEvent e) {
            displayMessage(e.getComponent().getClass().getName() + " --- Resized ");           
        public void componentShown(ComponentEvent e) {
            displayMessage(e.getComponent().getClass().getName() + " --- Shown");
        }Thanks for all supported your knowledge, you are great !

  • How to add action listener to internal frame?

    I have frame Main where I am trying to add action listener.
    Action listener should be listening button in frame Menu.
    I think it should be:
    Menu frame = new Menu();
    frame.btn_start.addActionListener(this);but it seems to be doing absolutely nothing.
    If I try to add in menu:
    btn_start.addActionListener(new Main());it generates: java.lang.StackOverflowError
    What should I do? Please help noob :)

    To get better help sooner, post a [_Short, Self Contained, Compilable and Executable, Example Program (SSCCE)_|http://mindprod.com/jgloss/sscce.html] that clearly demonstrates your problem.
    You're quite possible adding the ActionListener to the wrong component. And constructing a new instance of a class within the constructor is likely the cause of your StackOverflowError.
    db

  • How to handle Mouse listener (Clicked) in JGraph

    Hi Guys,
    I am doing a project using JGraph with SWING.
    How to handle Mouse events such as pressed or Move using JGraph in each of the node (Vertex&Edge).I have already tried a example which is presented in JGraph manual. But unable to fix the problem.Kindly help me

    i have not used JGraph before, but i think its event handling is equal to anyother swing component. so what exactly is the problem you can't solve?

  • How to add own Listener?

    Hi!
    The problem is that I have inherited the class MyTrayIcon from TrayIcon with implementing of MouseListener interface to handle mouse double click. But TrayIcon doesn't have method 'addMouseListener' as MyTrayIcon doesn't. So, how can I add listener is this case?

    How about looping through the array of listeners and
    removing it if it's an instance of ListListener?
    if (eventListeners[index] instanceof ListListener)
    removeMouseListener(eventListeners[index]);I thought of that, but as I said i my post, eventListeners[] is protected.
    How about writing your own ListListener in the
    appropriate package which does precisely nothing, and
    making sure it goes in the CLASSPATH before the
    package you're supposed to use?Nice idea, but unfortunately, when I submit the assignment I have no way of making sure that it does go into the classpath before the package.
    Thanks for your help, but I think I'll have to stick with the workaround.
    It's not too hard:  public static void setListData(DefaultListModel model, Object data[])
        model.clear();
        for (int i = 0; i < data.length; i++)
          model.addElement(data);

  • How to add map listener

    hi
    how can i add a MapListener in my application so that i can able to fire aevent when some record are inserted or deleted in cache, i am using java API.
    regards
    praveen jian

    Hi,
    Please see this link:
    http://wiki.tangosol.com/display/COH33UG/Deliver+events+for+changes+as+they+occur
    Thanks,
    Patrick

  • How to add a listener for enter key

    I'd like to build a chatzone applcation just like msn. The application
    has two textarea, one is for the messages sent and recieve and one is
    for the message typing area. Just like MSN, I'd like to send the text
    after the user pressed enter key. But my problem is I don't know how
    to make a key listener. I've tried jTextArea1.addKeyListener() but I don't
    know how to use it. Anyone can help me?
    Thanks in advance

    KeyListener is just an interface, so you could use:
    public class MyKeyListener implements KeyListener
       private JTextArea area = null;
       public MyKeyListener (JTextArea area)
            this.area = area;
       // Don't care about a key being pressed.
       public void keyPressed (KeyEvent e) {}
       // Don't care about a key being typed.
       public void keyTypes (KeyEvent e) {}
       // We care about the key being released.
       public void keyReleased (KeyEvent e)
           // Check what key it is.  Note sure if \n is the right one...maybe use the key codes.
           if (e.getKeyChar () == '\n')
                // The return key has been pressed and released, they really meant to press it!
                // Get the last line of the text from the text area.  This bits up to you...maybe
                // store the last location of the caret and then read from that point up
                // to the current point...
    }You can also use a DocumentListener if you are using a JTextArea but this is a little bit more complex but may be better, DocumentListeners work on telling you about more macro changes to the document...

  • How to add Window Listener

    Basically, I have created a simple window. I am having trouble adding a window listener so that when the user clicks the x to exit the program, it exits. Here is the code I have.
    package javagraphics;
    import java.awt.*;
    import java.awt.event.*;
    public class DispGraphics
        public static void main(String args[])
            Frame myFrame = new Frame("My Window");
            myFrame.setLayout(new BorderLayout());
            Label myLabel = new Label("Hello World!");
            myFrame.add(myLabel, BorderLayout.CENTER);
            myFrame.setSize(200, 200);
            myFrame.show();      
    }What do I need to add to it so that I can exit program with x on top right of window? Thanks.

            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            });Look at the tutorial for more info:
    http://java.sun.com/docs/books/tutorial/uiswing/events/windowlistener.html

  • How to add a listener for frame change

    hello
    Im quite new to jmf, and im writing a code which uses the webcam, but im stuck at a point where i want a listener which is called whenever the frame changes in the visualcomponent. so basically im looking for a frame changed listener to be added to the visual component instead of using a loop or a timer or something.
    i just need a method to be called constantly along the stream coming from the webcam but which is consistent with the changing of the frames.
    i would really appreciate any kind of help.
    thank you

    i thought there would be a listener or something ready to do thisThere is. It's the Rendered interface, which has a callback everytime data is received. If you want to create a custom renderer that is triggered everytime data is available, you set a processor to use your renderer and when data is available, your process command will be called. Same as an event listener...but it's very advanced stuff to implement the renderer interface.
    for example if u want to record a video ull need to capture every frame as soon as it comesNo, the video doesn't come to you a frame at a time. The video is already encoded somehow when you get it, so it's coming in as a stream just like it'll be going out to the file... It's a stream of bytes, not a stream of images... You're not digitizing here, you're transcoding.

  • How to add event listener to datagrid ROW

    I need to know if it is possible to have the datagrid rows execute a state change.
    For example: I have a datagrid populated with various items, when one row is selected I want it to change the state of a part of the canvas it is in.
    How is this possible? I can not give the row an id so I would not be able to say "when row is selected change state" because there is no way to tell what row is selected.
    Help please. Thanks.

    See Flex 4 and MXDataGridItemRenderer.

  • 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

Maybe you are looking for