JButton dispatchEvent problem

Hi,
I've got JButtons in a JTable which means I have to capture the mouse events and forward them to the button.
I do this with a mouse listener on the table, and the lines:
buttonEvent = (MouseEvent)SwingUtilities.convertMouseEvent(table, e, button);
button.dispatchEvent(buttonEvent);
System.out.println(buttonEvent);
table.repaint();where 'e' is the original mouse event. This produces, for example:
java.awt.event.MouseEvent[MOUSE_CLICKED,(145,167),button=1,modifiers=Button1,clickCount=1]
on
javax.swing.JButton[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.5 <snip> text=Delete,defaultCapable=true]but yet nothing happens to the button. Is this a coordinate problem, or am I missing something else, as I don't really know what I'm doing?
Cheers,
Rob

MOUSE_CLICKED,(145,167),Well I'm guessing that you can't just convert the table coordinates and use them as the button coordinates because the button isn't that big.
An alternative approach might be to use the doClick() method of the button.
In case that doesn't work, here's something I've been playing with that may help:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableButton3 extends JFrame
     public TableButton3()
          String[] columnNames = {"Date", "String", "Integer", "Decimal", ""};
          Object[][] data =
               {new Date(), "A", new Integer(1), new Double(5.1), "Delete1"},
               {new Date(), "B", new Integer(2), new Double(6.2), "Delete2"},
               {new Date(), "C", new Integer(3), new Double(7.3), "Delete3"},
               {new Date(), "D", new Integer(4), new Double(8.4), "Delete4"}
          DefaultTableModel model = new DefaultTableModel(data, columnNames);
          JTable table = new JTable( model )
               //  Returning the Class of each column will allow different
               //  renderers to be used based on Class
               public Class getColumnClass(int column)
                    return getValueAt(0, column).getClass();
          JScrollPane scrollPane = new JScrollPane( table );
          getContentPane().add( scrollPane );
          //  Create button column
          ButtonColumn buttonColumn = new ButtonColumn(table, 4);
     public static void main(String[] args)
          TableButton3 frame = new TableButton3();
          frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
          frame.pack();
          frame.setVisible(true);
     class ButtonColumn extends AbstractCellEditor
          implements TableCellRenderer, TableCellEditor, ActionListener
          JTable table;
          JButton renderButton;
          JButton editButton;
          String text;
          public ButtonColumn(JTable table, int column)
               super();
               this.table = table;
               renderButton = new JButton();
               editButton = new JButton();
               editButton.setFocusPainted( false );
               editButton.addActionListener( this );
               TableColumnModel columnModel = table.getColumnModel();
               columnModel.getColumn(column).setCellRenderer( this );
               columnModel.getColumn(column).setCellEditor( this );
          public Component getTableCellRendererComponent(
               JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
               if (hasFocus)
                    renderButton.setForeground(table.getForeground());
                     renderButton.setBackground(Color.WHITE);
               else if (isSelected)
                    renderButton.setForeground(table.getSelectionForeground());
                     renderButton.setBackground(table.getSelectionBackground());
               else
                    renderButton.setForeground(table.getForeground());
                    renderButton.setBackground(UIManager.getColor("Button.background"));
               renderButton.setText( (value == null) ? "" : value.toString() );
               return renderButton;
          public Component getTableCellEditorComponent(
               JTable table, Object value, boolean isSelected, int row, int column)
               text = (value == null) ? "" : value.toString();
               editButton.setText( text );
               return editButton;
          public Object getCellEditorValue()
               return text;
          public void actionPerformed(ActionEvent e)
               fireEditingStopped();
               System.out.println( "Action: " + e.getActionCommand() );
}

Similar Messages

  • JButton.setBackground() Problem

    Hi All,
    When i apply the setBackground() Method to a JButton to set its Background, i face i Problem :
    Under Mac Os : The JButton DOSE NOT change its color,
    when i take my code to my other computer under Windows : OK, the JButton change...
    i am wondering ....
    1) Why under my Mac OS i face this problem...
    2) and Why i get two different results from a same code ??? Java is not Portable?? and independant of the OS?? or it is the swing that makes the problem???
    My code is so simple :
    MyJButton.setBackground(new Color(255,100,100));
    Thanks to any help...

    ellias2007 wrote:
    Sorry because it is the first time for me in this forum....
    thanks for any help...
    Sorry againMost of us don't like disjointed discussions or repeating effort for a problem that has already been solved elsewhere. Thanks for your reply. A link to one discussion: [http://www.java-forums.org/awt-swing/25986-jbutton-setbackground-problem.html]
    If you have cross-posts elsewhere, please post links in all of them to each other or to one central location.

  • JButton imageIcon problem

    hello ,
    i am facing a problem in changing the imageicon of jbutton in my application.
    i want to change imageicon for few seconds and than again change it to original imageicon....
    is it possible?????????????i have tried but after initializing button with one imageicon we are not able to change that icon again..
    so what should i do...it is compulsory to change take two image for button.....
    please help

    Set up a Timer. You use the setIcon(...) method to change the icon. Then you start a Timer to fire in a few seconds and use the setIcon(...) method to change the image back to its original value.

  • DispatchEvent() problem (bug?)

    Hi all.
    I'm using a glasspane to process all mouse clicks that occur on inert, or 'no-state' components that don't require to be redrawn when they are clicked (ie
    SwingUtilities.getDeepestComponentAt(contentPane, x, y)
    returns a component such as a jpanel or a jlabel), and i'm redirecting all other events using:
    MouseEvent event2 = SwingUtilities.convertMouseEvent(glassPane, event, component);component.dispatchEvent(event2);
    The problem is that the dispatchEvent method doesn't trigger changes in the components' state or GUI that would normally occur if I wasn't using a glasspane: the checkmarks for checkboxes don't appear, comboboxes don't display their menus, textfields don't display a caret, buttons don't click, tabbedpanes don't change tabs, etc.
    I've tried the using component.doClick() and it works fine, but i'm stumped for any component that doesn't extend AbstractButton. I don't feel like adding mouse listeners to all my components (there are over 100 of them!) just to call processMouseEvent (whether or not that would solve my problem) because they don't otherwise need to listen for mouse clicks (validations are processed when an action occurs on an OK button). Do I need to redirect the mouse events in a different way? Is there a command i should add after the dispatchEvent statment?
    I could really use some help. Thanx :)

    Thanx viravan for your input. After trying it out, however, a few problems arose:
    A) Without considering the fact that you're suggestion would lead to a bad archetacture, as you probably know ( ;o) ), that would require that I add a mouse listener to all components just to make the glasspane visible again...and, like i said above, adding mouse listeners to over 100 components that otherwise don't need them is something i'm trying to avoid.
    B) I tested the following method on a single checkbox and it works, the checkmark is drawn, even with a visible glasspane, after recieving the redipatched event:checkbox.addMouseListener(new MouseAdapter()
                public void mouseClicked(MouseEvent event)
                    JCheckBox checkbox = (JCheckBox) event.getSource();
                    checkbox.setSelected(!checkbox.isSelected());
            });So this isn't a matter of whether or not the glasspane is visible.
    C) Adding some code (see below) in the glasspane mouselistener method revealed that the state of the JCheckBox did in fact not change so it's not only a matter of paint, but a matter of changing state.                        System.out.println("State: " + ((JCheckBox) component).isSelected());
                            glassPane.setVisible(false);
                            component.dispatchEvent(event2);
                            System.out.println("State: " + ((JCheckBox) component).isSelected());The print commands return "State: false" both before and after the dispatchEvent command.

  • DispatchEvent problem between Classes

    So, what I am trying to do is to dispatchEvent(new Event("gameOver") from my score.as class.
    That "gameOver" event is supposed to be picked up with "score.addEventListener("gameOver", lostGame, false, 32);" in my main-stage class Engine.as, and in my ships class: Ship.as.
    The problem is that it doesn't seem that my Ship.as refreshes the score.as data, and the event is only executed if I do the scorecheck when the score = 0, so the events will dispatch at start.
    That is the only time my Ship.as picks up the event. If I set it to be for example 100, it doesn't pick it up.
    Any idea on what to do? Thank you on advance!
    (If there is something someone doesn't understand, I will provide script/code)

    Hi,
    I can see that the problem is not dispatching the event (correct me if I'm wrong).
    Do you instantiate score on both Engine.as and Ship.as?
    If you do then you have two separate scores, independent from one another. Make some traces to see what's happening.
    If that's the case you have to instantiate only one time (in Engine.as, which I suppose it's your main class), and then have the Ship.as to listen to that instance, or have the Engine class send the value to Ship when it changes.
    Hope it helps.

  • JButton display problem

    I would have thought the following would bring up two identical MainWindows, but in fact the buttons in the second one look slightly different.
    public class Main {
         public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                     setUpApp();
         private static void setUpApp() {
              MainWindow mainWindow = new MainWindow();
              MainWindow mainWindow2 = new MainWindow();
    }This is what the two windows look like after display: (How do URLs work?)
    I'm not really sure what code to paste other than this because I would think the code is identical for both.

    Slow day, and I actually created an SSCCE:
    import javax.swing.*;
    import java.awt.*;
    public class MainWindow {
       private JFrame topLevelContainer;
       public MainWindow() {
          topLevelContainer = new JFrame();
          topLevelContainer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          topLevelContainer.setPreferredSize(new Dimension(400, 400));
          Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
          topLevelContainer.setTitle("ChatApp");
          topLevelContainer.setVisible(true);
          JPanel contentPane = new JPanel(new BorderLayout(2, 2));
          contentPane.setBorder(BorderFactory.createLineBorder(Color.BLUE));
          contentPane.setBackground(Color.BLUE);
          topLevelContainer.setContentPane(contentPane);
          JPanel sendingTo = new JPanel();
          sendingTo.setOpaque(false);
          sendingTo.setBorder(BorderFactory.createTitledBorder("Sending To"));
          contentPane.add(sendingTo, BorderLayout.PAGE_START);
          JPanel messageLog = new JPanel();
          messageLog.setOpaque(false);
          messageLog.setBorder(BorderFactory.createTitledBorder("Message Log"));
          contentPane.add(messageLog, BorderLayout.CENTER);
          JPanel sendPanel = new JPanel(new BorderLayout(2, 0));
          sendPanel.setBackground(Color.BLUE);
          JTextArea sendMessageArea = new JTextArea("Send Message Area", 5, 30);
          sendMessageArea.setOpaque(false);
          sendPanel.add(sendMessageArea, BorderLayout.CENTER);
          JButton _sendMessage = new JButton("Send Message");
          sendPanel.add(_sendMessage, BorderLayout.LINE_END);
          contentPane.add(sendPanel, BorderLayout.PAGE_END);
          try {
             UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
          } catch (ClassNotFoundException e) {
             e.printStackTrace();
          } catch (InstantiationException e) {
             e.printStackTrace();
          } catch (IllegalAccessException e) {
             e.printStackTrace();
          } catch (UnsupportedLookAndFeelException e) {
             e.printStackTrace();
          topLevelContainer.pack();
       private static void createAndShowUI() {
          new MainWindow();
          new MainWindow();
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
    }And in it, I notice that you're setting your GUI visible before adding components and your setting the look and feel after you've created and added components, and this seems a bit backwards. The look and feel issue is what is causing the problem that you are noticing.

  • JButton Adding Problem

    Hi everyone,
    First, like to say I appreciate all your help. I have come here for help before and I always get my questions answered. Thanks.
    Here is my problem:
    I've created a JPanel and added this panel to a JFrame. The JPanel has a MouseListener and a MouseMotionListener. I am tryin to add JButtons to the JPanel at positions passed from the MouseMotionListener, but everytime I attempt this, the JButton pops to the top left corner of the screen. I don't know if I should use a layout manager on the JPanel and if I do, I don't know which one to use. I've tried using the SpringLayout, but was unsuccessful at deploying it.
    Appreciate any help.
    Thanks again.

    Null layout is not recommended, see my earlier post. Here is a simple SpringLayout that does the same thing.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TestSpring extends JFrame
         Container cp;
         int mpx, mpy;
         int MINX= 80;
         int MINY=20;
         JLabel txt = new JLabel("use mouse to position buttons, drag to set size");
         SpringLayout slay = new SpringLayout();
         MouseInputAdapter mia = new MouseInputAdapter()
              public void mousePressed(MouseEvent evt){mousePress(evt);}
              public void mouseReleased(MouseEvent evt){mouseRelease(evt);}
         TestSpring()
              super("TestSpring");
              cp = getContentPane();
              addWindowListener(new WindowAdapter()
              {public void windowClosing(WindowEvent evt){System.exit(0);}});
              cp.addMouseListener(mia);
              cp.setLayout(slay);
              cp.add(txt);
              setBounds(0,0,700,400);
         void mousePress(MouseEvent evt)
              mpx = evt.getX();
              mpy = evt.getY();
         void mouseRelease(MouseEvent evt)
              int x,y,dx,dy;
              x = evt.getX();
              y=evt.getY();
              dx = x-mpx;
              dy = y-mpy;
              if(dx < 0){dx = -dx; mpx = x;}
              if(dy < 0){dy = -dy; mpy = y;}
              JButton jb = new JButton(mpx+","+mpy);
              cp.add(jb);
              setCPosition(jb,mpx,mpy);
              if(dx < MINX)dx = MINX;
              if(dy < MINY)dy = MINY;
              setCSize(jb, dx, dy);
              cp.validate();
         void setCPosition(Component c, int x, int y)
              slay.getConstraints(c).setX(Spring.constant(x));
              slay.getConstraints(c).setY(Spring.constant(y));
         void setCSize(Component c, int w, int h)
              slay.getConstraints(c).setWidth(Spring.constant(w));
              slay.getConstraints(c).setHeight(Spring.constant(h));
         // the main startup function
         public static void main(String[] args)
              new TestSpring().show();
    }

  • JButton clicked problem?

    I have a Jbutton and on button clicked, action is performed.
    Now if mouse is just clicked but moved only one pixel(means focus is still on the button) , action will not occur. It works only if the button is clicked and mouse does not move at all. I want action if the button is clicked and does not leave the button forground area until it is released.
    thnx

    Sounds like there is a problem in your code. Only can make wild guesses based on the lack of info. (If you post code, please spare us the pain of looking at all of it, just create a simple example).

  • JButton base problem

    Hi All,
    I have a primitive /as I known/ problem with the JButton.
    I create one, and set the text with this 'Show'. I set the font /eg. Arial/ and it's size to 9.
    If I set the required size of the button the text is not shown. /shown only .../
    When show the text correctly the width of button is very large for me.
    How can I make a button which hase a same width such as the text in it.?
    thx.

    Once you've set the font and text for a button, you can find out its preferred size using getPreferredSize.
    Typically buttons will add on padding between the text and the border. This is known as the "margin" and can be changed using setMargin.
    You can set the margin for all buttons using UIManager's Button.margin property.
    Hope this helps.

  • JButton NullPointerException problem

    Hi
    I was wondering if you guys can help me out on this one. I'm been prompted with a NullPointerException whenever I click on either of the 2 buttons.
    Thanks guys
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Alarm extends JPanel implements ActionListener{
        private JTextArea messageField;
        private JButton alarmOn, alarmOff;
        private JLabel alarmLED;
        public Alarm(){
            super.setPreferredSize(new Dimension(200,300));
            //configuring components;
            JButton alarmOn = new JButton("On");
            alarmOn.addActionListener(this);
            JButton alarmOff = new JButton("OFF");
            alarmOff.addActionListener(this);
            JLabel alarmLED = new JLabel("Alarm OFF");
            alarmLED.setOpaque(true);
            alarmLED.setBackground(Color.GREEN);
            messageField = new JTextArea(2,20);
            messageField.setEditable(false);
            messageField.setPreferredSize(new Dimension(200, 200));
            this.add(messageField, BorderLayout.PAGE_START);
            alarmOn.setPreferredSize(new Dimension(80, 20));
            this.add(alarmOn, BorderLayout.LINE_START);
            alarmOff.setPreferredSize(new Dimension(80, 20));
            this.add(alarmOff, BorderLayout.CENTER);
            alarmLED.setPreferredSize(new Dimension(65, 30));
            this.add(alarmLED, BorderLayout.LINE_END);
         public void actionPerformed(ActionEvent event){
            if(event.getSource()==this.alarmOn){
                this.alarmLED.setBackground(Color.RED);
                this.alarmLED.setText("Alarm ON");
            }else{
                this.alarmLED.setBackground(Color.GREEN);
                this.alarmLED.setText("Alarm OFF");
    }//end of class;

    I figured it out...I think i declared the button twice.
    Funny...it seems easier to spot it in this forums comparing it on BlueJ
    Will someone recommend me a better java client then BLueJ?
    Preferably user friendly kinds
    Thanks

  • [bc4j] Urgent jbutton binding problem

    Hi,
    I have a working application with a few panels, and a few viewobjects, viewlinks, etc. I can use the navigator to navigate through the records, etc, everything works fine.
    But when I add a jbutton to the panel, with an action binding for the view object ('insert new record' or 'next'), then when starting up the application, the view object begins to spill, all records seem to be loaded and spilled to the spill-table.
    If I remove the model form the jbutton and re-run, everything works fine again. What could cause this? All other binded controls (navigationbar, several jtextfields, and even a jtree) work fine, but the jbutton causes spills.
    And not even when I click it, but during startup of the app!
    Any idea?
    Greetings,
    Ivo

    Bug#2772798 filed after reproducing using your testcase. Thanks.
    Shailesh got back to me with this analysis:
    No bindings should force a range size of -1 by default except for Lov Bindings on Combo and List Boxes where all the data is needed on the client side control.
    ButtonlActionBinding's create method is setting the rangesize of the iterator to -1 leading to all rows being fetched. The workaround is to set the range size on the iterator in setPanelBinding() method after jbInit() to a desired size.
    Here's a line I added to Ivo's setPanelBinding() method of his PanelFootballView1.java class...
    jbInit();
    panelBinding.findIterBinding("FootballViewIter1").getRowSetIterator().setRangeSize(1);

  • Dispatchevent problem

    I am trying to run a basic eventlistener but unable to run, in debugger shows both the init and creationcomplete methods are executed but the showText is  not able to run what might be the reason?
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
                   creationComplete="onComplete()"
                   initialize="init()">
        <fx:Script>
            <![CDATA[
                public static const callMe="Call_Event";
                 public    function onComplete():void{
                    dispatchEvent(new Event(callMe,true,false));
               public    function init():void{
                    group.addEventListener(callMe,showText);
        public function showText(e:Event):void{
                      rt.visible=true;   
            ]]>
        </fx:Script>
        <s:VGroup id="group">
        <s:RichText 
            id="rt"
            text="Hai"
            visible="false">
        </s:RichText>
        </s:VGroup>
    </s:Application>
    thanks for reading.

    Hi, Your dispatched event is not reaching to 'group' so it is not listening it.
    You are dispatching it at the top application level.
    So you can listen it at application level by adding listener at application itself rather than on group as this.addEventListener(CALL_ME_EVENT,showText);
    or
    dispatching event from group container i.e. group.dispatchEvent(new Event(CALL_ME_EVENT,true,false));
    I have done it by dispatching event at group level and it works.
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx"
                   initialize="{init();}"
                   creationComplete="{onComplete();}"
                   minWidth="955" minHeight="600">
        <fx:Declarations>
            <!-- Place non-visual elements (e.g., services, value objects) here -->
        </fx:Declarations>
        <fx:Script>
            <![CDATA[
                import mx.controls.Alert;
                public static const CALL_ME_EVENT:String="Call_Event";
                public function init():void
                    group.addEventListener(CALL_ME_EVENT,showText);
                public function onComplete():void
                    group.dispatchEvent(new Event(CALL_ME_EVENT,true,false));
                public function showText(e:Event):void
                    rt.visible=true; 
                    trace("Done.. :)");
            ]]>
        </fx:Script>
        <s:VGroup id="group">
            <s:RichText id="rt"    text="Hai" visible="false"/>
        </s:VGroup>
    </s:Application>
    Hope it helps you.
    Abhinav Sharma

  • JButton Icon Problem

    Hi! How can I change the icon attached to a JButton when running the application? setIcon method doesn't work.. Not even if I put an updateUI() after that.. Thanks!

    Hi! How can I change the icon attached to a JButton
    when running the application? By calling setIcon.
    setIcon method doesn't work.. Yes it does.
    Not even if I put an updateUI() after that..There is no need for that as the button will be updated automatically. So you must be doing something wrong. To begin with, maybe you can explain what you mean by "doesn't work".

  • Problem with doClick(int i) inside a while loop.

    I'm doing a boring "watch and repeat" game. I have 9 JButtons. I want the computer to randomly click on those buttons and the player have to repeat the numbers in the correct order.
    My problem is when the computer is showing which buttons to press. My code looks like this (sorry about the formatting):
    ActionListener aL = new ActionListener() {
    public void actionPerformed(ActionEvent e){
    if(e.getSource()==start){
    while (something something){
    switch(here is a random number between 1 and 9){
    case 1: j1.doClick(900); //j1 is a JButton
    My problem is that the doClick doesn't release the button during the whole loop. If it loops 5 times, then all the pressed buttons will remain pressed down for as long as the loop is running. I've tried to call repaint, but it doesn't work. All buttons remains pressed even though they should go back to normal after 0,9 seconds.
    I don't think the ActionListener should cause any problem. And neither does the switch. It seems like the application simple won't repaint itself until the loop is finished.

    Ok here is the code to make work what you want. Note that it looks ugly :)
    import javax.swing.*;
    import java.awt.*;
    public class Test extends JFrame implements Runnable {
      private JButton btn1, btn2, btn3;
      public Test() {
        super("Test");
        btn1 = new JButton("1");
        btn2 = new JButton("2");
        btn3 = new JButton("3");
        JPanel p = new JPanel(new FlowLayout());
        p.add(btn1);
        p.add(btn2);
        p.add(btn3);
        getContentPane().add(p, BorderLayout.CENTER);
        pack();
        setVisible(true);
        Thread t = new Thread(this);
        t.start();
      public static void main(String args[]) {
        new Test();
      public void run() {
        //This run method is NOT in the event thread
        while (true) {
          try { Thread.sleep(1000); } catch (InterruptedException e) {}
          SwingUtilities.invokeLater(new Worker(btn1));
          try { Thread.sleep(1000); } catch (InterruptedException e) {}
          SwingUtilities.invokeLater(new Worker(btn2));
          try { Thread.sleep(1000); } catch (InterruptedException e) {}
          SwingUtilities.invokeLater(new Worker(btn3));
      class Worker implements Runnable {
        JButton button = null;
        public Worker(JButton b) {
          button = b;
        public void run() {
          button.doClick(100);
    }

  • Icon behavior in Jbuttons

    Hi,
    I'm a new programmer in java and I need help.
    I have to do one JButton matrix and I have to set one Icon to each JButton.The problem is that, I don't know how I can do to set more Icons to the same JButton and changing the Icon by click. I have to set 4 .gif Icon so after the 4th click i have to see again the 1st Icon. Hoping is clearly.
    Thanks.
    Code:
    package newpackage;
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    * @author Student
    public class myform extends javax.swing.JFrame {
    JButton[][] buttons = new JButton[5][5];
    Integer[][] i = new Integer[5][5];
    Integer[][] j = new Integer[5][5];
    ImageIcon icon = new ImageIcon("c:/0.gif");
    String name=new String();
    ImageIcon icon1 = new ImageIcon
    ("C:/1.gif");
    ImageIcon icon2 = new ImageIcon
    ("C:/2.gif");
    ImageIcon icon3 = new ImageIcon
    ("C:/3.gif");
    /** Creates new form NewJFrame */
    public myform() {
    initComponents();
    setTitle("Button");
    setBounds(8,8,0,0);
    for (int i=1;i<buttons.length;i++){
    for (int j=1;j<buttons.length;j++){
    buttons[j] = new JButton(new ImageIcon ("c:/0.gif"));
    this.getContentPane().add(buttons[j]);
    this.pack();
    buttons[j].addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    JButtonActionPerformed(evt);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    getContentPane().setLayout(new java.awt.GridLayout(5, 6));
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    pack();
    // </editor-fold>
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new myform().setVisible(true);
    private void JButtonActionPerformed(java.awt.event.ActionEvent evt) {
    JButton who = (JButton) evt.getSource();
    if (who.equals(who)){
    who.setIcon(icon1);
    //return a;
    // Variables declaration - do not modify
    // End of variables declaration
    }

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class IconSwap implements ActionListener {
        BufferedImage[] images;
        int imageIndex = 0;
        public IconSwap(BufferedImage[] images) {
            this.images = images;
        public void actionPerformed(ActionEvent e) {
            JButton button = (JButton)e.getSource();
            ImageIcon icon = new ImageIcon(images[++imageIndex % images.length]);
            button.setIcon(icon);
        private JPanel getContent() {
            JButton button = new JButton(new ImageIcon(images[0]));
            button.addActionListener(this);
            JPanel panel = new JPanel(new GridBagLayout());
            panel.add(button, new GridBagConstraints());
            return panel;
        public static void main(String[] args) throws IOException {
            String[] ids = {
                "-----", "-c---", "-cg--", "-c-h-"
            BufferedImage[] images = new BufferedImage[ids.length];
            for(int j = 0; j < images.length; j++)
                images[j] = ImageIO.read(new File("images/geek" + ids[j] + ".gif"));
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new IconSwap(images).getContent());
            f.setSize(300,300);
            f.setLocation(200,200);
            f.setVisible(true);
    }

Maybe you are looking for

  • Can not connect printer to iMac running osx 10.6.8

    Hi, I am a complete novice and need help please I had an iMac and it ran great albeit a few little glitches with our HP Mulitfunction printer but I thought the printer was a dud.  At christmas I got hubby a new ipod and things went downhill from ther

  • Error during sap r/3 installation  at update databse statistics

    Hi friends, I am getting an error during sap r/3 installation almost at the last stage. the error is  at update database statistics. my configuration is os: windows 2000 server. d/b: oracle 9i. erp: sap 4.7 ee During oracle installation stage the oui

  • Problem with hx:fileupload

    Hello! I have a new problem. I'm using a hx:fileupload tag, but when I write in this input text intead of selecting the browse button I get a javascript error. I have read that is a problem only with IE, so I need to make readonly this field. I have

  • How can I erase music on my iPad?

    I really want to erase my music list on my iPad, but it syncs to my Apple ID account, and I can't also find a way to erase these songs from the account as well. I've never found a way to erase music on an apple device before, but now that I want to r

  • How to prepare for DBA Interview

    Dear All, Sorry for posting this thread. But i need your suggestions to improve my skills. So kindly give me your suggestions and tips. What are the mail things i have to prepare. Thanks in advance. Moorthy.GS