2012-07-07 171 views
2

將具有圖形的JPanel添加到JFrame時,它工作正常。但是當我嘗試添加一個JPanel,其中我添加了另一個JPanel圖形,但它沒有顯示在JFrame中。請看下面的代碼在JPanel中未顯示添加到另一個JPanel的圖形

package sample; 

import java.awt.Graphics; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class Main extends JFrame{ 
    public static void main(String[] args) { 
     new Main(); 
    } 

    public Main(){ 
     setTitle("Sample"); 
     setVisible(true); 
     setSize(500,500); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     add(new SamplePanel2()); 
    } 
} 

class SamplePanel2 extends JPanel{ 
    public SamplePanel2(){ 
     add(new JButton("Hi")); 
     add(new SamplePanel()); 
    } 
} 
class SamplePanel extends JPanel { 
    public SamplePanel(){ 
    } 

    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     g.drawString("HHHHHHHHHHHH", 100, 100); 
    } 
} 
+1

簡單地覆蓋[的getPreferredSize()](http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#getPreferredSize()),並使其返回一定的價值就像'返回新的Dimension(300,300);',在你的'SamplePanel Class'裏面' – 2012-07-07 15:33:54

+0

請參閱'我如何將JPanel類添加到NetBeans的JFrame表單類中?'在更多信息的stackoverflow – MaVRoSCy 2012-07-07 15:35:50

+0

@MaVRoSCy:夥伴,你只是忘了把鏈接到評論,就像爲了在這裏發表評論,把方括號[]放在這裏像[這裏],然後像[這裏]括號一樣, ()並在括號內粘貼URL。 – 2012-07-08 05:44:32

回答

4

請不要觀​​看Main類的構造函數,使此習慣中遵循所示的序列這個例子。首先將組件添加到JFrame,然後只撥打電話pack(), setSize() or setVisible(...),而不是之前。

始終讓它成爲你的習慣,只要你重寫paintcomponent()方法,也可以重寫getPreferredSize()方法。

並且始終在EDT - Event Dispatch Thread中放置pack()/setVisible(...)等呼叫。請閱讀Concurrency in Swing,瞭解更多關於該主題的信息。

import java.awt.Dimension; 
import java.awt.Graphics; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class Main extends JFrame{ 
    public static void main(String[] args) { 
     new Main(); 
    } 

    public Main(){ 
     setTitle("Sample");   
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     setContentPane(new SamplePanel2()); 
     pack();   
     setVisible(true); 
    } 
} 

class SamplePanel2 extends JPanel{ 
    public SamplePanel2(){ 
     add(new JButton("Hi")); 
     add(new SamplePanel()); 
    } 
} 
class SamplePanel extends JPanel { 
    public SamplePanel(){ 
    } 

    @Override 
    public Dimension getPreferredSize() 
    { 
     return (new Dimension(300, 300)); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     g.drawString("HHHHHHHHHHHH", 100, 100); 
    } 
} 
+1

@ user1508907:請注意,'JPanel'的默認佈局是['FlowLayout'](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html#flow)。 – trashgod 2012-07-07 17:33:50

+0

謝謝大家的幫助。 – UDPLover 2012-07-08 18:22:46

+0

你是最歡迎和保持微笑:-) – 2012-07-08 18:31:24

相關問題