2014-01-15 16 views
1

我一直在從YouTube視頻中學習Java Swing GUI,因爲直到下個學期在大學結束時我才瞭解它們,我覺得這太有趣了。然而,儘管視頻製作人員很容易跟蹤,並且我學到了很多東西,但我可以說他自己也許可以自己學習,因爲他的一些編碼習慣與我們在學校學到的習慣有些不同。 (例如,他不在乎封裝或駱駝案件。)這讓我擔心,我所學的一切都是無用的。如果不擴展JFrame,將會產生什麼?

他在他的視頻中所做的所有項目都在一個類中,使用實現ActionListener,MouseListener等的內部類。所以我不知道如何將我從這些視頻中學到的東西與無GUI的多個類我在學校工作的項目。

我給的是如何在項目是一般的例子:(我只加了私人,因爲這是我已經習慣了)

public class Something extends JFrame { 
    private JPanel topPanel; 
    private JPanel bottomPanel; 
    private JLabel label; 
    private JButton button; 

    public Something() { 

    Container pane = this.getContentPane(); //need help with this 

    topPanel = new JPanel(); 
    topPanel.setLayout(new GridLayout(1,1)); 

    label = new JLabel("x"); 
    topPanel.add(label); 
    pane.add(topPanel); 

    bottomPanel = new JPanel(); 
    bottomPanel.setLayout(new GridLayout(1,1)); 

    button = new JButton("Button"); 
    bottomPanel.add(button); 
    pane.add(bottomPanel); 

    Event e = new Event(); 
    button.addActionListener(e); 

    } 

    public class Event implements ActionListener { 

    } 

另外,我爲什麼延長讀取另一個線程在這裏JFrame是一個壞主意。如果我必須適應,我會創建一個JFrame框架,然後添加(框架)?然後確保我將下一層添加到框架中?我需要做什麼安排?

+0

在學習GUI之前,或在學習GUI時,還要學習接口,設計模式和依賴注入的概念。 –

+2

如果您在swing上尋找更多幫助,您應該查看Oracle的[教程](http://docs.oracle.com/javase/tutorial/uiswing/)。 – endorphins

回答

1

通常,您不應該擴展JFrame。相反,擴展JPanel。例如您的代碼可能是這樣的:

public class Something extends JPanel { 
    // very similar code to yours goes here 
    // though I'd set a specific LayoutManager 
} 

現在你有更多的靈活性:您可以將您的精彩GUI成一個JFrame,JDialog的,或者進入另一個更復雜的JPanel。例如

JDialog dialog = new JDialog(); 
JPanel reallyComplexPanel = new JPanel(new BorderLayout()); 
// add in stuff here, e.g buttons at the bottom 
Something mySomething = new Something(); 
reallyComplexPanel .add(mySomething, BorderLayout.NORTH); // my stuff at the top 
dialog.setContentPane(reallyComplexPanel); 
+0

什麼是contentPane?我用它,但我不是100%定義它是什麼。它是否在JFrame之下但在面板之上? – Abdul

相關問題