GUI基础编程 Day 04
画笔
import java. awt. *;
import java. awt. event. WindowAdapter;
import java. awt. event. WindowEvent;
import java. security. PublicKey;
public class TextPaint {
public static void main ( String[ ] args) {
new MyPaint ( ) . loadFrame ( ) ;
}
}
class MyPaint extends Frame {
public void loadFrame ( ) {
setBounds ( 200 , 200 , 600 , 400 ) ;
setVisible ( true ) ;
}
@Override
public void paint ( Graphics g) {
g. setColor ( Color. red) ;
g. drawOval ( 100 , 100 , 100 , 100 ) ;
g. fillOval ( 200 , 200 , 100 , 100 ) ;
g. setColor ( Color. YELLOW) ;
g. fillRect ( 100 , 200 , 50 , 50 ) ;
}
}
鼠标监听事件
import java. awt. *;
import java. awt. event. MouseAdapter;
import java. awt. event. MouseEvent;
import java. util. ArrayList;
import java. util. Iterator;
public class TextMouseListener {
public static void main ( String[ ] args) {
new MyFrame ( "画图" ) ;
}
}
class MyFrame extends Frame {
ArrayList paints;
public MyFrame ( String title) {
super ( title) ;
setBounds ( 200 , 200 , 600 , 500 ) ;
paints = new ArrayList < > ( ) ;
setVisible ( true ) ;
this . addMouseListener ( new MyMouseListener ( ) ) ;
}
@Override
public void paint ( Graphics g) {
Iterator iterator = paints. iterator ( ) ;
while ( iterator. hasNext ( ) ) {
Point point = ( Point) iterator. next ( ) ;
g. setColor ( Color. black) ;
g. fillOval ( point. x, point. y, 20 , 20 ) ;
}
}
public void addPaint ( Point point) {
paints. add ( point) ;
}
private class MyMouseListener extends MouseAdapter {
@Override
public void mousePressed ( MouseEvent e) {
MyFrame myFrame = ( MyFrame) e. getSource ( ) ;
myFrame. addPaint ( new Point ( e. getX ( ) , e. getY ( ) ) ) ;
myFrame. repaint ( ) ;
}
}
}
窗口监听
import java. awt. *;
import java. awt. event. WindowAdapter;
import java. awt. event. WindowEvent;
public class TextWindow {
public static void main ( String[ ] args) {
new WindowFrame ( ) ;
}
}
class WindowFrame extends Frame {
public WindowFrame ( ) {
setBackground ( Color. blue) ;
setBounds ( 100 , 100 , 500 , 500 ) ;
setVisible ( true ) ;
this . addWindowListener (
new WindowAdapter ( ) {
@Override
public void windowClosing ( WindowEvent e) {
System. out. println ( "你点击了关闭" ) ;
System. exit ( 0 ) ;
}
@Override
public void windowActivated ( WindowEvent e) {
WindowFrame source = ( WindowFrame) e. getSource ( ) ;
source. setTitle ( "欢迎回来!" ) ;
System. out. println ( "你激活了窗口!" ) ;
}
}
) ;
}
}
键盘监听
import java. awt. *;
import java. awt. event. KeyAdapter;
import java. awt. event. KeyEvent;
public class TextKeyListener {
public static void main ( String[ ] args) {
new KeyFrame ( ) ;
}
}
class KeyFrame extends Frame {
public KeyFrame ( ) {
setBounds ( 100 , 100 , 500 , 500 ) ;
setVisible ( true ) ;
this . addKeyListener ( new KeyAdapter ( ) {
@Override
public void keyPressed ( KeyEvent e) {
int keyCode = e. getKeyCode ( ) ;
System. out. println ( keyCode) ;
if ( keyCode== KeyEvent. VK_UP) {
System. out. println ( "你按下了向上键" ) ;
}
}
} ) ;
}
}