Reputation: 133
I have a ColorChooser panel, how can I make that appear when I click a JButton in my program? EDIT: I want to make it appear in a new frame that is resizable, movable and closable.
Upvotes: 2
Views: 2071
Reputation: 2952
You need to write an ActionListener for your JButton.
Something like this:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
*
* @author roger
*/
public class MyActListener extends JFrame implements ActionListener{
public MyActListener(){
super("My Action Listener");
JButton myButton = new JButton("DisplayAnything");
myButton.addActionListener(this);
this.add(myButton);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
// TODO code application logic here
MyActListener ma = new MyActListener();
}
@Override
public void actionPerformed(ActionEvent e) { // YOur code for your button here
if("DisplayAnything".equals(e.getActionCommand())){
Color c = JColorChooser.showDialog(this, "Color Chooser", Color.BLACK);
JButton displayAnything = (JButton)e.getSource();
displayAnything.setBackground(c);
}
}
Take a look at the Java tutorials of How to write an ActionListener. Look at the really big index in there to see basic tutorials about java in general.
Upvotes: 1
Reputation: 5134
You can look at the Java Swing Tutorial - ColorChooserDemo2: http://docs.oracle.com/javase/tutorial/uiswing/components/colorchooser.html#advancedexample
Basically, JColorChoose can be shown in a dialog: http://docs.oracle.com/javase/6/docs/api/javax/swing/JColorChooser.html
Color newColor = JColorChooser.showDialog(
ColorChooserDemo2.this,
"Choose Background Color",
banner.getBackground());
For the button to activate this file chooser:
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
//color is whatever the user choose
Color color = JColorChooser.showDialog(currentComponent, "Color Chooser", Color.WHITE);
JButton thisBtn = (JButton)e.getSource(); //or you can just use button if that's final or global
thisBtn.setBackground(color);
}
});
Upvotes: 2