編寫一個程序,其中顯示兩個標有「綠色」和「橙色」的按鈕。如何在我的程序底部獲得這兩個按鈕
如果用戶點擊綠色按鈕,窗口的背景變成綠色。如果用戶單擊橙色按鈕,窗口的背景將變爲橙色。爲此GUI創建一個JFrame
。 GUI採用默認佈局管理器。 A需要JPanel
。
在面板內放置兩個按鈕,並將面板添加到邊界佈局的南部區域。
注意標題欄中的文字。綠色按鈕應該有白色文本和綠色背景。橙色按鈕應具有橙色背景的黑色文本。
以下是我到目前爲止,它似乎沒有工作。
public class LabAssign91 extends JFrame implements ActionListener{
private JPanel loc1Panel;
private JButton greenButton, orangeButton;
public LabAssign91()
{
super("Colored Buttons");
setLayout(new GridLayout(2, 2));
setSize(300,250);
setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(loc1Panel);
loc1Panel = new JPanel();
add(loc1Panel, BorderLayout.SOUTH);
greenButton = new JButton("Green");
greenButton.addActionListener(this);
loc1Panel.add(greenButton, BorderLayout.WEST);
greenButton.setBackground(Color.green);;
orangeButton = new JButton("Orange");
orangeButton.addActionListener(this);
loc1Panel.add(orangeButton, BorderLayout.EAST);
orangeButton.setBackground(Color.orange);
}
public static void main(String[] args) {
LabAssign91 app = new LabAssign91();
}
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
* 「它似乎沒有工作。」 *什麼你以爲看到了什麼?反而發生了什麼? – 2013-04-29 03:53:49
歡迎來到SO。這不符合發佈問題的指導原則,如[FAQ]和[Ask]中所述。只是發佈代碼框架並要求某人爲你完成它並不是正確的方法。嘗試自己編寫必要的代碼,然後在出現問題時詢問具體問題。 – 2013-04-29 03:55:23
您將「BorderLayout」的「默認」佈局更改爲「setLayout(new GridLayout(2,2));',我很確定您的任務不會這麼做;)。另外,在添加它之前,你並沒有創建'loc1Panel' ...第一次,其本身是奇怪的(增加兩次) – MadProgrammer 2013-04-29 03:55:24