Adding ActionListener to JPanel or equivalent

Hi all.
I am trying to add an actionListener for mouse clicks on a JPanel, ideally using something like this:
panel.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e)
          //do something
   });However, JPanel does not implement addActionListener, and as far as I can see the only components which do are buttons, radio buttons and the like.
I tried extending JPanel to implement ActionListener, but had no success.
Is there an easy way to monitor for mouse clicks on a JPanel or container? Bearing in mind there will be several of these containers at different locations, so using a global mouse listener would not be useful.
Thanks

Hi all.
I am trying to add an actionListener for mouse clicks
on a JPanel, ideally using something like this:
panel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
//do something
});owever, JPanel does not implement addActionListener,
and as far as I can see the only components which do
are buttons, radio buttons and the like.
I tried extending JPanel to implement ActionListener,
but had no success.
Is there an easy way to monitor for mouse clicks on a
JPanel or container? Use a MouseListener.
Bearing in mind there will be
several of these containers at different locations,
so using a global mouse listener would not be
useful.So add individual MouseListeners to each container.
>
Thanks

Similar Messages

  • Added actionListener, then GUI broke

    Hi,
    1. first i ran my menu GUI, it worked fine
    2. then i added the actionListener code... now she no workie...
    what did i do wrong???
    ERROR MSG:
    C:\jLotto\LotFrame.java:34: cannot resolve symbol
    symbol : class ActionListener
    location: class LottoFrame
              new ActionListener(){
    ^
    1 error
    Tool completed with exit code 1
    import javax.swing.JFrame;
    import javax.swing.JMenuBar;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.KeyStroke;
    import java.awt.Event;
    import javax.swing.JOptionPane; //print menu trial run
    public class LotFrame extends JFrame
      // Constructor
      public LotFrame(String title)
        setTitle(title);                             // Set the window title
        setDefaultCloseOperation(EXIT_ON_CLOSE);     // handle exit operation
        setJMenuBar(menuBar);                        // Add the menu bar to the window
        //MAIN MENU
        JMenu fileMenu    = new JMenu("File");          // Create File menu
        JMenu findMenu    = new JMenu("Find");
        // Construct the file pull down menu
        newItem   = fileMenu.add("New");             // Add New item
        openItem  = fileMenu.add("Open");            // Add Open item
        closeItem = fileMenu.add("Close");           // Add Close item
        fileMenu.addSeparator();                      // Add separator
        saveItem  = fileMenu.add("Save");            // Add Save item
        saveAsItem= fileMenu.add("Save As...");      // Add Save As item
        fileMenu.addSeparator();                      // Add separator
        printItem.addActionListener(
               new ActionListener(){
                    public void actionPerformed( ActionEvent e )
                         JOptionPane.showMessageDialog( LotFrame.this,
                         "adding actionListener at end of GUI setup",
                         "action at end", JOptionPane.PLAIN_MESSAGE);
                    }//end of actionPerformed
              }//end of actionLinstener
         );//endof .addActionListener
       printItem = fileMenu.add("Print");           // Add Print item
        menuBar.add(fileMenu);                       // Add the file menu
        menuBar.add(findMenu);
      }//end of constructor
      private JMenuBar menuBar = new JMenuBar();     // Window menu bar
      // File menu items
      private JMenuItem newItem, openItem, closeItem, saveItem, saveAsItem, printItem;
    }//end of class LotFrame

    java.awt.event.*;
    import java.awt.Event;

  • Adding actionListener to JComboBox

    Hi there
    I have added actionListener to a JComboBox. I only want the actionPerformed() get called when the user choose the item in the JComboBox, however, it also get called whenever I change the items in the JComboBox.
    I have tried to call the ActionEvent.getID() method to identify the action, however, changing the items and choosing the item give me the same ID - 1001.
    Has anyone got this problem before? How did you solve it?
    Should I use other Listener for listening only the choosing event?
    In advance thanks!
    From
    Edmond

    I had many problems using actionListeners with JComboBox because it gets called all the time, I have had much better luck using mouseListener and the events getClickCount() method for single and double click selections, this avoided many of the problems for me.

  • JScrollPane (added to a JPanel, which paints) is visible but does nothing

    Hi. I am writing a program that reads data from files and does paiting using the info. The top level window is a JFrame, which is divided into two parts - A Box which contains the buttons through which the user interacts and a JPanel on which the painting is done. I have added the JPanel to a JScrollPane, but have run into problems there. The JScrollPane is visible (both policies always visible) but it does nothing. I understand that when the drawing is fitting, the ScrollPane is not used. But even if I make the window small or draw something that is not visible in the normal are, the JScrollPane doesn't work. In fact, no knob is visible on either of the two scrollbars. I am pasting the relevant code below:
    //import
    public class MainWindow extends JFrame {
        public static void Main(String[] args) {
            new MainWindow();
        //Declare all the variables here.
        private Box buttionBox;
        private JScrollPane scroller;
        private HelloPanel drawingPanel;   
        //other variables
        //The constructor for the class MainWindow.
        public MainWindow() {
           initComponents();
            this.setLayout(new BorderLayout());
            this.setPreferredSize(new Dimension(900,670));
            //buttonBox containts the buttons - not very relevant to this problem.
            this.getContentPane().add(buttonBox, BorderLayout.WEST);
            //scroller is the JScrollPane
            this.getContentPane().add(scroller, BorderLayout.CENTER);       
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setTitle("My Title");       
            this.setVisible(true);
            this.pack();       
        public void initComponents() {
            buttonBox = Box.createVerticalBox();
            //instantiate the buttons here and add them to the ButtonBox.
            //The event listeners instantiated. Not relevant.       
            //The various components are assigned their appropriate event listeners here.
             //Not relevant.
    //Now adding all the buttons to the box with proper spacing.
            buttonBox.add(Box.createVerticalStrut(20));
            //This is the drawing panel on which the drawing will be done.
            drawingPanel = new HelloPanel();
            scroller = new JScrollPane(drawingPanel);
                    scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
            scroller.getHorizontalScrollBar().setUnitIncrement(10);
            scroller.getVerticalScrollBar().setUnitIncrement(10);
        //This inner class is used to define and implement the event listener for handling the checkboxes.
        private class checkBoxListener implements ItemListener{
            public void itemStateChanged(ItemEvent e){
                 drawingPanel.repaint();
                    //Implement actions. Irrelevant
        //This private class is used to define and implement the event listener for the buttons.
        private class buttonListener implements ActionListener {
            //Do this when the button which has an instance of this class as its listener is clicked.       
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == saveStructureButton){
                  //Implement action. Irrelvant.
        //The panel on which the drawings are done.
        private class HelloPanel extends JPanel {
            //This JPanel is used for drawing the image (for the purpose of saving to disk).
            JComponent c;    //For image. Irrelevant.
            public HelloPanel(){           
                c = this;   //This is necessary for drawing the image to be saved to disk.
                this.setBackground(Color.WHITE);
            //This is the method that actually paints all the drawings whenever a.
            //The shapes theselves can be defined somewhere else, but that paint method must be invoked from here.
            public void paintComponent(Graphics g){
                super.paintComponent(g);    //First of all, clear the panel.
                Graphics2D g2 = (Graphics2D) g;
                g2.fill(new Rectangle2D.Double(40,40,100,100));    //Just for this post.
                g2.drawString("Text", 750, 750);    //To test the scrollpane.
    } I hope this helps you get an idea of what I am trying to do and what the problem might be. Any help would be really appreciated. I have spent hours on this and I have no idea why it doesn't work.
    The actual code is much bigger, so if you need any extra information, please tell me.

    HelloPanel should provide a "public Dimension getPreferredSize()" method.
    With your code you create a simple JPanel and want to draw outside of it, but you never tell the JScrollPane that your HelloPanel is actually bigger than it seems, that's why it does not feel the need to add scroll bars.
    Here's the working code:
    //import
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    public class MainWindow extends JFrame {
        public static void main(String[] args) {
            new MainWindow();
        //Declare all the variables here.
        private Box buttionBox;
        private JScrollPane scroller;
        private HelloPanel drawingPanel; 
        //other variables
        //The constructor for the class MainWindow.
        public MainWindow() {
           initComponents();
            this.setLayout(new BorderLayout());
            this.setPreferredSize(new Dimension(900,670));
            //buttonBox containts the buttons - not very relevant to this problem.
            //this.getContentPane().add(buttonBox, BorderLayout.WEST);
            //scroller is the JScrollPane
            this.getContentPane().add(scroller, BorderLayout.CENTER);       
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setTitle("My Title");       
            this.setVisible(true);
            this.pack();       
        public void initComponents() {
            //buttonBox = Box.createVerticalBox();
            //instantiate the buttons here and add them to the ButtonBox.
            //The event listeners instantiated. Not relevant.       
            //The various components are assigned their appropriate event listeners here.
             //Not relevant.
    //Now adding all the buttons to the box with proper spacing.
            //buttonBox.add(Box.createVerticalStrut(20));
            //This is the drawing panel on which the drawing will be done.
            drawingPanel = new HelloPanel();
            scroller = new JScrollPane(drawingPanel);
                    scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
            scroller.getHorizontalScrollBar().setUnitIncrement(10);
            scroller.getVerticalScrollBar().setUnitIncrement(10);
        //This inner class is used to define and implement the event listener for handling the checkboxes.
        private class checkBoxListener implements ItemListener{
            public void itemStateChanged(ItemEvent e){
                 drawingPanel.repaint();
                    //Implement actions. Irrelevant
        //This private class is used to define and implement the event listener for the buttons.
        private class buttonListener implements ActionListener {
            //Do this when the button which has an instance of this class as its listener is clicked.       
            public void actionPerformed(ActionEvent e) {
                //if (e.getSource() == saveStructureButton){
                  //Implement action. Irrelvant.
        //The panel on which the drawings are done.
        private class HelloPanel extends JPanel {
            //This JPanel is used for drawing the image (for the purpose of saving to disk).
            JComponent c;    //For image. Irrelevant.
            public HelloPanel(){           
                c = this;   //This is necessary for drawing the image to be saved to disk.
                this.setBackground(Color.WHITE);
            //This is the method that actually paints all the drawings whenever a.
            //The shapes theselves can be defined somewhere else, but that paint method must be invoked from here.
            public void paintComponent(Graphics g){
                super.paintComponent(g);    //First of all, clear the panel.
                Graphics2D g2 = (Graphics2D) g;
                g2.fill(new Rectangle2D.Double(40,40,100,100));    //Just for this post.
                g2.drawString("Text", 750, 750);    //To test the scrollpane.
         public Dimension getPreferredSize()
         return new Dimension(750,750);
    }

  • Adding actionlistener to JTextArea

    I'm trying to add an actionListener to my JTextArea, so that when the user hits 'enter', the action occurs.
    sort of like this:
    JTextArea.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ??????) {
    doSomethingToTextArea();
    but I'm having problems (e.g. how to make enter the action event, and some problem that says JTextArea can't use actionlisteners???)
    any ideas?
    thanks,
    n00bProgrammer

    Like serveral of the more complex swing gadgets the JTextarea uses model/view architecture. In this case the model behind the textarea is a Document, and the text change listener needs to be added to the Document, not the gadget itself. i.e. area.getModel().addDocumentListener();
    However JTextArea still inherits the methods of java.awt.Component including addKeyListener();

  • Adding Backgrounds on JPanels

    Could anyone help with the following code; I am trying to put two JPanels on a JLayeredPane and have one of them act as background; the code goes like this
    /** The game has been implemented as part of the final
    project for CSc322
    *     @author Zengine Productions version 1
    // This is the main frame
    import java.lang.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class SpaceBall
    //To do the background just draw a JPanel inside
    another JPanel just set the opacity of the outside one
    to false and let
    //it hold all the components of the game
    public static void main(String[] args)
    //declaring the buttons
    JButton test=new JButton("test");
    JButton test1=new JButton("test1");
    JButton test2=new JButton("test2");
    //declaring and setting the properties of the frame
    JFrame SpaceBall= new JFrame("Space Ball"); // the
    game window
    SpaceBall.setSize(700,750);
    //declaring the Panels
    JLayeredPane bgPanel= new JLayeredPane(); // the
    panel that holds the background image
    JPanel fgPanel= new JPanel(); // the panel that
    holds all the game objects
    JPanel topPanel= new JPanel(); // the panel on top
    of the game panel
    JPanel sidePanel= new JPanel(); // the panel on the
    side of the game panel
    JPanel lowPanel= new JPanel(); // the panel that
    will hold bgPanel and sidepanel
    JPanel masterPanel= new JPanel(); // the panel that
    holds everything to be added to the JFrame
    //adding the buttons to the corresponding panels
    fgPanel.add(test1);
    sidePanel.add(test2);
    topPanel.add(test);
    // ImageIcon background= new
    ImageIcon("images/background.jpg");
    // JLabel backlabel = new JLabel(background);
    // bgPanel.add(backlabel, new
    Integer(Integer.MIN_VALUE));
    backlabel.setBounds(0,0,background.getIconWidth(),background.getIconHeight());
    fgPanel.setOpaque(false);
    bgPanel.add(fgPanel);
    bgPanel.setForeground(Color.white);
    //adding bgPanel and sidePanel to lowPanel
    lowPanel.setLayout(new GridLayout(1,2));
    lowPanel.add(bgPanel);
    lowPanel.add(sidePanel);
    //adding the Panels to the masterPanel
    masterPanel.setLayout(new GridLayout(2,1));
    masterPanel.add(topPanel);
    masterPanel.add(lowPanel);
    //getting the container of SpaceBall and adding the
    Panels to it
    Container cp=SpaceBall.getContentPane();
    cp.add(masterPanel);
    //displaying everything
    SpaceBall.show();
    WindowListener ClosingTheWindow=new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    SpaceBall.addWindowListener(ClosingTheWindow);
    Could anyone point out any bug in the code that keeps it from displaying the button on the background Panel!
    Thanks

    Thanks Wekion but I think the editor messed up the format of my code; below is the exact one that I try to run but never get the result that I seek!
    // This is the main frame
    import java.lang.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class SpaceBall
    //To do the background just draw a JPanel inside another //JPanel just set the opacity of the outside one
    //to false and let
    //it hold all the components of the game
    public static void main(String[] args)
    //declaring the buttons
    JButton test=new JButton("test");
    JButton test1=new JButton("test1");
    JButton test2=new JButton("test2");
    //declaring and setting the properties of the frame
    JFrame SpaceBall= new JFrame("Space Ball");
    SpaceBall.setSize(700,650);
    //declaring the Panels
    JLayeredPane bgPanel= new JLayeredPane();
    JPanel fgPanel= new JPanel();
    JPanel topPanel= new JPanel();
    JPanel sidePanel= new JPanel();
    JPanel lowPanel= new JPanel();
    JPanel masterPanel= new JPanel();
    //adding the buttons to the corresponding panels
    fgPanel.add(test1);
    sidePanel.add(test2);
    topPanel.add(test);
    ImageIcon background= new ImageIcon("images/background.jpg");
    JLabel backlabel = new JLabel(background);
    backlabel.setBounds(0,0,background.getIconWidth(),background.getIconHeight());
    backlabel.add(test1);
    bgPanel.add(backlabel, new Integer(0));
    fgPanel.setOpaque(false);
    bgPanel.add(fgPanel, new Integer(100));
    bgPanel.moveToFront(fgPanel);
    //adding bgPanel and sidePanel to lowPanel
    lowPanel.setLayout(new GridLayout(1,2));
    lowPanel.add(bgPanel);
    lowPanel.add(sidePanel);
    //adding the Panels to the masterPanel
    masterPanel.setLayout(new GridLayout(2,1));
    masterPanel.add(topPanel);
    masterPanel.add(lowPanel);
    //getting the container of SpaceBall and adding the Panels to it
    Container cp=SpaceBall.getContentPane();
    cp.add(masterPanel);
    //displaying everything
    SpaceBall.show();
    WindowListener ClosingTheWindow=new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    SpaceBall.addWindowListener(ClosingTheWindow);

  • Adding actionlistener to menuItem

    hi...i'm trying to add an actionListener to a menuItem. i looked at the tutorial on "how to use menus" but i cant seem to execute the menuitem. here's my code...
    public class Controller implements ActionListener
        GUI gui;
        public Controller(GUI g)
            gui = g;
            gui.menuItem.addActionListener(this);
        public void actionPerformed(ActionEvent e)
            gui.menuItem = (JMenuItem)(e.getSource());
            if (gui.menuItem.getText().equals("New Database"))
                System.out.println("Hello");
    }where the class GUI is where the menItems have been added to the menus. i'm just trying out for one menuItem first but i wont get the "hello" printed on the screen...can someone give me some assistance on this given that i havent used JMenuItems before...thx in advance...

    As carnickr said we really need the source from GUI to be able to help you more. Even without looking at GUI it's apparent that you're methodology is lacking. Depending on design and requirements I can think of many different ways you might need to handle menu item actions. I can't think of a single one that would involve comparing the text, which is what you're doing.
    First of all, adding a listener to a public field of a different class is inherently the product of a flawed design or bad design itself. Your code should look more like this:
    JMenuItem newDatabase = new JMenuItem("New Database");
    JMenuItem openDatabase = new JMenuItem("Open Database");
    JMenuItem closeDatabase = new JMenuItem("Close Database");
    ActionListener listener = new ActionListener() {
         public void actionPerformed(ActionEvent e) {
              if (e.getSource() == newDatabase) {
                   System.out.println("New database clicked");
              } else if (e.getSource() == openDatabase) {
                   System.out.println("Open database clicked");
              } else fi (e.getSource() == closeDatabase) {
                   System.out.println("Close database clicked");
    newDatabase.addActionListener(listener);
    openDatabase.addActionListener(listener);
    closeDatabase.addActionListener(listener);Obviously an anonymous class is not always appropriate. The important thing here is that you're comparing the reference to see if it's the same Object, not trying to compare the text. If you post GUI and a little more about what you're trying to do we can try and give you some pointers on how to design it better.

  • Adding ActionListener to JMenu

    Is it possible to add actionListener to Jmenu object
    for example File, Format, Exit these are Menus added in the menuBar not menu items
    on clicking the Exit the frame shuld get closed.
    For detecting the action clicked on the Menu shall i use actionListener?
    I have tried using MenuListener its getting invoked on selection
    I dont want it on selection , I want the frame to be displayed only on clicking that menu.

    Alas, whilst a JMenu is-a JMenuItem (the Composite Pattern at work), it doesn't function entriely like on,
    and registering ActionListeners with a JMenu doesn't work. Try MenuListener:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class ActionExample {
        public static void main(String[] args) {
            Action sample = new SampleAction();
            JMenu menu = new JMenu("Menu");
            menu.setMnemonic(KeyEvent.VK_M);
            menu.add(sample);
            menu.addMenuListener(new SampleMenuListener());
            JToolBar tb = new JToolBar();
            tb.add(sample);
            JTextField field = new JTextField(10);
            field.setAction(sample);
            JFrame f = new JFrame("ActionExample");
            JMenuBar mb = new JMenuBar();
            mb.add(menu);
            f.setJMenuBar(mb);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(tb, BorderLayout.NORTH);
            f.getContentPane().add(field, BorderLayout.SOUTH);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    class SampleMenuListener implements MenuListener {
        public void menuSelected(MenuEvent e) {
            System.out.println("menuSelected");
        public void menuDeselected(MenuEvent e) {
            System.out.println("menuDeelected");
        public void menuCanceled(MenuEvent e) {
            System.out.println("menuCanceled");
    class SampleAction extends AbstractAction {
        public SampleAction() {
            super("Sample");
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("alt S"));
            putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_S));
            putValue(SHORT_DESCRIPTION, "Just a sample action");
        public void actionPerformed(ActionEvent evt) {
            System.out.println("sample...");
    }

  • Trouble adding actionlistener to a panel in a tabbed pane

    Hi, please help me! this is the code i wrote, with the error given below:
    CODE:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class tabslisten extends JApplet
         JPanel RecPanel;
         GridBagLayout gbl;
         GridBagConstraints gbc;
         public void init ()
              FlowLayout flow;
              flow = new FlowLayout();     
              Container content = getContentPane();
              content.setLayout(new GridLayout());
              JTabbedPane tabpane = new JTabbedPane();
              content.add(tabpane, flow);
              RecPanel = new JPanel();
              recipientDetails();
              tabpane.addTab("Recipient Details", null, RecPanel, "Recipient Details");     
         public void recipientDetails()
              JLabel lblRecFName;
              JLabel lblRecLName;
              JTextField txtRecFName;
              JTextField txtRecLName;
              JButton btnValidate;
              gbl = new GridBagLayout();
              gbc = new GridBagConstraints();
              RecPanel.setLayout(gbl);
              lblRecFName = new JLabel("First Name");
              lblRecLName = new JLabel("Last Name");
              txtRecFName = new JTextField(8);
              txtRecLName = new JTextField(5);
              btnValidate= new JButton("Validate");
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 8;
              gbl.setConstraints(lblRecFName, gbc);
              RecPanel.add(lblRecFName);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 4;
              gbc.gridy = 8;
              gbl.setConstraints(txtRecFName, gbc);
              RecPanel.add(txtRecFName);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 11;
              gbl.setConstraints(lblRecLName, gbc);
              RecPanel.add(lblRecLName);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 4;
              gbc.gridy = 11;
              gbl.setConstraints(txtRecLName, gbc);
              RecPanel.add(txtRecLName);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 4;
              gbc.gridy = 32;
              gbl.setConstraints(btnValidate, gbc);
              RecPanel.add(btnValidate);
              validateAction validateButton = new validateAction();
              btnValidate.addActionListener(validateButton);
         class validateAction implements ActionListener
              public void actionPerformed(ActionEvent evt)
                   Object obj = evt.getSource();
                   if (obj == btnValidate)
                        String fName = txtRecFName.getText();
                        String lName = txtRecLName.getText();
                        if (fName.length()==0)
                             getAppletContext().showStatus("First Name not entered.");
                             return;
                        else if (lName.length()==0)
                             getAppletContext().showStatus("Last Name not entered.");
                             return;
                        else
                             getAppletContext().showStatus("Successful.");
    ERROR:
    tabslisten.java:90: Undefined variable: btnValidate
    if (obj == btnValidate)
    ^
    tabslisten.java:92: Undefined variable or class name: txtRecFName
    String fName = txtRecFName.getText();
    ^
    tabslisten.java:93: Undefined variable or class name: txtRecLName
    String lName = txtRecLName.getText();
    ^
    3 errors
    Press any key to continue...
    I'm sure I'm doing something really stupid, but I don't know what! ANY and ALL help will be appreciated! Thanks!

    I copied your program and ran it. It works fine. Make sure the three variables you made class variables are only defined in one place. (ie you moved them not copied them). Other than that I have no ideas.
    With regards to naming conventions. My only comment is, take a look at the Java API.
    1) classes have uppercased words. Examples from your program - JTextField, Container, FlowLayout, GridLayout...
    2) methods and variable names don't upper case the first word - getContentPane(), setLayout()...
    Here is the program that works for me:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class FirstApplet extends JApplet
         JPanel RecPanel;
         GridBagLayout gbl;
         GridBagConstraints gbc;
         JTextField txtRecFName;
         JTextField txtRecLName;
         JButton btnValidate;
         public void init ()
              System.out.println("hello there");
              FlowLayout flow;
              flow = new FlowLayout();
              Container content = getContentPane();
              content.setLayout(new GridLayout());
              JTabbedPane tabpane = new JTabbedPane();
              content.add(tabpane, flow);
              RecPanel = new JPanel();
              recipientDetails();
              tabpane.addTab("Recipient Details", null, RecPanel, "Recipient Details");
         public void recipientDetails()
              JLabel lblRecFName;
              JLabel lblRecLName;
              gbl = new GridBagLayout();
              gbc = new GridBagConstraints();
              RecPanel.setLayout(gbl);
              lblRecFName = new JLabel("First Name");
              lblRecLName = new JLabel("Last Name");
              txtRecFName = new JTextField(8);
              txtRecLName = new JTextField(5);
              btnValidate= new JButton("Validate");
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 8;
              gbl.setConstraints(lblRecFName, gbc);
              RecPanel.add(lblRecFName);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 4;
              gbc.gridy = 8;
              gbl.setConstraints(txtRecFName, gbc);
              RecPanel.add(txtRecFName);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 11;
              gbl.setConstraints(lblRecLName, gbc);
              RecPanel.add(lblRecLName);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 4;
              gbc.gridy = 11;
              gbl.setConstraints(txtRecLName, gbc);
              RecPanel.add(txtRecLName);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 4;
              gbc.gridy = 32;
              gbl.setConstraints(btnValidate, gbc);
              RecPanel.add(btnValidate);
              validateAction validateButton = new validateAction();
              btnValidate.addActionListener(validateButton);
         class validateAction implements ActionListener
              public void actionPerformed(ActionEvent evt)
                   Object obj = evt.getSource();
                   if (obj == btnValidate)
                        String fName = txtRecFName.getText();
                        String lName = txtRecLName.getText();
                        if (fName.length()==0)
                             getAppletContext().showStatus("First Name not entered.");
                             return;
                        else if (lName.length()==0)
                             getAppletContext().showStatus("Last Name not entered.");
                             return;
                        else
                             getAppletContext().showStatus("Successful.");

  • Adding iamge to JPanel but it is not display in it's original size.

    hi,
    I am trying to add Image to JPanel successfully, but it' s visible in panel as a small icon rather then it's original size.
    First i creating a panel class and after that adding this panel to JFrame. I am using BufferedImage. I have tried it all the way but it's not working.Anybody have any idea about the problem.
    Thanks

    rule #1 when you have problem with code: post the code! How do you expect people to help you if you give them nothing but the plea for help?
    rule #2: use the code tags (when you paste your code, select it and press the code button) to format it so it is easy to read.

  • Adding JScrollPane on JPanel??Is there any problem.??

    hi,
    I have a JPanel over which i added a JScrollPane on to whose view portvie i added a JTable.
    But the problem is the table is not getting visble.Not only table all the components i add to scrollpane which on a panel is not getting displayed.
    Am i missing something??
    final JScrollPane scrollPane = new JScrollPane();
              panel.add(scrollPane);
              table = new JTable();
              scrollPane.setViewportView(table);

    Make sure to add the panel to the content pane as well.
    If the problem still persists, then please post a simple executable demo program that demonstrates the behavior.

  • Adding mouselisteners to JPanels created through for loop

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.io.File;
    import java.io.IOException;
    import java.util.Vector;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JViewport;
    import javax.swing.SwingConstants;
    import javax.swing.filechooser.FileSystemView;
    public class ScrollableWrapTest {
        public static void main(String[] args) {
            try {
                  ScrollableWrapTest st = new ScrollableWrapTest();
                final JPanel mainPanel = new JPanel(new WrapScollableLayout(FlowLayout.LEFT, 10, 10));
                mainPanel.setBackground(Color.WHITE);
                JScrollPane pane = new JScrollPane(mainPanel);
                pane.setPreferredSize(new Dimension(550, 300));
                Vector v = new Vector();
                v.add("first.doc");
                v.add("second.txt");
                v.add("third.pdf");
                v.add("fourth.rar");
                v.add("fifth.zip");
                v.add("sixth.folder");
                v.add("seventh.exe");
                v.add("eighth.bmp");
                v.add("nineth.jpeg");
                v.add("tenth.wav");
                JButton button = null;
                for(int i =0;i<v.size();i++){
                    JPanel panel = new JPanel(new BorderLayout());
                    Icon icon = st.getIcone(st.getExtension(v.elementAt(i).toString().toUpperCase()));
                      panel.setBackground(Color.WHITE);
                     Action action = new AbstractAction("", icon) {
                         public void actionPerformed(ActionEvent evt) {
                     button = new JButton(action);
                     button.setPreferredSize(new Dimension(icon.getIconWidth(), icon.getIconHeight()));
                     JPanel buttonPanel = new JPanel();
                     buttonPanel.setBackground(Color.WHITE);
                     buttonPanel.add(button);
                     JLabel label = new JLabel((String)v.elementAt(i));
                     label.setHorizontalAlignment(SwingConstants.CENTER);
                     panel.add(buttonPanel , BorderLayout.NORTH);
                     panel.add(label, BorderLayout.SOUTH);
                     mainPanel.add(panel);
                    mainPanel.revalidate();
                st.buildGUI(pane);
            } catch (Exception e) {e.printStackTrace();}
        public void buildGUI(JScrollPane scrollPane)
             JFrame frame = new JFrame("Scrollable Wrap Test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(scrollPane, BorderLayout.CENTER);
            frame.setLocationRelativeTo(null);
            frame.pack();
            frame.setVisible(true);
        public String getExtension(String name)
              if(name.lastIndexOf(".")!=-1)
                   String extensionPossible = name.substring(name.lastIndexOf(".")+1, name.length());
                   if(extensionPossible.length()>5)
                        return "";
                   else
                        return extensionPossible;
              else return "";
         public Icon getIcone(String extension)
              //we create a temporary file on the local file system with the specified extension
              File file;
              String cheminIcone = "";
              if(((System.getProperties().get("os.name").toString()).startsWith("Mac")))
                   cheminIcone = System.getProperties().getProperty("file.separator");
              else if(((System.getProperties().get("os.name").toString()).startsWith("Linux")))
                   //cheminIcone = FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath()+
                   cheminIcone = "/"+"tmp"+"/BoooDrive-"+System.getProperty("user.name")+"/";
              else cheminIcone = System.getenv("TEMP") + System.getProperties().getProperty("file.separator");
              File repIcone = new File(cheminIcone);
              if(!repIcone.exists()) repIcone.mkdirs();
              try
                   if(extension.equals("FOLDER"))
                        file = new File(cheminIcone + "icon");
                        file.mkdir();
                   else
                        file = new File(cheminIcone + "icon." + extension.toLowerCase());
                        file.createNewFile();
                   //then we get the SystemIcon for this temporary File
                   Icon icone = FileSystemView.getFileSystemView().getSystemIcon(file);
                   //then we delete the temporary file
                   file.delete();
                   return icone;
              catch (IOException e){ }
              return null;
        private static class WrapScollableLayout extends FlowLayout {
            public WrapScollableLayout(int align, int hgap, int vgap) {
                super(align, hgap, vgap);
            public Dimension preferredLayoutSize(Container target) {
                synchronized (target.getTreeLock()) {
                    Dimension dim = super.preferredLayoutSize(target);
                    layoutContainer(target);
                    int nmembers = target.getComponentCount();
                    for (int i = 0 ; i < nmembers ; i++) {
                        Component m = target.getComponent(i);
                        if (m.isVisible()) {
                            Dimension d = m.getPreferredSize();
                            dim.height = Math.max(dim.height, d.height + m.getY());
                    if (target.getParent() instanceof JViewport)
                        dim.width = ((JViewport) target.getParent()).getExtentSize().width;
                    Insets insets = target.getInsets();
                    dim.height += insets.top + insets.bottom + getVgap();
                    return dim;
    }How can I add mouse listener to each of the 'panel' in 'mainpanel' created inside the 'for loop' using the code mainPanel.add(panel);Rony

    >
    How can I add mouse listener to each of the 'panel' in 'mainpanel' created inside the 'for loop' using the code mainPanel.add(panel);
    Change the first part of the code like this..
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.io.File;
    import java.io.IOException;
    import java.util.Vector;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JViewport;
    import javax.swing.SwingConstants;
    import javax.swing.filechooser.FileSystemView;
    public class ScrollableWrapTest {
        public static void main(String[] args) {
            try {
                  ScrollableWrapTest st = new ScrollableWrapTest();
                final JPanel mainPanel = new JPanel(new WrapScollableLayout(FlowLayout.LEFT, 10, 10));
                mainPanel.setBackground(Color.WHITE);
                JScrollPane pane = new JScrollPane(mainPanel);
                pane.setPreferredSize(new Dimension(550, 300));
                Vector<String> v = new Vector<String>();
                v.add("first.doc");
                v.add("second.txt");
                v.add("third.pdf");
                v.add("fourth.rar");
                v.add("fifth.zip");
                v.add("sixth.folder");
                v.add("seventh.exe");
                v.add("eighth.bmp");
                v.add("nineth.jpeg");
                v.add("tenth.wav");
                JButton button = null;
                MouseListener ml = new MouseAdapter() {
                        @Override
                        public void mouseClicked(MouseEvent me) {
                             System.out.println(me);
                for(int i =0;i<v.size();i++){
                    JPanel panel = new JPanel(new BorderLayout());
                    Icon icon = st.getIcone(st.getExtension(v.elementAt(i).toString().toUpperCase()));
                      panel.setBackground(Color.WHITE);
                     Action action = new AbstractAction("", icon) {
                         public void actionPerformed(ActionEvent evt) {
                     button = new JButton(action);
                     button.setPreferredSize(new Dimension(icon.getIconWidth(), icon.getIconHeight()));
                     JPanel buttonPanel = new JPanel();
                     buttonPanel.setBackground(Color.WHITE);
                     buttonPanel.add(button);
                     JLabel label = new JLabel((String)v.elementAt(i));
                     label.setHorizontalAlignment(SwingConstants.CENTER);
                     panel.add(buttonPanel , BorderLayout.NORTH);
                     panel.add(label, BorderLayout.SOUTH);
                     mainPanel.add(panel);
                     panel.addMouseListener( ml );
                    mainPanel.revalidate();
                st.buildGUI(pane);
            } catch (Exception e) {e.printStackTrace();}
    ...

  • Adding Image to JPanel?

    Hi all,
    I am new to Swing..
    How to add the "Image" to JPanel.
    if anyone knows please help me..
    Thanks

    Here's a long reply involving several classes, some obtained directly from Sun for reuse. These allow you to fill an image in a panel as the background to your frame. You can add components on top of this background image. If this isn't what you wanted, excuse my misunderstanding:
    First, you need a panel for your frame:
    <code>
    public class FramePanel extends JPanel
    * Initialized by the (first call to the) constructor. This
    * Fill is used to paint the entire panel.
    private static TiledFill tiledFill = null;
    /*Constructors */
    public FramePanel()
    super();
    setOpaque(true);
    * Create a TiledFill object to draw the
    * background from preferences properties file
    public void getBackgroundImage()
    setForeground(Color.BLACK);
    setBackground(Color.WHITE);
    if (tiledFill == null)
    try
    FileImageInputStream file = new FileImageInputStream(*your image's file location*);
    BufferedImage image = ImageIO.read(file);
    ImageFill fill = new ImageFill(image);
    tiledFill = new TiledFill(fill, image.getWidth(), image.getHeight());
    catch (IOException e)
    e.printStackTrace();
    JOptionPane pane = new JOptionPane("Could not retrieve image in FramePanel");
    pane.setVisible(true);
    * Paint the area within <code>g.getClipBounds()</code>
    * making sure that the new tiles are aligned with a tileWidth
    * by tileHeight grid whose origin is at 0,0.
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    getBackgroundImage();
    /* To ensure that the tiles we paint are aligned with
    * a tileWidth X tileHeight grid whose origin is 0,0 we
    * enlarge the clipBounds rectangle so that its origin
    * is aligned with the origin of a tile and its size
    * is a multiple of the tile size.
    Rectangle clip = g.getClipBounds();
    int tw = tiledFill.getTileWidth();
    int th = tiledFill.getTileHeight();
    int x = (clip.x / tw) * tw;
    int y = (clip.y / th) * th;
    int w = (((clip.x + clip.width + tw - 1) / tw) * tw) - x;
    int h = (((clip.y + clip.height + th - 1) / th) * th) - y;
    Graphics gFill = g.create();
    tiledFill.paintFill(this, gFill, new Rectangle(x, y, w, h));
    gFill.dispose();
    </code>
    Now you need the fill and tiled fill classes size the image.
    <code>
    import java.awt.*;
    public class Fill
    public void paintFill(Component c, Graphics g, Rectangle r)
    g.setColor(c.getBackground());
    g.fillRect(r.x, r.y, r.width, r.height);
    public void paintFill(Container c, Graphics g)
    Insets insets = c.getInsets();
    int x = insets.left;
    int y = insets.top;
    int w = c.getWidth() - (insets.left + insets.right);
    int h = c.getHeight() - (insets.top + insets.bottom);
    paintFill(c, g, new Rectangle(x, y, w, h));
    public void paintFill(Component c, Graphics g, int x, int y, int w, int h)
    paintFill(c, g, new Rectangle(x, y, w, h));
    </code>
    <code>
    import java.awt.*;
    import java.awt.image.*;
    * Displays a single <code>BufferedImage</code>, scaled to fit the
    * <code>paintFill</code> rectangle.
    * <pre>
    * BufferedImage image = ImageIO.read(new File("background.jpg"));
    * final ImageFill imageFill = new ImageFill(image);
    * JPanel p = new JPanel() {
    * public c void paintComponent(Graphics g) {
    *     imageFill.paintFill(this, g);
    * </pre>
    * Note that animated gifs aren't supported as there's no image observer.
    public class ImageFill extends Fill
    private final static int IMAGE_CACHE_SIZE = 8;
    private BufferedImage image;
    private BufferedImage[] imageCache = new BufferedImage[IMAGE_CACHE_SIZE];
    private int imageCacheIndex = 0;
    * Creates an <code>ImageFill</code> that draws <i>image</i>
    * scaled to fit the <code>paintFill</code> rectangle
    * parameters.
    * @see #getImage
    * @see #paintFill
    public ImageFill(BufferedImage image)
    this.image = image;
    * Creates an "empty" ImageFill. Before the ImageFill can be
    * drawn with the <code>paintFill</code> method, the
    * <code>image</code> property must be set.
    * @see #setImage
    * @see #paintFill
    public ImageFill()
    this.image = null;
    * Returns the image that the <code>paintFill</code> method draws.
    * @return the value of the <code>image</code> property
    * @see #setImage
    * @see #paintFill
    public BufferedImage getImage()
    return image;
    * Set the image that the <code>paintFill</code> method draws.
    * @param image the new value of the <code>image</code> property
    * @see #getImage
    * @see #paintFill
    public void setImage(BufferedImage image)
    this.image = image;
    for (int i = 0; i < imageCache.length; i++)
    imageCache[i] = null;
    * Returns the actual width of the <code>BufferedImage</code>
    * rendered by the <code>paintFill</code> method. If the image
    * property hasn't been set, -1 is returned.
    * @return the value of <code>getImage().getWidth()</code> or -1 if
    * getImage() returns null
    * @see #getHeight
    * @see #setImage
    public int getWidth()
    BufferedImage image = getImage();
    return (image == null) ? -1 : image.getWidth();
    * Returns the actual height of the <code>BufferedImage</code>
    * rendered by the <code>paintFill</code> method. If the image
    * property hasn't been set, -1 is returned.
    * @return the value of <code>getImage().getHeight()</code> or -1 if
    * getImage() returns null
    * @see #getWidth
    * @see #setImage
    public int getHeight()
    BufferedImage image = getImage();
    return (image == null) ? -1 : image.getHeight();
    * Create a copy of image scaled to width,height w,h and
    * add it to the null element of the imageCache array. If
    * the imageCache array is full, then we replace the "least
    * recently used element", at imageCacheIndex.
    private BufferedImage createScaledImage(Component c, int w, int h)
    GraphicsConfiguration gc = c.getGraphicsConfiguration();
    BufferedImage newImage = gc.createCompatibleImage(w, h, Transparency.TRANSLUCENT);
    boolean cacheOverflow = true;
    for (int i = 0; i < imageCache.length; i++)
    Image image = imageCache;
    if (image == null)
    imageCache[i] = newImage;
    cacheOverflow = false;
    break;
    if (cacheOverflow)
    imageCache[imageCacheIndex] = newImage;
    imageCacheIndex = (imageCacheIndex + 1) % imageCache.length;
    Graphics g = newImage.getGraphics();
    int width = image.getWidth();
    int height = image.getHeight();
    g.drawImage(image, 0, 0, w, h, 0, 0, width, height, null);
    g.dispose();
    return newImage;
    * Returns either the image itself or a cached scaled copy.
    private BufferedImage getFillImage(Component c, int w, int h)
    if ((w == getWidth()) && (h == getHeight()))
    return image;
    for (int i = 0; i < imageCache.length; i++)
    BufferedImage cimage = imageCache[i];
    if (cimage == null)
    break;
    if ((cimage.getWidth(c) == w) && (cimage.getHeight(c) == h))
    return cimage;
    return createScaledImage(c, w, h);
    * Draw the image at <i>r.x,r.y</i>, scaled to <i>r.width</i>
    * and <i>r.height</i>.
    public void paintFill(Component c, Graphics g, Rectangle r)
    if ((r.width > 0) && (r.height > 0))
    BufferedImage fillImage = getFillImage(c, r.width, r.height);
    g.drawImage(fillImage, r.x, r.y, c);
    </code>
    Now it's just a simple matter of creating a frame and making the frame panel the frame's content pane:
    <code>
    import java.awt.BorderLayout;
    import java.awt.HeadlessException;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.UIManager;
    public class ImageFrame extends JFrame
    private FramePanel framePanel;
    //start of constructors
    public ImageFrame() throws HeadlessException
    super();
    init();
    public ImageFrame(String title) throws HeadlessException
    super(title);
    init();
    // end of constructors
    void init()
    try
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    catch (Exception e)
    System.out.println ("Unknown Look and Feel");
         framePanel = new FramePanel();
         this.getContentPane().add(framePanel, BorderLayout.CENTER);
         this.setContentPane(framePanel);
         ((JPanel)this.getContentPane()).setOpaque(false);
    </code>

  • Adding actionListener to a button

    pls i want to create an applet with buttons rectangle,circle,and polygon and having a textArea.when someone clicks on the rectangle buttons it draws a rectangle,on the circle buttons it draws a circle and on the polygon button it draws a polygon.pls i have already created the user interface how do i add the actionListeners to the respective buttons and reggister them.

    Hi,
    try something like this:
    JButton jButton1 = new JButton("yourbutton");
    jButton1.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent evt) {
                    someMethodThatDoesWhatYouNeed();
    });this is just a way to do it, there are other ways, just look around in the forum to discover them.
    JoY?TiCk

  • Adding actionListener to JOptionPane

    how do you add an actionListener to a JOptionPane?
    im using JOptionPane.showMessageDialog, and i want an event to happen when the user clicks on the "Okay" button

    Can you do something like this instead? Use a showConfirmDialog(...) istead of the showMessageDialog(...), then use the return value to determine which button the user pushed?
    int retValue = JOptionPane.showConfirmDialog(parent, message, Title, JOptionPane.OK_CANCEL_OPTION );
    if (retValue == JOptionPane.OK_OPTION)
      doOkayEvent();
    else
      doNotOkayEvent();

Maybe you are looking for

  • Filtering extended event in sql server 2008 r2

    This code has been generated in sql server 2012 (using the graphical interface). CREATE EVENT SESSION [backupsmssql] ON SERVER ADD EVENT sqlserver.sp_statement_starting( ACTION( sqlserver.client_app_name, sqlserver.client_hostname,sqlserver.nt_userna

  • HP Photosmart C5180 Will no longer feed 8x11 Photo paper from main tray

    My C5180 all in one will no longer feed 8x11 photo paper from main tray.  Rollers slip and will not pull paper in. Any suggestions?  583seve

  • When there is a battery on it. It never boots up

    Hello my laptop hp pavilion dv4 does not boot up when there is a battery on it even charger is plugged in. Only when I take the battery out and plugged in the charger my laptop works. What is the problem with my laptop. I already replaced a new batte

  • Using "Button" functionality

    I would like to have a button that work function as an Exit action on the last slide of my project. Therefore, I would like to name the button "Click to Exit". However, it does not appear that Captivate 3 offers that action as a choice under the "On

  • Re: Report of fraud

    I've logged on this evening to find £30 has been extracted from my account and lots of phone calls made to Somalia, Congo, South Africa etc. I've stopped the automatic subscription, changed my password. Anything else I should be doing? Regards