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();
}
}
我知道這很可能是錯誤的,我是一個業餘愛好者,但我希望能在一些幫助下變得更好!
setContentPane(hello);並添加(hello,BorderLayout.CENTER);和添加(你好)是相同的,從Java6和更新版本。 – mKorbel
謝謝你的幫助! – blueprintChris