這是文件1(我的導師更喜歡是我們使用單獨的文件爲每個分機)如何將圓圈移動到「WEST」邊框佈局框架?
import javax.swing.*;
import java.awt.*;
public class Lab2 extends JFrame {
Lab2(){
setTitle("Lab 1b - Application #2");
Lab2Panel p = new Lab2Panel();
add(p);
}
public static void main(String[] args){
Lab2 frame = new Lab2();
frame.setTitle("Lab2 Application # 1");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 400);
frame.setVisible(true);
}
}
文件2:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Lab2Panel extends JPanel{
Lab2Button canvas = new Lab2Button();
JPanel panel = new JPanel();
Lab2Panel() {
setLayout(new BorderLayout());
JButton leftButton = new JButton("left");
JButton rightButton = new JButton("right");
JButton upButton = new JButton("up");
JButton downButton = new JButton("down");
panel.add(leftButton);
panel.add(rightButton);
panel.add(upButton);
panel.add(downButton);
this.add(canvas, BorderLayout.CENTER);
this.add(panel, BorderLayout.SOUTH);
leftButton.addActionListener(new Lab2MoveBallListener());
}
}
文件3:
import javax.swing.*;
import java.awt.*;
public class Lab2Button extends JPanel {
int radius = 5;
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawOval(getWidth()/2 - radius, getHeight()/2 - radius, 2 * radius, 2 * radius);
}
public void moveLeft(){
this.add(this, BorderLayout.WEST);
this.repaint();
}
}
動作監聽代碼:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Lab2MoveBallListener implements ActionListener{
public void actionPerformed(ActionEvent e){
this.moveLeft();
}
}
當用戶單擊「左」按鈕時,我正嘗試將圓圈移至WEST邊框佈局。有人能幫助我嗎。
不擴展每個類並只擴展actionlistener的原因是什麼? – Robert 2012-01-31 02:23:00
比繼承更喜歡構圖。 *必須*實現'ActionListener',其他可以用其他方式完成。 – 2012-01-31 02:24:53
我不認爲我會跟着你。到目前爲止,在課堂上我們只創建了這樣的類。當我們需要一個按鈕時,我們編寫一個擴展JButton的類並調用該類的一個實例。 – Robert 2012-01-31 02:28:18