Swing——画棋盘

import java.awt.Color;


import javax.swing.JPanel;


//1,创建类MyPanel继承JPanel
//5,给MyPanel注册第4步中的监听器
public class MyPanel extends JPanel{
public MyPanelListener l;
public MyPanel() {
setSize(200, 200);
setBackground(Color.BLUE);
MyPanelListener l=new MyPanelListener();
addMouseListener(l);
addMouseMotionListener(l);
// l.setGraphics(getGraphics());
}


public static void main(String[] args) {
new MyPanel();
}

}



import javax.swing.JFrame;


//2,写一个窗体的基础类MainFrame(通用代码写在构造方法中)
public class MainFrame extends JFrame{
public MainFrame() {
setSize(300, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);

setVisible(true);
}
public static void main(String[] args) {
new MainFrame();
}
}



import java.awt.Graphics;


//3,写一个MyFrame继承MainFrame,在构造方法中改写窗体大小,创建MyPannel对象,添加到窗体
//6,在面板上画棋盘
public class MyFrame extends MainFrame {
public MyFrame(){
setTitle("棋盘");
setSize(600,600);
MyPanel mp = new MyPanel();
new MyPanelListener().setGraphics(getGraphics());
add(mp);
}
// public void paint(Graphics g) {
// for (int i = 0; i <=300; i+=20) {
// g.drawLine(i, 20, i, 300);
// }
// for (int i = 0; i <=300; i+=20) {
// g.drawLine(0, i, 300, i);
// }
// }
public static void main(String[] args) {
new MyFrame();
}
}



import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;


//4,写一个监听器类MyPanelListener实现MouseListener和MouseMotionListener接口
public class MyPanelListener implements MouseListener,MouseMotionListener {
private Graphics g;
private int x,y;


public void mouseClicked(MouseEvent e) {

}
public void mouseEntered(MouseEvent e) {

}
public void mouseExited(MouseEvent e) {

}
public void mousePressed(MouseEvent e) {
x=e.getX();
y=e.getY();
System.out.println("鼠标点击");
}
public void mouseReleased(MouseEvent e) {
int x2=e.getX();
int y2=e.getY();
g.drawLine(x, y, x2, y2);
// g.drawRoundRect(x2, y2, 10, 10, 10, 10);
System.out.println("鼠标释放");
}
public void mouseDragged(MouseEvent e) {

}
public void mouseMoved(MouseEvent e) {

}
public void setGraphics(Graphics g) {
MyPanelListener.g=g;
}


}


你可能感兴趣的:(Swing——画棋盘)