I have to create a program that moves the circle using buttons, it doesn't move. I have tried lots of things but I'm afraid I should have organised the classes differently or I'm missing something. Here is the code that moves the circles without the conditions of overlapping.
DrawCircle class:
public class DrawCircle extends JComponent {
Graphics e;
@Override
public void paintComponent(Graphics g) {
g.drawOval(30,30,50,50);
e=g;
}
int moveSpeed = 10;
public void moveUp() {
if(e.getClipBounds().getMinY() - moveSpeed >= 0){ // make sure the future location of the circle is within bounds of visual frame
e.setClip( (int) Math. round(e.getClipBounds().getCenterX()),(int) Math. round( e.getClipBounds().getCenterY() - moveSpeed),(int) Math. round( e.getClipBounds().getX()),
(int) Math. round(e.getClipBounds().getY() - moveSpeed));
}
repaint();
}
public void moveDown()
{
if(e.getClipBounds().getMaxY() - moveSpeed <= 140){ // make sure the future location of the circle is within bounds of visual frame
e.setClip((int) Math. round(e.getClipBounds().getCenterX()),(int) Math. round( e.getClipBounds().getCenterY() + moveSpeed) ,(int) Math. round( e.getClipBounds().getX()),
(int) Math. round(e.getClipBounds().getY() + moveSpeed));
}
repaint();
}
public void moveRight ()
{
e.setClip((int) Math. round(e.getClipBounds().getCenterX()-10) ,(int) Math. round( e.getClipBounds().getCenterY()),
(int) Math. round(e.getClipBounds().getX()-10), (int) Math. round(e.getClipBounds().getY()) ) ;
repaint();
}
public void moveLeft()
{
e.setClip( (int) Math. round(e.getClipBounds().getCenterX()+10) ,(int) Math. round( e.getClipBounds().getCenterY()),
(int) Math. round(e.getClipBounds().getX()+10 ),(int) Math. round( e.getClipBounds().getY()));
repaint();
}
}
Main Class:
public class Main{
public static void main(String[] args) {
final JButton button1;
final JButton button2;
final JButton button3;
final JButton button4;
JPanel panel;
final JFrame frame=new JFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,200);
final DrawCircle c=new DrawCircle();
frame.add(c);
button1=new JButton(" Right ");
button2=new JButton(" Left ");
button3=new JButton(" Up ");
button4=new JButton(" Down ");
panel=new JPanel();
panel.setLayout(new BorderLayout());
panel.add(button1,BorderLayout.WEST);
panel.add(button2,BorderLayout.EAST);
panel.add(button3,BorderLayout.NORTH);
panel.add(button4,BorderLayout.SOUTH);
frame.add(panel,BorderLayout.EAST);
class ListenerClass implements ActionListener {
public void actionPerformed (ActionEvent e)
{
if (e.getSource()==button3)
{
c.moveUp();
}
else if (e.getSource()==button4)
{
c.moveDown();
}
else if (e.getSource()==button1)
{
c.moveRight();
}
else if (e.getSource()==button2)
{
c.moveLeft();
}
}
}
ListenerClass listen=new ListenerClass();
button1.addActionListener (listen);
button2.addActionListener (listen);
button3.addActionListener (listen);
button4.addActionListener (listen);
}
}