Moving lines in java

Code to Animate an Image Body through a Straight Line in Java

The equation of a straight line has the general form y = mx + c ;
where m is the slope and c is the intercept on the y-axis.

For a vertical line, x is constant and for a horizontal line, y is constant.

Generating Straight Lines for Java

Given any 2 points (x1, y1) and (x2, y2); we’ll have:

Comparing this to the general equation of a straight line, i.e. y = mx + c

m = y2 — y1
x2 — x1
&
c = x2y1 — x1y2
x2 — x1

Say we are to find the equation for the line represented by the arbitrary points (50, 50) and (200, 100):

m = 100 — 50 = 50 = 1
200 — 50 150 3
&
c = 200(50) — 50(100) = 10000 — 5000
200 — 50 150
= 5000 = 100
150 3

Code to Animate a Graphic Object by a Line Equation in Java

To make a graphic (dot) travel by the equation of a line, continuously increment x, and use the equation to get the corresponding y value.
Let’s do so with the above equation representing points (x1, y1) = (50, 50) and (x2, y2) = (100, 200).

Create 2 new classes; File, New.
Call them PanelsStraightLine and StraightLine.
Type out the adjoining Java code for animating an image body through the path of a straight line.

Canvas/Button class

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class ButtonandCanvasPanels implements ActionListener public JPanel button_panel , canvas_panel ;
public JButton motion_bttn ;
public StraightLine motion ;

public ButtonandCanvasPanels() button_panel = new JPanel();
// pick a background colour
button_panel .setBackground(Color. PINK );
button_panel .setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
// O my; but for convenience sake let’s add our control button here
motion_bttn = new JButton( «Move» );
motion_bttn .setBackground(new Color(255, 0, 255));
motion_bttn .addActionListener( this );
// using the default layout manager
button_panel .add( motion_bttn );

canvas_panel = new JPanel();
canvas_panel .setLayout(new BorderLayout());
motion = new StraightLine();
// attach appropriate drawing component
canvas_panel .add( motion , BorderLayout.CENTER);
>

/**
* Respond to the button click event
*/
public void actionPerformed(ActionEvent evt) motion .moveInLine();
>
>

Java code for StraightLine class

public class StraightLine extends Canvas

protected Color ball_colour ;
protected int x1 = 50;
protected int x2 = 800;
protected int y1 = 50;
protected int y2 = 300;
protected int x = x1 ;
protected int y = y1 ;
protected double m , c ; // slope and y -intercept of a straight line
protected final int aWIDTH , aHEIGHT ;

Читайте также:  This getclass getresource java

public StraightLine() setBackground(Color. LIGHT_GRAY ); // canvas color
ball_colour = Color. RED ;
aWIDTH = aHEIGHT = 10;

m = ( double ) ( y2 — y1 ) / ( x2 — x1 ); // slope
c = ( double ) ( x2 * y1 — x1 * y2 ) / ( x2 — x1 ); // y -intercept

// Feel free to double buffer if flickering occurs
public void paint(Graphics g) g.setColor( ball_colour );
// draw a dot
g.fillOval( x , y , aWIDTH , aHEIGHT );
>

public void moveInLine() // condition for continuing motion
while ( x <= 700) y = ( int ) Math.ceil( m * x + c );
paint( this .getGraphics());

x += 10;
// introduce a delay between renderings
try Thread.sleep(50);
> catch (InterruptedException e) >
>
>
>

All demonstrations on this site are continually under review.
To report any typos, misconceptions, erroneous code/code caveats or general errors,
please use our forum platform; twitter or facebook outlet; or email us at contact@usingmaths.com; Thanks!

Источник

[Solved]-How to move an existing Line shape in java using a mouse?-Java

LearningJava 25

moving by binding start x y and end x y

In this aproach we are dragging circle shapes and the start and the end of line object will follow those shapes ’cause they are binded This is a functional single javafx app you can try . red circle is for start line position and blue is for end

public class App extends Application < @Override public void start(Stage stage) throws Exception < Line line = new Line(0, 0, 0, 200); Shape endHandler = new Circle(15, Color.BLUE); endHandler.setStroke(Color.BLACK); Shape startHandler = new Circle(15, Color.RED); startHandler.setStroke(Color.BLACK); endHandler.translateXProperty().bindBidirectional(line.endXProperty()); endHandler.translateYProperty().bindBidirectional(line.endYProperty()); startHandler.translateXProperty().bindBidirectional(line.startXProperty()); startHandler.translateYProperty().bindBidirectional(line.startYProperty()); endHandler.setOnMouseDragged(e ->< endHandler.setTranslateX(endHandler.getTranslateX() + e.getX()); endHandler.setTranslateY(endHandler.getTranslateY() + e.getY()); >); startHandler.setOnMouseDragged(e -> < startHandler.setTranslateX(startHandler.getTranslateX() + e.getX()); startHandler.setTranslateY(startHandler.getTranslateY() + e.getY()); >); Group group = new Group(line, endHandler, startHandler); group.setTranslateX(250); group.setTranslateY(250); Scene scene = new Scene(new AnchorPane(group), 500, 500); stage.setTitle("moving line"); stage.setScene(scene); stage.show(); > > 

moving line with mouse

moving a line using mouse event

 public class App extends Application < private double startX; private double startY; @Override public void start(Stage stage) throws Exception < Line line = new Line(0, 0, 0, 200); line.setStrokeWidth(8); Shape endHandler = new Circle(15, Color.BLUE); endHandler.setStroke(Color.BLACK); line.setOnMousePressed(e ->< startX = line.getLayoutX() - e.getX(); startY = line.getLayoutY() - e.getY(); >); line.setOnMouseDragged(e -> < line.setTranslateX(line.getTranslateX() + e.getX()+startX); line.setTranslateY(line.getTranslateY() + e.getY()+startY); >); Group group = new Group(line); group.setTranslateX(250); group.setTranslateY(250); Scene scene = new Scene(new AnchorPane(group), 500, 500); stage.setTitle("moving line"); stage.setScene(scene); stage.show(); > > 
  • How to add more documents in already existing elasticsearch index using java API?
  • How to move a mouse smoothly throughout the screen by using java?
  • How to write to an existing XML file using java
  • How to move a folder(including subdirectories and files) into a new folder using Java code
  • How to authenticate to https://tfspreview.com (MIcrosoft-hosted TFS) using Java command line application?
  • How to perform schematron validation using Saxon java library command line tool?
  • How to serve existing web page using a java servlet
  • How to run command line within java using thread async
  • How to match a document with existing array elements in mongodb using java driver
  • How to draw a rectangle on a java applet using mouse drag event and make it stay
  • How to add text at second last line in text file using java
  • How to move to the next value in a loop when using Java 8 Stream API
  • How to print starting line number using java
  • How to read, update and delete the existing XML file using node attribute value in Java
  • how to interact with system cmd line using java code
  • How to iterate the JavaRDD using foreach and find the particular element from each line using spark java
  • How to mouse hover using java through selenium-webdriver and Java
  • How to call existing JavaScript function from Java method using CodeName One?
  • How do I enable a user to see the shape while dragging the mouse in a line drawing program?
  • How to build a command line interface in java for an existing web based application
  • How to test a simple command line application in Java using JUnit
  • How to reformat Java from Allman to K&R with line comments using Eclipse?
  • How to generate JAXB classes using XJC using some existing Java classes?
  • how to properly move one or more packages into another package in java using code
  • How is Java 9 running code compiled with Java 8 that is using a non-exported package
  • How can I change the label on a Unit using the Java Measurement API?
  • How can a project support Java 7 despite using Java 8 features
  • How to send mail with java mail by using Gmail SMTP with OAuth2 authentication?
  • How to search for an Exchange appointment for an iCalUid using Java EWS API?
  • How to copy a generic Collection in Java using wildcards
Читайте также:  Пример работы java метода

More Query from same tag

  • How can I create/instantiate an object from an if-else statement?
  • Eclipse doesn’t build Android project targeted at 5.0 Lollipop
  • How do I implement a custom @JsonDeserialize method on an endpoint class?
  • Solr stopped with Error opening new searcher at org.apache.solr.core
  • JSF and f:ajax for hiding/showing div
  • How to deal with a big dataset with H2O
  • StompBrokerRelayMessageHandler — many log errors
  • How to set language to PhantomJs Ghostdriver with java?
  • Fast way to check if long integer is a cube (in Java)
  • SparkContext parallelize invocation example in java
  • JNA vs. DLL (Delphi)
  • JVM Attach API Virtual Machine. What does it mean to «Attach»?
  • How to ignore the key press event in Swing?
  • javax.xml.bind.Marshaller encoding unicode characters with their decimal values
  • Cannot see finished job in Spark web UI
  • How to fix jvm options exports javafx 11 to com.jfoenix on gradle idea?
  • Sorting 2D String Array with BUBBLESORT in java
  • java exception: Comparison method violates its general contract
  • What could be the reason for thread to be parked at java.util.concurrent.ThreadPoolExecutor.getTask
  • configure checkstyle to ignore an empty catch block
  • Java how to remove duplicates from ArrayList
  • How to correctly format a date cell and populate content using Apache POI 3.7
  • jsonrpc4j: How to add type info to parameters?
  • Collection of Interfaces to pick from, Java
  • How to create cube using single mesh in libgdx
  • Do something when mocked object’s method is being called
  • Array becoming null when List.toArray is used
  • Is it possible to Serialize and Deserialize objects in C++?
  • jersey 2 context injection based upon HttpRequest without singleton
  • Spring dependencies not injected for Cucumber runner
Читайте также:  Html textarea style margin

Источник

Move Line in Java using Swing Components, JPanel, JFrame and Graphics

Move Line in java using swing components, JPanel,JFrame and Graphics. This is a Java small program that I created on jGRASP but it is possible to open it on Notepad++, notepad, jCreator and other softwares for java. Move Line either left or right by clicking on the respective button or direction key on keyboard. The display consists of two JPanels in a JFrame, arranged using BorderLayout. The top panel is used for custom painting; the bottom panel holds two JButtons arranged using FlowLayout. Buttons 1. Left Button 2. Right Button. All these buttons are working correct what you must do just download the file and debug it on your computer. It a simple program. If you have any problem contact me on my email address:[email protected] /[email protected] or Facebook: http://www.facebook.com/mzwenhlanhla.dlamini

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe’s, .ocx’s, .dll’s etc.)—only run source code.

Tags

Источник

Оцените статью