2012-03-26 37 views
2

我有一個ColorChooser面板,當我在程序中單擊一個JButton時,該如何顯示? 編輯: 我想使它出現在一個新的框架是可調整大小,可移動和可關閉。如何在單擊JButton時使JPanel出現?

+0

需要更多信息。從哪裏出現?從另一個面板後面的同一個窗口?在對話框中彈出? – 2012-03-26 19:46:58

+0

我想讓它出現在一個可調整大小,可移動和可關閉的新框架中。 – 2012-03-26 19:57:50

+0

您是如何獲得ColorChooser的?與你自己的面板一樣。 – Randy 2012-03-26 20:02:34

回答

1

你需要爲你的JBu編寫一個ActionListener tton。

事情是這樣的:

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

看看的How to write an ActionListenerJava tutorials。看看那裏真的很大的索引,通常可以看到關於java的基本教程。

+0

如果這是爲JButton編寫動作監聽器的正確方法,我能否從其他讀者那裏獲得反饋?當按鈕的數量開始增加時,爲它實現ActionListener的類是否更好?或者不是'myButton.addActionListener(this);'make'myButton.addActionListener(new MouseListener(){...})' – Roger 2012-03-26 20:31:55

+1

我個人比較喜歡使用匿名內部類,比如註釋中的最後一個例子,並調用類從那裏實施邏輯。這樣,就不需要定義動作命令了,正如你注意到的那樣,當添加新按鈕時,你的actionPerformed方法會變得相當長。所有的例子都是有效的,當然在使用。 – mort 2012-03-26 20:41:26

+0

謝謝!還有一個問題,我怎麼才能使按鈕顯示我選擇的顏色? – 2012-03-26 20:46:50

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

謝謝:) 如何在我的JButton的ActionPerformed中實現該功能? – 2012-03-26 20:21:05

+0

好的,謝謝,還有一個問題,我怎樣才能使按鈕顯示我選擇的顏色? – 2012-03-26 20:46:38