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;
}


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值