2016-01-22 50 views
1

沒有什麼是出現在Java相當新,我已經創建了一個主頁和幾個按鈕,當我點擊其中一個按鈕時,它將主頁面板可見性設置爲false,打開一個新類並設置該類的Jpanel可見。當我切換JPanels

homePanel.setVisible(false); 
Goodsin Barcode = new Goodsin(); 
Goodsin.setVisible(true); 

但是,一旦它打開新的類「Goodsin」它不會顯示任何按鈕或TextFileds。我知道它是打開新的類作爲System.out.println打印到控制檯,但沒有顯示在JFrame中,我不知道爲什麼。

這是我的新類

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 


public class Goodsin { 

    public JPanel Goodsin; 
    public JTextField item1; 
    public String code; 
    public JButton btn1; 

    public Goodsin() { 

     System.out.println("TEST"); 

     Goodsin = new JPanel(); 
     item1 = new JTextField(10); 
     btn1 = new JButton("Look up Barcode"); 

     Goodsin.setVisible(true); 

     Goodsin.add(item1); 
     item1.setSize(80, 30); 

     Goodsin.add(btn1); 
     btn1.setSize(80, 30); 

    } 

    public void getString(String code) { 
     System.out.println(code); 

    } 

} 

我敢肯定,我沒有做與Jpanel正確的東西或添加的文本框或按鈕,但我已經看到了所有的答案至今havnt工作的代碼。

+0

如何創建一個名爲Goodsin的屬性? – Leo

+0

如果Goodsin尚未添加,則設置其可見性將無意義。 – Neil

回答

1

我建議你將你的面板添加到JFrame。您可以通過從類中擴展JFrame來完成此操作,或者只是在構造函數中實例化一個JFrame。然後,您可以根據需要簡單地添加和刪除(或設置可見/不可見)。儘管如此,請務必在更改可見性後驗證JFrame/JPanel。

+0

我們在Main中有一個JFrame,當您點擊進入Goodsin Class時它仍然可見,但它似乎並未將面板表單Goodsin Class添加到JFrame中。它只是返回一個空白的JFrame – user5654841

+0

你試過做nameOfJFrame.revalidate()和nameOfJPanel.revalidate()嗎? – James

+0

好吧,我添加了一個新的JFrame到我的Goodins類,當我點擊按鈕去貨物中打開一個新的JFrame並顯示我需要什麼,但是如何讓它顯示在我已經有的JFrame中,所以新窗口不打開? – user5654841

1

嘗試做這樣的事情:

Goodsin = new JPanel(); 
     item1 = new JTextField(10); 
     btn1 = new JButton("Look up Barcode"); 

     item1.setSize(80, 30); 
     Goodsin.add(item1); 

     btn1.setSize(80, 30); 
     Goodsin.add(btn1); 

    JFrame frame = new JFrame("JFrame Example"); 
     Goodsin.setLayout(new FlowLayout()); 
     frame.add(Goodsin); 
0

我建議你試試下面的代碼:

public class Goodsin extends JFrame{ 

    public static void main(String[] args) { 
     Goodsin ui = new Goodsin(); 
     JTextField item1 = new JTextField(10); 
     JButton btn1 = new JButton("Look up Barcode"); 
     JPanel centralPanel = new JPanel(new FlowLayout()); 
     centralPanel.add(item1); 
     centralPanel.add(btn1); 
     item1.setSize(80, 30); 
     btn1.setSize(80, 30); 
     ui.add(centralPanel); 

     ui.pack(); 
     ui.setVisible(true); 

    } 
} 

一切都在我的例子中的主要方法做了,但是你仍然可以改善這種代碼並以更好的方式重構它。

0

只需要設置Goodsin面板的邊界或設置尺寸並添加主頁框架