接口是完全抽象的類型契約,只定義方法簽名(名稱、返回值、參數),無方法體,不能實例化。一個類可實現多個接口,實現「多重繼承」效果,彌補 Java 單繼承限制。
public interface NetJava {
String COMNAME = "cq"; // 隱含 public static final
void draw(int x1, int y1, int x2, int y2);
}
public interface Other {
String doOther();
}
public class Impoval implements NetJava, Other {
public void draw(int x1, int y1, int x2, int y2) {
System.out.println("我畫的是圓形");
System.out.println("出品人" + NetJava.COMNAME);
}
public String doOther() {
return "實現了Other類中的方法";
}
}
public class Test {
public static void main(String[] args) {
Impoval im = new Impoval();
im.draw(0, 0, 0, 0);
im.doOther();
// 接口類型引用指向實現對象
Other cs = new Impoval();
cs.doOther();
}
}
事件處理核心:事件源、事件對象、監聽器。監聽器實現特定接口(如 ActionListener),註冊到事件源,事件觸發時回調監聽器方法。
// 界面構建類
public class Frame {
public static void main(String[] args) {
new Frame().showFrame();
}
public void showFrame() {
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
// 組件
JLabel userLabel = new JLabel("賬號");
JLabel passLabel = new JLabel("密碼");
JTextField userField = new JTextField(21);
JPasswordField passField = new JPasswordField(21);
JButton loginBtn = new JButton("登錄");
JButton cancelBtn = new JButton("取消");
JCheckBox remember = new JCheckBox("記住賬號");
// 添加組件
frame.add(userLabel); frame.add(userField);
frame.add(passLabel); frame.add(passField);
frame.add(loginBtn); frame.add(cancelBtn); frame.add(remember);
// 窗口屬性
frame.setTitle("登錄界面 2.0");
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// 設置動作命令,區分按鈕
loginBtn.setActionCommand("login");
cancelBtn.setActionCommand("cancel");
// 註冊監聽器
Listener lis = new Listener();
loginBtn.addActionListener(lis);
cancelBtn.addActionListener(lis);
}
}
// 監聽器實現
public class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if ("login".equals(cmd)) {
System.out.println("登陸成功");
} else if ("cancel".equals(cmd)) {
System.out.println("取消");
}
}
}
setActionCommand 為按鈕賦予業務標識e.getActionCommand() 獲取標識,實現多按鈕共用一個監聽器