• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Changing The ImageIcon Of a JButton With a click

 
Koh Khai Huat
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

I am working in a applet program and it require the user to click the button and then change the button's image to a different image how do u go about doing that. I am open to all suggestion and advice on how i am going to slove this problem, Thanks in advance

regards,
KKH
 
Vasu Reddy
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Please go through the below program.


import java.awt.*;
import javax.swing.*;
import java.applet.*;
import java.awt.event.*;

public class ActionExample extends Applet implements ActionListener
{

private JButton testButton;
private int test =1;
private ImageIcon testButtonIcon2;

public void init()
{
ImageIcon testButtonIcon1 = new ImageIcon("test1.gif");
testButtonIcon2 = new ImageIcon("test2.gif");

setLayout(new FlowLayout());
// testButton = new JButton("Test");
//testButton.setBackground(Color.blue);

testButton = new JButton(testButtonIcon1);
add(testButton);

testButton.addActionListener(this);

}


public void paint(Graphics g)
{

testButton.setBackground(Color.blue);
if(test != 1) {
//testButton.setBackground(Color.orange);
testButton.setIcon(testButtonIcon2);
}

}

public void actionPerformed(ActionEvent evt)
{

if (evt.getSource() == testButton)
test++;
repaint();
}

}
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just have an action listener that sets the icon. No need to override paint:

[ February 08, 2006: Message edited by: Jeff Albertson ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic