2010-11-12 32 views
1

我無法將按鈕添加到此JFrame,它與我正在使用的Java圖形事件有衝突。評論中的內容是我到目前爲止所嘗試的內容,並不奏效。將按鈕添加到使用java圖形的contentPane

import java.awt.*; 
import javax.swing.*; 
public class JFramePaint1 { 
//Button draw; 
public static JButton b = new JButton("button"); 

    public static void main(String[] a) { 

    JFrame f = new JFrame(); 

     f.setTitle("Drawing Graphics in Frames"); 
    f.setSize(800, 650); 
    f.setLocation(200,50); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    //f.add(b); 

    f.setContentPane(new ContentComponent()); 
    //f.getContentPane.add(b); 

     f.setVisible(true); 
    } 
    static class ContentComponent extends JComponent { 
    public int activa = 1; 
// add(b); 
    //this.add(b); 
    public void paint(Graphics g) { 


    g.setColor (Color.RED); 
    g.fillRect(0, 0, 800, 650); 
    if(activa == 1){ 

    g.setColor(Color.BLACK); 
    g.drawRect(40, 20, 150, 80); 
    int x = 40; 
    int y= 20; 
    for(int i = 0; i< 4; i++){ 

    g.drawRect(x+10, y+10, 150, 80); 
    x = x+10; 
    y = y+10; 
    } 

    } 

    // g.fillRect(20, 10, 100, 60); 
    // g.drawRect(40, 20, 150, 80); 
     } 
    } 
} 

回答

1

ContentComponent子類JPanel代替JComponent,然後直接或通過添加f.getContentPane().add(b)按鈕到面板上。

JPanel被設計爲具有子組件;它是一個容器。

2

不管你使用JComponent還是JPanel,都是容器。

區別在於默認情況下,JPanel使用FlowLayout,但JComponent不使用任何佈局管理器,因此如果您想使用JCompnent,則需要設置佈局管理器。

自定義繪畫應該通過重寫paintComponent()方法來完成。你還應該調用super.paintComponent(...)。兩者之間的另一個區別是JPanel會自動繪製背景,但JComponent不會。

此外,請與您的代碼的格式一致。始終使用空格或製表符。由於格式化,發佈的代碼非常糟糕。

+0

感謝您的澄清Rob。 – 2010-11-12 19:01:02