2016-12-16 48 views
1

是相當新的二OO我創建了一個類,這是我的大多數程序界面的,我已經把它都聚集在一類。然後我想將我的面板類添加到我的主類,以便我的面板連接到我的框架:我如何在面板類添加到我的框架主類

這是我試過的,我沒有收到任何錯誤,當我運行我的程序但面板不顯示:

面板類:

public class PanelDriver extends JPanel { 
     public JPanel p1, myg; 
     public PanelDriver() { 

     JPanel p1 = new JPanel(); 
     p1.setBackground(Color.CYAN); 

     // Graphicsa myg = new Graphicsa(); 


    JTextArea txt = new JTextArea(5,20); 
    txt.setText("test"); 
    p1.add(txt); 

    } 
} 

主類:

public class GraphicMain { 

    public static void main(String[] args) { 
    JFrame frame = new JFrame("My Program"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(600, 600); 

    PanelDriver panels = new PanelDriver(); 
    frame.getContentPane().add(panels); 

    GridLayout layout = new GridLayout(1,2); 
} 
+0

代碼甚至沒有編譯! – Azodious

+0

@現在應該做的很好,抱歉! – j1234567

+0

@Azodious沒有'Graphicsa MYG =新Graphicsa();'它,但沒有什麼實際happnes的xD – XtremeBaumer

回答

0

你需要一個超級調用(因爲你擴展JPanel你並不需要創建一個新的),並在你的佈局面板類是這樣的:

public class CustomerTest extends JPanel { 

    public CustomerTest() { 
     super(); 
     this.setBackground(Color.CYAN); 
     this.setLayout(new BorderLayout()); 
     JTextArea txt = new JTextArea(); 
     txt.setText("test"); 
     this.add(txt); 
     this.setVisible(true); 

    } 
} 

,然後在主類中使用此,設置該框架可見並顯示內容。你有你創建後設置佈局框架:

JFrame frame = new JFrame("My Program"); 
    GridLayout layout = new GridLayout(1, 2); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(600, 600); 

    CustomerTest panels = new CustomerTest(); 
    frame.getContentPane().setLayout(layout);; 
    frame.add(panels); 
    frame.setVisible(true); 
0

PanelDriver類創建一個p1JPanel,但不會將其添加到任何東西。

至少將它添加到PanelDriver本身:

this.add(p1); 

請注意你的代碼,框架甚至沒有顯示,查看由@XtremeBaumer的答案來解決的那部分。

+0

但程序不會顯示任何東西 – XtremeBaumer

相關問題