Simple Actionlistener problem
Hi,
This is probably a stupid problem, but my gui skills have kind of faded in a year.
In the following test code I'm adding a button to a panel, which is added to a frame. The button works fine, but it won't change it's color when pressed. Thanks in advance for any help.
Code :
public class test extends JFrame{
public static void main (String[]args) {
test t = new test();
}
public test() {
JButton knapp = new JButton("button");
JPanel panel = new JPanel();
knapp.addActionListener(new listener());
panel.add(knapp);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private class listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton test = (JButton)e.getSource();
test.setBackground(Color.BLACK);
System.out.println("why hello thar");
}
}
}
Re: Simple Actionlistener problem
This is not an ActionListener issue as much as it is a JButton issue.
It is all good and well to set the color of a JButton, but it will have no effect if the JButton is still transparent. You have to remember to use the JComponent.setOpaque(boolean isOpaque) method for the color to show. So, to fix this, simply before (or after) setting the color of your JButton, include the statement:
and you should be good.
Re: Simple Actionlistener problem
I'm not sure if the fact that I'm using a mac should have anything to say, but all it did was this:
http://i56.tinypic.com/2cdwgmb.png
Did as you said and put knapp/test.setOpque(true); above or under where I set the color. Thanks for your interest in this matter, has been holding me up for a while..
Re: Simple Actionlistener problem
Quote:
Originally Posted by
olemagro
I'm not sure if the fact that I'm using a mac should have anything to say
The newer jdk's may have somewhat solved this on mac, but I recall the opacity being an issue for JButton's on my older system. I worked around the issue by creating icons for my buttons rather than using the default OS look and feel.
Re: Simple Actionlistener problem
Quote:
Originally Posted by
copeg
The newer jdk's may have somewhat solved this on mac, but I recall the opacity being an issue for JButton's on my older system.
Cheers, I'll look into it.
Re: Simple Actionlistener problem
Couldn't be arsed getting a new eclipse, but I'm fairly confident it's the operating system that prevents the button itself to change its color. I'll just go around it like you did copeg.
Thanks to both of you :)