2013-10-08 31 views
1

我目前正在學習Uni的軟件工程,並且我正在努力解決如何正確添加JPanel到JFrame的問題。我的JPanel有幾個按鈕以及一個JLabel,它通過點擊其中一個按鈕並使用ActionListener進行更改。如何正確地將JPanel放置到JFrame上?

我知道有幾種方法可以做到這一點,這就是我一直在嘗試的,但我不能爲我的生活弄明白!

我知道我在加載錯誤,但它是什麼?

這裏是我的代碼:

UIPanelOne:

import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.*; 
import javax.swing.event.*; 


public class UIPanelOne extends JPanel implements ActionListener { 

private JButton yes, no, cancel; 
private JPanel panel; 
private JLabel l1, l2; 

UIPanelOne() { 

    super(); 
    setVisible(true); 

    //label dec 
    panel = new JPanel(); 

    //buttons 
    yes = new JButton("Yes"); 
    no = new JButton("No"); 
    cancel = new JButton("Cancel"); 

    //label dec 
    l1 = new JLabel("Hello"); 

    //button dec 
    panel.setLayout(new BorderLayout()); 
    panel.add(yes); 
    panel.add(no); 
    panel.add(cancel); 
    panel.add(l1); 

} 

public void actionPerformed(ActionEvent e) { 

    if (e.getSource() == yes) { 

     l1.setText("OK then!"); 
    }else if (e.getSource() == no){ 

     l1.setText("Goodbye then!"); 


    }else if(e.getSource() == cancel){ 

     System.exit(0); 
    } 


} 

public JComponent getGUI(){ 

    return panel; 
} 
} 

UIFrame:

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


public class UIFrame extends JFrame{ 


//constructor 
public UIFrame(){ 

    //layout 
    super("Can I help you?"); 
    setSize(400,600); 
    setLayout(new BorderLayout()); 
    setVisible(true); 
    setLocationRelativeTo(null); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    UIPanelOne hello = new UIPanelOne(); 

    getContentPane().add(hello.getGUI()); 
    } 
} 

UITest:

public class UITest { 

public static void main(String[] args){ 

UIFrame frame = new UIFrame(); 
frame.pack(); 

} 

} 

我知道這很可能是錯誤的,我是一個業餘愛好者,但我希望能在一些幫助下變得更好!

回答

3

由於您UIPanelOne擴展JPanel類,你可以添加組件的該面板(不需要建立新的面板)上,創建一個新的實例,並將該實例添加的JFrame方法:

add(new UIPanelOne()); 

UIPanelOne hello = new UIPanelOne(); 
add(hello,BorderLayout.CENTER); 

setContentPane(hello); 

避免用swing組件擴展你的類,除非你想爲它們定義新的方法(創建自定義組件),或者如果你不想重寫它們的某些方法。

您不必爲JFrame設置BorderLayout,因爲它的默認佈局爲JFrame(準備設置)。

致電setVisible方法JFrame AFTER添加組件後。

另外,閱讀約Concurrency in Swing

+0

setContentPane(hello);並添加(hello,BorderLayout.CENTER);和添加(你好)是相同的,從Java6和更新版本。 – mKorbel

+0

謝謝你的幫助! – blueprintChris