2011-09-06 78 views
2

我想學習java和我正在練習一個簡單的程序與2個簡單的按鈕。這裏是我的代碼:全部按鈕窗口 - Java

import javax.swing.*; 

public class Main { 

    public static void main(String[] args) { 

    JFrame frame = new JFrame("Askhsh 3");  
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    ColorJPanel application = new ColorJPanel(); 
    frame.add(application); 
    frame.setSize(500,500); 
    frame.setVisible(true); 

    } 

} 

和類ColorJPanel:

import java.awt.*; 
import javax.swing.*; 


public class ColorJPanel extends JPanel{ 

    public void paintComponent(Graphics g) 
    { 
    super.paintComponent(g); 
    this.setBackground(Color.WHITE); 

    JButton arxikopoihsh = new JButton("Αρχικοποίκηση"); 

    JButton klhrwsh = new JButton("Κλήρωση"); 

    add(arxikopoihsh); 
    add(klhrwsh);  

    this.revalidate(); 
    this.repaint(); 

    } 
} 

正如你可以看到我想要做的,現在的唯一的事情就是將2點簡單的按鈕,什麼也不做!這裏是我的輸出: http://imageshack.us/photo/my-images/847/efarmogh.jpg/ 當我運行應用程序時,我看到按鈕填滿窗口! 請注意,如果我刪除「this.revalidate();」命令我必須調整窗口的大小來查看按鈕! 非常感謝您的時間:)

+0

使用'frame.pack()'每3行代碼) –

+0

我試圖這樣,在在代碼中的幾個地方,並沒有解決問題,如果我把它放在程序的末尾我得到一個非常小的窗口,當我調整它時,我又得到很多按鈕:(感謝您的時間無論如何:) – VGe0rge

+0

@flying:每3個代碼行?沒有意義。 –

回答

4

不要在paintComponent中添加組件。此方法僅用於繪畫,不適用於程序邏輯或構建GUI。要知道,這個方法經常被JVM調用,而且大多數情況下這個方法不受你控制,並且也知道當你要求通過repaint()方法調用它時,這只是一個建議,油漆管理員有時可能會選擇忽略您的請求。 paintComponent方法必須精簡而快速,因爲任何減慢速度的方法都會減慢應用程序的感知響應速度。

在你當前的代碼中,我甚至沒有看到需要重寫paintComponent方法,所以除非你需要它(例如爲了實例組件的自定義繪畫),我建議你擺脫這種方法(以及重新繪製和重新驗證的調用)。相反,將組件添加到類的構造函數中,並確保在添加組件後並在調用setVisible(true)之前打包頂層容器。最重要的 - 閱讀Swing教程,因爲這些都在這裏覆蓋。

例如,

Main.java

import javax.swing.*; 

public class Main { 

    public static void main(String[] args) { 

    JFrame frame = new JFrame("Askhsh 3"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    ColorJPanel application = new ColorJPanel(); 
    frame.add(application); 
    frame.pack(); 
    frame.setVisible(true); 
    } 
} 

ColorJPanel.Java

import java.awt.*; 
import javax.swing.*; 

public class ColorJPanel extends JPanel{ 
    public static final int CJP_WIDTH = 500; 
    public static final int CJP_HEIGHT = 500; 

    public ColorJPanel() { 
    this.setBackground(Color.WHITE); 
    JButton arxikopoihsh = new JButton("Αρχικοποίκηση"); 
    JButton klhrwsh = new JButton("Κλήρωση"); 
    add(arxikopoihsh); 
    add(klhrwsh); 
    } 

    // let the component size itself 
    public Dimension getPreferredSize() { 
    return new Dimension(CJP_WIDTH, CJP_HEIGHT); 
    } 
} 
+0

所以很好的捕獲+1 – mKorbel

+0

感謝您的幫助!我明白我的錯誤;) – VGe0rge

+0

不客氣,歡迎它幫助! –