圖形用戶接口也就是一個人機交互的界面,下面先介紹一下界面的組成:
1. JFrame框架,這個是屏幕上的Windows的對象,在創建界面時,這個是首要創建的,如果把設計一個界面比喻爲畫水彩畫,那麼它就相當於一個支架,在畫畫前先安好支架如右圖
2. JPanel面板,組件是不能直接加載JFrame上的,必須先得到面板,然後在添加其他組件,面板就和上圖的畫板一個道理
3. widget組件,就相當於在畫板上畫的圖形,JButton、JCHeckBox等
JFrame frame;
JButton button;
frame = new JFrame();
button = new JButton("click me!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Windows關閉時該程序自動關閉
frame.getContentPane().add(button);
frame.setSize(300, 300);
frame.setVisible(true);
上面是一個設計了一個單純的界面,那麼下面將介紹如何設計一個有功能的界面 ,這裏以按鈕組件爲例,在按下按鈕之前顯示"click me",在按下按鈕之後顯示"I have been clicked",那麼這裏就有一個問題就是程序如何知道按鈕被按下,如何知道要改變按鈕上的文字:
1. 事件來源:JButton ,JCheckBox等組件接收註冊,並在取得用戶的操作,並調用相應的接口方法
2. 事件對象:MouseEvent, KeyEvent等,在調用接口的方法時,此會作爲參數被調用
3.監聽接口:MouseListener,KeyListener等接口,這裏,我們一般扮演監聽接口的任務,也就是向按鈕等組件註冊並實現接口的方法
當我們對事件來源做出相關的動作時會產生事件對象。
public class SimpleGuil implements ActionListener{
JFrame frame;
JButton button;
public static void main(String[] args) {
// TODO Auto-generated method stub
SimpleGuil gui = new SimpleGuil();
gui.go();
}
public void go(){
frame = new JFrame();
button = new JButton("click me!");
button.addActionListener(this);//註冊,並得到事件對象
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(button);
frame.setSize(300, 300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event){//<span style="font-size:24px;color:#ff0000;">這裏就是接口的實現方法,當用戶做出相應的操作時,編輯器就會自動調用這個函數,而不用我們手動調用</span>
button.setText("I have been clicked!");
}
}
這裏我再寫一下關於面板的問題,面板類JPanel的方法是PaintComponent()函數,一般情況下,我們是不會自己調用該函數,而是面板所處的Frame顯示時,該函數就會被調用
public class SimpleAnimation {
int x = 70;
int y = 70;
public static void main(String[] args) {
// TODO Auto-generated method stub
SimpleAnimation gui = new SimpleAnimation();
gui.go();
}
public void go(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyDrawPanel1 drawPanel = new MyDrawPanel1();
frame.getContentPane().add(drawPanel);
frame.setSize(300, 300);
frame.setVisible(true);
for(int i = 0;i<130;i++)
{
x++;
y++;
drawPanel.repaint();
try{
Thread.sleep(50);
}catch(Exception ex){}
}
}
class MyDrawPanel1 extends JPanel {<span style="white-space:pre"> </span><span style="font-size:24px;color:#ff6666;">//這邊引入了一個內部類的概念</span>
public void paintComponent(Graphics g){
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.green);
g.fillOval(x, y, 40, 40);
}
}
}