Window Display
package dymetric;
import java.awt.*;
import javax.swing.*;
public class Facet extends JFrame {
public Container face;
public ButtonandCanvasPanels components;
public ImageIcon logo;
public Facet() {
super("A window that will hold a Canvas and Button");
setSize(780,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
logo = new ImageIcon(getClass().getResource("studyingPays.png"));
this.setIconImage(logo.getImage());
face = this.getContentPane();
face.setBackground(Color.PINK);
components = new ButtonandCanvasPanels();
face.add(components.button_panel, BorderLayout.NORTH);
face.add(components.canvas_panel, BorderLayout.CENTER);
}
}
Canvas/Button class
package dymetric;
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 MovingBody traction;
public ButtonandCanvasPanels() {
button_panel = new JPanel();
button_panel.setBackground(Color.PINK);
button_panel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
motion_bttn = new JButton("Glide");
motion_bttn.setBackground(new Color(255, 0, 255));
motion_bttn.addActionListener(this);
button_panel.add(motion_bttn);
canvas_panel = new JPanel();
canvas_panel.setLayout(new BorderLayout());
traction = new MovingBody();
canvas_panel.add(traction, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent evt) {
traction.doGlide();
}
}
Java code for MovingBody class
package dymetric;
import java.awt.*;
public class MovingBody extends Canvas {
protected Color ball_colour;
protected int x = 10;
protected int y = 110;
protected final int aWIDTH, aHEIGHT;
public MovingBody() {
setBackground(Color.LIGHT_GRAY);
ball_colour = Color.RED;
aWIDTH = aHEIGHT = 80;
}
public void paint(Graphics g) {
g.clearRect(x - 10, y, aWIDTH, aHEIGHT);
g.setColor(ball_colour);
g.fillOval(x, y, aWIDTH, aHEIGHT);
}
public void doGlide() {
while (x <= 670) {
paint(this.getGraphics());
x += 10;
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
}
}