在jpanel上画线的问题 java
比如一个jpanel,在上面添加一个鼠标进入的事件,鼠标进入的时候,就在这个jpanel画一条水平的直线,鼠标移动,这条水平线跟着鼠标运动。...
比如一个jpanel ,在上面添加一个鼠标进入的事件,鼠标进入的时候,就在这个jpanel画一条水平的直线,鼠标移动,这条水平线跟着鼠标运动。
展开
1个回答
2013-05-23
展开全部
写了一个 不过 写成jpanel 没办法运行 我就继承了 jframe
换成jpanel一样的
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
public class TestPanel extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
TestPanel tp =new TestPanel();
tp.setVisible(true);
}
public TestPanel() {
initComponents();
}
private void initComponents() {
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent event) {
mouseMotionMouseMoved(event);
}
});
setSize(320, 240);
}
//重写paint方法 鼠标移动就重画
@Override
public void paint(Graphics g) {
super.paint(g);//带上这句是为了还原
g.drawLine(0,y, this.getWidth(), y);//横线
g.drawLine(x,0, x, this.getHeight());//竖线
}
int x;
int y;
private void mouseMotionMouseMoved(MouseEvent event) {
//记录x,y坐标
x = event.getX();
y = event.getY();
paint(this.getGraphics());
}
}
换成jpanel一样的
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
public class TestPanel extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
TestPanel tp =new TestPanel();
tp.setVisible(true);
}
public TestPanel() {
initComponents();
}
private void initComponents() {
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent event) {
mouseMotionMouseMoved(event);
}
});
setSize(320, 240);
}
//重写paint方法 鼠标移动就重画
@Override
public void paint(Graphics g) {
super.paint(g);//带上这句是为了还原
g.drawLine(0,y, this.getWidth(), y);//横线
g.drawLine(x,0, x, this.getHeight());//竖线
}
int x;
int y;
private void mouseMotionMouseMoved(MouseEvent event) {
//记录x,y坐标
x = event.getX();
y = event.getY();
paint(this.getGraphics());
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询