如何在单击JButton时显示JPanel?

时间:2012-03-26 19:32:24

标签: java swing jpanel jbutton

我有一个ColorChooser面板,当我在程序中单击JButton时,如何才能显示它? 编辑: 我想让它出现在一个可调整大小,可移动和可关闭的新框架中。

2 个答案:

答案 0 :(得分:2)

您可以查看Java Swing教程 - ColorChooserDemo2: http://docs.oracle.com/javase/tutorial/uiswing/components/colorchooser.html#advancedexample

基本上,JColorChoose可以在对话框中显示: http://docs.oracle.com/javase/6/docs/api/javax/swing/JColorChooser.html

Color newColor = JColorChooser.showDialog(
                 ColorChooserDemo2.this,
                 "Choose Background Color",
                 banner.getBackground());

用于激活此文件选择器的按钮:

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);
    }  
}); 

答案 1 :(得分:1)

您需要为JButton编写一个ActionListener。

这样的事情:

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);
    }
}

查看Java tutorialsHow to write an ActionListener。看看那里真正的大索引,看看有关java的基本教程。