2011-07-15 30 views
0

如何添加JButton到我的Canvas如何將JButton添加到Canvas()?或者如何將JButton添加到Panel()並將Panel()背景設置爲透明?

public class mywindow extends Window 
{ 
    private static final Canvas canvas = new Canvas(); 
    private JButton button; 

    public mywindow 
    { 
     super(new Frame()); 
     button = new JButton("close"); 
     setLayout (new BorderLayout()); 

     //Step 1 - failed 
     add("North", canvas); 
     canvas.setSize(300,300); 
     canvas.setLocation(0,0); 

     // button = new JButton(my, "close"); will not work 
     // How can I add the button to the canvas? 

     //Step 2 - works, but it gets the background color, instead of real transparency. 
     //JPanel p = new JPanel(); p.setOpaque(false); 
     //p.setSize(300,300); p.setLocation(0,0); 
     //add("North", p); 
     //p.add("Left", button); 
    } 
} 
+3

你爲什麼要把AWT和Swing混合?爲什麼不簡單地堅持一個全Swing GUI?而且爲什麼你不必要地將類字段靜態化? –

回答

6

請不要混合AWTSwing。今天,需要Swing代碼JPanel。當然,可以將AWT與Swing混合使用,但是可能會將意外輸出到GUI。對於透明度,您必須查看How to Create Translucent and Shaped Windows並在此處搜索示例。

編輯:最好的和更好的輸出到GUI檢查,LayoutManagers如何工作。

+0

你給的透明鏈接。它會與此一起工作嗎? #java -version Java版本「1.6.0_22」 OpenJDK運行時環境(IcedTea6 1.10.2)(fedora-58.1.10.2.fc15-i386) OpenJDK服務器虛擬機(內部版本20.0-b11,混合模式) – YumYumYum

+0

@ 89899.3K這真的是操作系統和OpenJDK相關的問題,很難說,我無法給你答案,因爲我只有Win和Solaris管理員,我發佈的鏈接是關於Java SE Release 6 Update 10 API的教程, – mKorbel