文字的定时移动和画板的建立.java

public class Test extends JFrame {
private static DrawPane movingPane = new DrawPane();//画板
Test() {
setTitle("java练习");
setSize(500, 500);
getContentPane().add(movingPane);//如果这句改成getContentPane().add(new DrawPane());那么将只有绘图功能
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

addWindowListener(new WindowAdapter() {// 窗口事件的处理;

public void windowClosing(WindowEvent e) {
System.exit(0);// JOptionPane.showConfirmDialog(null, "正在关闭窗口!");// TODO
// Auto-generated method stub
}
});
}

public static void main(String[] args) {
Test test = new Test();
Thread moving = new Thread(new myThread(10,movingPane));
moving.start();
test.setVisible(true);

}
}
class DrawPane extends JPanel {//定义画板类;

private Point start = new Point();
private Point end = new Point();
private boolean rightButton;
private boolean leftButton;
int x;//定义移动文字的横坐标;
public void setX(int x){
this.x=x;
}
DrawPane() {
// setTitle("画板");
setVisible(true);
addMouseListener(new MouseAdapter() {// 鼠标事件处理;
public void mousePressed(MouseEvent e) {
if (e.getButton()==MouseEvent.BUTTON1) {
start.x = e.getX();// TODO Auto-generated method stub
start.y = e.getY();
leftButton=true;//标记左键被按,用于MouseMotionListener;
}
else if(e.getButton()==MouseEvent.BUTTON3){
rightButton=true;
}
}
public void mouseReleased(MouseEvent e) {
if(e.getButton()==MouseEvent.BUTTON1)
leftButton=false;
else if(e.getButton()==MouseEvent.BUTTON3)
rightButton=false;
}
});
addMouseMotionListener(new MouseMotionAdapter() {

@Override
public void mouseDragged(MouseEvent e) {
Graphics g = getGraphics(); // 获取画笔;
if (leftButton) {
g.setColor(Color.RED);
g.drawLine(start.x, start.y, e.getX(), e.getY());
start.x = e.getX();// TODO Auto-generated method stub
start.y = e.getY();
}

else if(rightButton)
{
g.setColor(getBackground());
g.fillOval(e.getX()-5, e.getY()-5, 10, 10);
}//做一个椭圆作为橡皮察,抹掉已画的线条
g.dispose();
}

});
}

public void paintComponent(Graphics g) {//重写paint();
super.paintComponent(g);
g.setColor(Color.RED);
g.drawString("Hello!",x,50);
System.out.println(" FUCK ");
}
}
class myThread implements Runnable {
private int x;
private DrawPane moving;
myThread(int x,DrawPane movingPane){
this.x=x;
this.moving=movingPane;
}
public void run() {
while(true){
try {
Thread.sleep(1000);

if(x<=moving.getSize().width){
x+=10;
}
else{
x = 0;
}
moving.setX(x);
moving.repaint();

}catch(InterruptedException e){}
}
}

}//定义线程

你可能感兴趣的:(java)