I am trying to draw a car as a polygon in swing and move it left and right when clicking button
The problem is that I can't display the buttons on the screen when running the program and can't make them works
And I Don't know how implement the buttons inside of the user interface when using polygon
Here is my code:-
package java2d;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Java2D extends JFrame{
int xValues[];
int yValues[];
private JButton Right, Left;
public Java2D() {
super( "Drawing lines, rectangles and ovals" );
setSize( 500, 300 );
setVisible( true );
}
public void paint( Graphics g ) {
int xValues[] = { 40, 100, 130, 230, 260, 320, 320, 40 };
int yValues[] = { 120, 120, 40, 40, 120, 120, 170, 170 };
Polygon polygon1 = new Polygon( xValues, yValues, 8 );
g.setColor(Color.blue);
g.drawPolygon( polygon1 );
Right = new JButton("Right");
Left = new JButton("Left");
Right.setSize(50, 50);
Left.setSize(50, 50);
Right.setLocation(100, 200);
Left.setLocation(200, 200);
g.add(Right);
g.add(Left);
}
public void actionPerformed(ActionEvent event) {
if(event.getActionCommand().equals("Right")){
for (int i=0; i<xValues.length;i++) {
xValues[i] = xValues[i] + 10;
yValues[i] = yValues[i] + 10;
}
}
if(event.getActionCommand().equals("Left")){
for (int i=0; i<xValues.length;i++) {
xValues[i] = xValues[i] + 10;
yValues[i] = yValues[i] + 10;
}
}
repaint();
}
public static void main(String[] args) {
Java2D application = new Java2D();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
THANKS