I am trying to write simple code in java for a moving ball program. im new to java, i mean I know the basics one so here it is my code, in case you can help me.I cant move the ball object. I created the class frame which have the gui component and also the ball class with the features of he ball
public class Frame extends JFrame{
private static final int width= 500;
private static final int height=500;
private static final Color cbw= Color.BLACK;
private Ball ball; // the moving object
private DrawCanvas canvas; // the custom drawing canvas
private JPanel btnpanel; // the panel of the buttons
private JPanel mainpanel; // the mainpanel
private JButton button_ML; // move_Left button
private JButton button_MR;// move_Right button
public Frame (){
setProperties();
init();
setUI();
}
private void setProperties() {
setSize(width, height);
setTitle("MOVE THE BALL");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
private void init(){
btnpanel = new JPanel(new FlowLayout());
mainpanel= new JPanel(new BorderLayout());
button_ML = new JButton("Move left");
button_MR = new JButton("Move right");
//creating the ball with its features
ball= new Ball (30,30,width/2-2,height/2-10,Color.red);
canvas = new DrawCanvas();
// it makes possible the ball to be seen though we have a main panel.
canvas.setPreferredSize(new Dimension(width,height));
button_ML.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
move_Left();
}
});
button_MR.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
move_Right();
}
});
}
private void setUI(){
mainpanel.add(btnpanel, BorderLayout.SOUTH);// adds the button panels to the main panel
btnpanel.add(button_ML);// adds the button to the panel of buttons
btnpanel.add(button_MR);
mainpanel.add(canvas, BorderLayout.CENTER); // adds the canvas to mainpanel
add(mainpanel); // adds the panel in the frame
}
class DrawCanvas extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(cbw); // puts color to the background
ball.paint(g); // the ball paints itself
}
}
private void move_Left(){
int savedX = ball.x;
ball.x -=10;
canvas.repaint(savedX, ball.y, ball.WIDTH, ball.HEIGHT);
canvas.repaint(ball.x,ball.y,ball.WIDTH,ball.HEIGHT);
}
private void move_Right(){
int savedX = ball.x;
ball.x += 10;
canvas.repaint(savedX, ball.y, ball.WIDTH, ball.HEIGHT);
canvas.repaint(ball.x,ball.y,ball.WIDTH,ball.HEIGHT);
}
}
// the ball class
public class Ball extends JFrame {
//variables for the construction of the circle
int x, y; // actual position of the ball
int WIDTH, HEIGHT;// parameters for the size of the rectangle where the circle is posited.
Color color = Color.RED;// the color of the ball
// the constructor of the class
public Ball(int x, int y, int WIDTH, int HEIGHT,Color color) {
this.x = x;//
this.y = y;
this.WIDTH = WIDTH;
this.HEIGHT = HEIGHT;
this.color=color;
}
// method for the color and drawing the ball
public void paint(Graphics g) {
g.setColor(Color.red);
g.fillOval(80,70, 350,350);
}
}
Start by using the values of Ball in it paint methods instead of :
// method for the color and drawing the ball
public void paint(Graphics g) {
g.setColor(Color.red);
g.fillOval(80,70, 350,350);
}
It should look like
// method for the color and drawing the ball
public void paint(Graphics g) {
g.setColor(Color.red);
g.fillOval(x,y, WIDTH, HEIGHT);
}
Related
Hello I am currently making a small game in java, and I am running into problems trying to making the gamepanel. I am using a JPanel as the basis and JPanel to the top to put in a HUD, and a gamepanel for the playable protion of the game. I can add the two panels the HUD and gamepanel fine. However the objects which are JComponents will not show up at all. I know they are created I'm not sure how to make them visible though.
Here are my classes:
This is my window class that holds the panels:
public class Window extends JFrame {
public static final int ScreenWidth = 1000;
public static final int ScreenHeight = 700;
public static JFrame frame;
private StatesHandler statesHandler;
public Window(JFrame frame) throws IOException {
this.frame = frame;
this.statesHandler = new StatesHandler();
displaywindow();
}
public void paint(Graphics g) {
super.paint(g);
}
public void displaywindow() {
this.frame.setLayout(new FlowLayout());
this.frame.setPreferredSize(new Dimension(ScreenWidth,ScreenHeight));
this.frame.setMaximumSize(new Dimension(ScreenWidth,ScreenHeight));
this.frame.setMinimumSize(new Dimension(ScreenWidth,ScreenHeight));
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.frame.setResizable(false);
this.frame.setBackground(Color.pink);
this.frame.setLocationRelativeTo(null);
this.frame.pack();
this.frame.setVisible(true);
}
public JFrame getFrame() {
return this.frame;
}
This is this the level class:
it holds the hud and the gamepanel
private Window win;
Level(Window win) {
this.setPreferredSize(new Dimension(gw,gh));
this.win = win;
this.setFocusable(true);
this.requestFocus();
Hud hud = new Hud();
getwinframe().getContentPane().add(hud);
getwinframe().getContentPane().validate();
gamepanel gmp = new gamepanel();
getwinframe().getContentPane().add(gmp);
getwinframe().getContentPane().revalidate();
Ball ball = new Ball(600, 200, 3, 3);
System.out.println(this);
gmp.add(ball);
gmp.revalidate();
}
Here is the Ball which I am trying to add to gamepanel
public Ball(int xpos, int ypos,int vx, int vy) {
this.xpos =xpos;
this.ypos = ypos;
this.vx = vx;
this.vy = vy;
this.collsionbox = new Rectangle(xpos, ypos, bwidth, bheight);
}
This is the gamepanel which I'm trying to add the ball to
public gamepanel(){
this.setPreferredSize(new Dimension(Window.ScreenWidth, Window.ScreenHeight -Window.ScreenHeight/6));
this.setLayout(new FlowLayout());
System.out.println(Window.ScreenWidth +" " + Window.ScreenHeight/6);
this.setBackground(Color.pink);
Ball ball2 = new Ball(500, 100, 3, 3);
System.out.println(ball2);
add(ball2);
validate();
}
It runs, the buttons work, but i just can't get it to draw with the paint(). I think it has something to do with the main method on SwingDraw, but i'm not 100% sure. Thanks for any help and sorry for the long code :/
SwingDraw:
// Import Core Java packages
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
public class SwingDraw extends JFrame implements ActionListener, ItemListener{
// Initial Frame size
static final int WIDTH = 1500; // frame width
static final int HEIGHT = 1000; // frame height
// Color choices
static final String[] COLOR_NAMES = new String[]{"None", "Red", "Blue", "Green"};
static final Color COLORS[] = {null, Color.red, Color.blue, Color.green };
// Button control
JButton circle;
JButton roundRec;
JButton threeDRec;
JButton line;
JButton square;
JButton oval;
JButton clear;
JButton delete;
// List to keep track of shapes
JList<String> shapesKeeper;
// Color choice box
JComboBox<String> colorChoice = new JComboBox<>(COLOR_NAMES);
SwingDrawCanvas betterCanvas = new SwingDrawCanvas();
/**
* Constructor
*/
public SwingDraw() {
// Create a frame
setSize(WIDTH, HEIGHT);
setLocation(130, 100);
// add window closing listener
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create panel for controls
JPanel topPanel = new JPanel();
JPanel leftList = new JPanel();
// create button control
JPanel buttonPanel = new JPanel();
topPanel.add(buttonPanel, BorderLayout.NORTH);
circle = new JButton("Circle");
buttonPanel.add(circle);
roundRec = new JButton("Rounded Rectangle");
buttonPanel.add(roundRec);
threeDRec = new JButton("3D Rectangle");
buttonPanel.add(threeDRec);
line = new JButton("Line");
buttonPanel.add(line);
square = new JButton("Square");
buttonPanel.add(square);
oval = new JButton("Oval");
buttonPanel.add(oval);
clear = new JButton("Clear");
buttonPanel.add(clear);
JPanel listPanel = new JPanel();
leftList.add(listPanel, BorderLayout.WEST);
JList<String> shapesKeeper = new JList<>();
listPanel.add(shapesKeeper);
delete = new JButton("Delete Shape");
listPanel.add(delete);
// add button listener
circle.addActionListener(this);
roundRec.addActionListener(this);
threeDRec.addActionListener(this);
line.addActionListener(this);
square.addActionListener(this);
oval.addActionListener(this);
clear.addActionListener(this);
// create panel for color choices
JPanel colorPanel = new JPanel();
JLabel label = new JLabel("Filled Color:");
topPanel.add(colorPanel);
colorPanel.add(label);
JComboBox<String> colorChoice = new JComboBox<>(COLOR_NAMES);
colorPanel.add(colorChoice);
colorChoice.addItemListener(this);
add(topPanel, BorderLayout.NORTH);
add(leftList, BorderLayout.WEST);
setVisible(true);
} // end of constructor
/**
* Implementing ActionListener
*/
public void actionPerformed(ActionEvent event) {
if(event.getSource() == circle) { // circle button
betterCanvas.setShape(SwingDrawCanvas.CIRCLE);
}
else if(event.getSource() == roundRec) { // rounded rectangle button
betterCanvas.setShape(SwingDrawCanvas.ROUNDED_RECTANGLE);
}
else if(event.getSource() == threeDRec) { // 3D rectangle button
betterCanvas.setShape(SwingDrawCanvas.RECTANGLE_3D);
}
else if(event.getSource() == clear){
betterCanvas.setShape(SwingDrawCanvas.CLEAR);
}
else if(event.getSource() == line){
betterCanvas.setShape(SwingDrawCanvas.LINE);
}
else if(event.getSource() == square){
betterCanvas.setShape(SwingDrawCanvas.SQUARE);
}
else if(event.getSource() == oval){
betterCanvas.setShape(SwingDrawCanvas.OVAL);
}
}
/**
* Implementing ItemListener
*/
public void itemStateChanged(ItemEvent event) {
Color color = COLORS[colorChoice.getSelectedIndex()];
betterCanvas.setFilledColor(color);
}
/**
* the main method
*/
public static void main(String[] argv) {
new SwingDraw();
}
}
SwingDrawCanvas:
public class SwingDrawCanvas extends JPanel implements MouseListener, MouseMotionListener {
// Constants for shapes
public static final int CIRCLE = 1;
public static final int ROUNDED_RECTANGLE = 2;
public static final int RECTANGLE_3D = 3;
public static final int LINE = 4;
public static final int SQUARE = 5;
public static final int OVAL = 6;
public static final int CLEAR = 7;
// Coordinates of points to draw
private int x1, y1, x2, y2;
// shape to draw
private int shape = CIRCLE;
/**
* Method to set the shape
*/
public void setShape(int thisShape) {
System.out.println("HEY");
this.shape = thisShape;
System.out.println(shape);
}
// filled color
private Color filledColor = null;
/**
* Method to set filled color
*/
public void setFilledColor(Color color) {
filledColor = color;
}
/**
* Constructor
*/
public SwingDrawCanvas() {
addMouseListener(this);
addMouseMotionListener(this);
} // end of constructor
/**
* painting the component
*/
public void paint(Graphics g) {
System.out.println("ARHFHASJDASHDHAs");
super.paint(g);
System.out.println("AHAHAHAHAHAHAHA");
g.drawString("FUCK", 1, 1);
// the drawing area
int x, y, width, height;
// determine the upper-left corner of bounding rectangle
x = Math.min(x1, x2);
y = Math.min(y1, y2);
// determine the width and height of bounding rectangle
width = Math.abs(x1 - x2);
height = Math.abs(y1 - y2);
if(filledColor != null)
g.setColor(filledColor);
switch (shape) {
case ROUNDED_RECTANGLE :
if(filledColor == null)
g.drawRoundRect(x, y, width, height, width/4, height/4);
else
g.fillRoundRect(x, y, width, height, width/4, height/4);
break;
case CIRCLE :
int diameter = Math.max(width, height);
if(filledColor == null)
System.out.println("HRE BITCHS");
else
System.out.println("HEY FUCK YOU GUY");
break;
case RECTANGLE_3D :
if(filledColor == null)
g.draw3DRect(x, y, width, height, true);
else
g.fill3DRect(x, y, width, height, true);
break;
}
}
/**
* Implementing MouseListener
*/
public void mousePressed(MouseEvent event) {
x1 = event.getX();
y1 = event.getY();
}
public void mouseReleased(MouseEvent event) {
x2 = event.getX();
y2 = event.getY();
repaint();
}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
/**
* Implementing MouseMotionListener
*/
public void mouseDragged(MouseEvent event) {
x2 = event.getX();
y2 = event.getY();
repaint();
}
public void mouseMoved(MouseEvent e) {}
}
I'm not very good at this, I'm just looking for any help you guys can give me :D
Instead of having paint(), your function should be name paintComponent(Graphics g).
When creating the paintComponent(Graphics g) functions, you need #Override so that java recognizes the function because you can not call paintComponent(Graphics g) directly.
In addition, any time you want to refresh your panel, you can call repaint() or you can resize your JFrame after the code as compiled. Both of these methods will call the paintComponent(Graphics g) function.
I want to prohibit my Sprite object to move on certain coordinates of canvas. How can I do this ? What I have done until now:
Package project1;
import java.awt.*;
// Using AWT's Graphics and Color
import java.awt.event.*;
// Using AWT's event classes and listener
interfaces import javax.swing.*;
// Using Swing's components and containers
/**
* Custom Graphics Example: Using key/button to move a object left or right.
* The moving object (sprite) is defined in its own class, with its own
* operations and can paint itself. *
*/ class Sprite {
// Variables (package access)
public int x;
public int y;
int width, height;
// Use an rectangle for illustration
Color color = Color.RED; // Color of the object
// Constructor
public Sprite(int x, int y, int width, int height, Color color) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
}
// Paint itself given the Graphics context
public void paint(Graphics g) {
g.setColor(color);
g.fillRect(x, y, width, height); // Fill a rectangle
// g.drawLine(20, 0, 20, 240);
System.out.println("paint X: "+x+" Y: "+y);
//System.out.println("paint 2nd X: "+x+" Y: "+y); } }
public class Project1 extends JFrame {
// Define constants for the various dimensions
public static final int CANVAS_WIDTH = 400;
public static final int CANVAS_HEIGHT = 240;
public static final Color CANVAS_BG_COLOR = Color.CYAN;
private DrawCanvas canvas;
// the custom drawing canvas (an inner class extends JPanel)
private Sprite sprite; // the moving object
// Constructor to set up the GUI components and event handlers
public Project1() {
// Construct a sprite given x, y, width, height, color
int x = 0,y = 0;
sprite = new Sprite(CANVAS_WIDTH / 2 - 30, CANVAS_HEIGHT / 2 - 30,
10, 10, Color.RED);
// Set up a panel for the buttons
JPanel btnPanel = new JPanel(new FlowLayout());
JButton btnLeft = new JButton("Move Left ");
btnPanel.add(btnLeft);
btnLeft.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
moveLeft();
requestFocus(); // change the focus to JFrame to receive KeyEvent
}
});
//JPanel btnPanel1 = new JPanel(new FlowLayout());
JButton btnDown = new JButton("Move down ");
btnPanel.add(btnDown);
btnDown.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
moveDown();
requestFocus(); // change the focus to JFrame to receive KeyEvent
}
});
JButton btnRight = new JButton("Move Right");
btnPanel.add(btnRight);
btnRight.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
moveRight();
requestFocus(); // change the focus to JFrame to receive KeyEvent
}
});
JButton btnUp = new JButton("Move Up");
btnPanel.add(btnUp);
btnUp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
moveUp();
requestFocus(); // change the focus to JFrame to receive KeyEvent
}
});
// Set up the custom drawing canvas (JPanel)
canvas = new DrawCanvas();
canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
// Add both panels to this JFrame
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
cp.add(canvas, BorderLayout.CENTER);
cp.add(btnPanel, BorderLayout.SOUTH);
// "super" JFrame fires KeyEvent
addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent evt) {
switch(evt.getKeyCode()) {
case KeyEvent.VK_LEFT: moveLeft(); break;
case KeyEvent.VK_RIGHT: moveRight(); break;
case KeyEvent.VK_DOWN: moveDown(); break;
case KeyEvent.VK_UP: moveUp(); break;
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Move a Sprite");
pack(); // pack all the components in the JFrame
setVisible(true); // show it
requestFocus(); // "super" JFrame requests focus to receive KeyEvent }
// Helper method to move the sprite left private void moveLeft() {
// Save the current dimensions for repaint to erase the sprite
int savedX = sprite.x;
// update sprite
sprite.x -= 10;
// Repaint only the affected areas, not the entire JFrame, for efficiency
canvas.repaint(savedX, sprite.y, sprite.width, sprite.height); // Clear old area to background
canvas.repaint(sprite.x, sprite.y, sprite.width, sprite.height); // Paint new location }
// Helper method to move the sprite right private void moveRight() {
// Save the current dimensions for repaint to erase the sprite
int savedX = sprite.x;
// update sprite
sprite.x += 10;
// Repaint only the affected areas, not the entire JFrame, for efficiency
canvas.repaint(savedX, sprite.y, sprite.width, sprite.height); // Clear old area to background
canvas.repaint(sprite.x, sprite.y, sprite.width, sprite.height); // Paint at new location }
private void moveDown() {
//Save the current dimensions for repaint to erase the sprite
int saved = sprite.y;
// update sprite
sprite.y += 10;
// Repaint only the affected areas, not the entire JFrame, for efficiency
canvas.repaint( sprite.x, saved, sprite.width, sprite.height); // Clear old area to background
canvas.repaint(sprite.x, sprite.y, sprite.width, sprite.height); // Paint new location } private void moveUp() {
//Save the current dimensions for repaint to erase the sprite
int savedY = sprite.y;
// update sprite
sprite.y -= 10;
// Repaint only the affected areas, not the entire JFrame, for efficiency
canvas.repaint( sprite.y, savedY, sprite.width, sprite.height); // Clear old area to background
canvas.repaint(sprite.x, sprite.y, sprite.width, sprite.height); // Paint new location }
// Define inner class DrawCanvas, which is a JPanel used for custom drawing class DrawCanvas extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(CANVAS_BG_COLOR);
sprite.paint(g); // the sprite paints itself
} }
// The entry main() method public static void main(String[] args) {
// Run GUI construction on the Event-Dispatching Thread for thread safety
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Project1(); // Let the constructor do the job
}
});
}
}
Too many comments in the code making it difficult to spot the issue, but, going from your question, you could use a grid to keep track of the x&y coordinates. And then check if the coordinates your object is at corresponds with the location(s) you don't want the object to move to. I am using the same strategy for my simulation.
My drawing class: for example I just want to draw a simple line
public class DrawNot1 extends JPanel {
private BasicStroke BS = new BasicStroke(2);
private int x;
private int y;
public DrawNot1(int x, int y){
setSize(100, 100);
this.x = x;
this.y = y;
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
doDrawing(g);
}
private void doDrawing(Graphics g){
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(BS);
g2d.drawLine(x, y, x, y+10);
}
my JFrame class:
public class Main extends JFrame{
private int x;
private int y;
public Main() {
initUI();
}
public void initUI() {
setSize(600, 500);
setTitle("Points");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new DrawNot1(20, 20));
add(new JButton("button1"));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Main ex = new Main();
ex.setVisible(true);
}
});
}
}
I want to show my drawing next to the button but that doesn't appear the only component that appear is the button, my drawing does not.
My ultimate goal is when I press the button my drawing is appear near the button.
JFrame uses a BorderLayout by default, adding two components to the default (CENTRE) position means that only the last one added will be shown.
Try adding the button to the SOUTH position instead
add(new JButton("button1"), BorderLayout.SOUTH);
You may also find the overriding the getPreferredSize method of DrawDot1 and providing a suitable value will also result in a better output
I have an application which has a swing user interface class, which has buttons that send variables to a canvas class like so;
public class createWindow extends JFrame implements ActionListener
{
createCanvas canvas = new createCanvas(10, 10);
JPanel mainPanel = new JPanel();
public createWindow()
{
mainPanel.add(canvas, BorderLayout.CENTER);
}
}
createCanvas is a class which declares a paintComponent;
public class createCanvas extends JPanel
{
int xValue;
int yValue;
int xCoordinate;
int yCoordinate;
public createCanvas(int x, int y)
{
xValue = x;
yValue = y;
}
public void setXCoordinate(int x)
{
xCoordinate = x;
}
public void setYCoordinate(int y)
{
yCoordinate = y;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
drawGrid(g, this.xValue, this.yValue);
g.fillArc(xCoordinate, yCoordinate, 6, 6, 0, 360);
}
public drawGrid(Graphics g, int xLength, int yLength)
{
//creates a grid that is xLength x yLength
}
}
However, I also have a selection of Objects which I want to have a .draw() function, which can use the paintComponent in createCanvas.
The problem is, of course, when I need to draw the node on the grid, I can set the coordinates, but how do I display the node on the canvas I declared in createWindow?
public class Node()
{
int xCoordinate;
int yCoordinate;
//Suitable constructors, sets, gets
public void draw()
{
createCanvas canvas = new createCanvas();
canvas.setXCoordinate(this.xCoordinate);
canvas.setYCoordinate(this.yCoordinate);
canvas.repaint();
}
}
So, I am wondering if there is a way for me to keep what I have drawn on the canvas in createWindow, as well as what I draw in my Object class.
Thanks.
What you want to do is have the draw method in your object take a Graphics argument. This Graphics object will be the same Graphics context in your paintComponent method. You can create the object in your JPanel class. Something like this
public class Circle {
int x, y;
public Circle(int x, int y) {
this.x = x;
this.y = y;
}
public void drawCirlce(Graphics g) {
g.fillRect(x, y, 50, 50);
}
}
Then in you JPanel class
public class CirclePanel extends JPanel {
Circle circle = new Circle(100, 100);
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
circle.drawCircle(g);
}
}
You can have a setter for the x and y in your Circle class. You should change them somewhere in your JPanel class then call repaint() afterwards. You could move it with the press of a key or you can animate it with a java.util.Timer. For example
With a Timer
public class CirclePanel extends JPanel {
Circle circle = new Circle(100, 100);
public CirclePanel() {
Timer timer = new Timer(50, new ActionListener(){
#Override
public void actionPerfomed(ActionEvent e) {
circle.x += 10;
repaint();
}
});
timer.start();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
circle.drawCircle(g);
}
}
With a key binding
public class CirclePanel extends JPanel {
Circle circle = new Circle(100, 100);
public CirclePanel() {
InputMap inputMap = getInputMap(JComponent.WHEN_FOCUSED_IN_WINDOW);
inputMap.put(KeyStroke.getKeyStroke("RIGHT"), "moveRight");
getActionMap().put("moveRight", new AbstractAction(){
public void actionPerformed(ActionEvent e) {
circle.x += 10;
repaint();
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
circle.drawCircle(g);
}
}
With a button press
public class CirclePanel extends JPanel {
Circle circle = new Circle(100, 100);
public CirclePanel() {
JButton button = new JButton("Move Right");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
circle.x += 10;
repaint();
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
circle.drawCircle(g);
}
}