接口與多態(tài)
接口
- 一種特殊的類驻子,是一種抽象類的延伸。
- 接口之間允許繼承而且允許多重繼承---一個接口可以繼承多個接口估灿。
- 接口只寫方法就可以了崇呵。
- 接口中定義的方法必須被定義為public或abstract形式,其他修飾權限不被Java編譯器認可馅袁。
- 接口是可以多實現的:因為接口中的方法都是抽象的域慷,都沒有實現,在創(chuàng)建子類對象并調用該重寫的抽象方法時汗销,很明顯就是調用重寫之后的方法犹褒,不會出現調用的不確定性。
- 注意:類與類之間是繼承關系 弛针,通過繼承可以得到繼承體系的基本功能叠骑。接口與接口之間是實現關系核行,通過實現接口可以得到繼承體系之外的功能的止。
實例
- 一個簡單的音樂家的接口,寫和音樂家相關的方法(彈鋼琴和拉小小提琴)旁理。
public interface Musician {
void playPiano();
void palyViolin();
}
窗口的實現
1付材、創(chuàng)建一個類去繼承JFrame這個父類朦拖。
2、在該類的構造函數中對窗口的一些基本屬性進行初始化操作厌衔。
public MyFrame() { // 構造函數 窗口的初始化璧帝。
this.setSize(300, 200); // 窗口大小的設置
this.setResizable(false); // 定義窗口大小是否被改變。
this.setLocationRelativeTo(null); // 窗口的放置位置富寿。
this.setDefaultCloseOperation(EXIT_ON_CLOSE); // 關閉即退出睬隶。
this.setLayout(null); // 不要布局管理器
}3锣夹、在窗口上添加文本組件
JTextField jTextField = new JTextField("你好瓜",90);
jTextField.setFont(new Font("楷體",Font.CENTER_BASELINE ,20));
jTextField.setBounds(50, 50, 200, 80);
this.add(jTextField);4、在窗口上添加標簽組件
JLabel jLabel = new JLabel("傻不傻");
jLabel.setFont(new Font("楷體", Font.BOLD, 18));
jLabel.setBounds(225,100, 200, 600);
JCheckBox jCheckBox = new JCheckBox("1");
jCheckBox.setBounds(225,100, 200, 50);
this.add(jCheckBox);-
5苏潜、在窗口上添加按鈕組件并創(chuàng)建按鈕的事件監(jiān)聽器
JButton jButton = new JButton("按下有驚喜");
jButton.setFont(new Font("楷體", Font.BOLD, 16));
jButton.setForeground(Color.BLUE);
jButton.setBackground(Color.RED);
jButton.setBounds(225, 300, 200, 50);
this.add(jButton);
jButton.addActionListener(e -> {
JOptionPane.showMessageDialog(null, "你好傻R肌!"); // 消息提示面板});
6恤左、窗口上Timer的創(chuàng)建與應用
Timer timer = new Timer(10, e->{
for (int i = 0; i < total; i++) {
SmallBall smallball = ballarray[i];
smallball.move();
repaint(); //回調paint()方法贴唇,即改變x,y值后再重新渲染一次飞袋。} }); timer.start();7戳气、雙緩存讓窗口上的動畫更加的流暢
private BufferedImage image = new BufferedImage(700, 700, 1);
public void paint(Graphics g) {
// TODO Auto-generated method stub
Graphics otherg = image.getGraphics();
super.paint(otherg);
// otherg.setColor(Color.BLUE);
// otherg.fillOval(x<700?x:700-(x-700), y<700?y:700-(y-700), 40, 40);
for (int i = 0; i < total; i++) {
SmallBall smallball = ballarray[i];
smallball.draw(otherg);
}
g.drawImage(image, 0, 0, null);
}-
8、隨機獲得顏色
public Color randomColor() {
int red = (int) (Math.random() * 256);
int green = (int) (Math.random() * 256);
int blue = (int) (Math.random() * 256);
return new Color(red, green, blue);
}