Java 是一種面向對象的編程語言,擁有廣泛的應用場景。其中,Java 的移動直線和圓代碼較為常見,下面為大家介紹一些相關代碼實現(xiàn),代碼使用pre
標簽。
1. 移動直線的代碼實現(xiàn):
import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class MoveLine extends JPanel implements ActionListener{ private Timer timer; private int x1; private int y1; private int x2; private int y2; private int deltaX = 1; private int deltaY = 1; public MoveLine(){ timer = new Timer(10, this); timer.start(); x1 = 0; y1 = 0; x2 = 100; y2 = 100; } public void paintComponent(Graphics g){ super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.drawLine(x1, y1, x2, y2); } public void actionPerformed(ActionEvent e){ if(x1+deltaX<0 || x1+deltaX>this.getWidth()-100) deltaX=-deltaX; if(y1+deltaY<0 || y1+deltaY>this.getHeight()-100) deltaY=-deltaY; x1+=deltaX; y1+=deltaY; x2+=deltaX; y2+=deltaY; repaint(); } public static void main(String[] args){ JFrame frame = new JFrame("移動直線"); frame.add(new MoveLine()); frame.setSize(500, 500); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
2. 移動圓的代碼實現(xiàn):
import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Ellipse2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class MoveCircle extends JPanel implements ActionListener{ private Timer timer; private int x; private int y; private int deltaX = 3; private int deltaY = 3; public MoveCircle(){ timer = new Timer(10, this); timer.start(); x = 0; y = 0; } public void paintComponent(Graphics g){ super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; Ellipse2D circle = new Ellipse2D.Double(x, y, 100, 100); g2d.draw(circle); } public void actionPerformed(ActionEvent e){ if(x+deltaX<0 || x+deltaX>this.getWidth()-100) deltaX=-deltaX; if(y+deltaY<0 || y+deltaY>this.getHeight()-100) deltaY=-deltaY; x+=deltaX; y+=deltaY; repaint(); } public static void main(String[] args){ JFrame frame = new JFrame("移動圓"); frame.add(new MoveCircle()); frame.setSize(500, 500); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
以上就是 Java 移動直線和圓的代碼實現(xiàn)。如有需要,可以參考以上代碼進行開發(fā),實現(xiàn)想要的功能。