I am a student trying to figure out the basics of Java's graphics. My class creates a window where a single red button will move every time it is pressed. I set the bounds of the window to 720x720 and the button is 50 pixels wide. Everytime it is pressed, the button goes to a new x and y coordinate that is between 0 and 670. My understanding is that if the setBounds() method is called with the parameters (670,670,50,50) then my red button will occupy the bottom right corner of the window.
Unfortunately, the button seems to be going outside of the window even when the bounds are set to something like (660,660,50,50).
I have tried tracking the bounds by printing every change in coordinates but this still does not add up.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Custom extends JPanel
{
//fields
private int kovakx = 0, kovaky = 0; //stores x and y coordinates of the button
private double accuracy_percent = 100; //not used yet
private JButton kovak = new JButton();
//Only ActionListener this program needs since theres only one button that moves around the screen.
private class Elim implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
kovakx = (int)(Math.random()*670);
kovaky = (int)(Math.random()*670);
kovak.setBounds(kovakx,kovaky,50,50);
System.out.println(kovakx+","+kovaky);//prints out the new coordinates of the button
}
}
//Constructor sets icon and initally puts the button in the top left corner
public Custom()
{
kovak.setIcon(new ImageIcon("Target.png"));
setLayout(null);
kovak.setBounds(0,0,50,50);
kovak.addActionListener(new Elim());
add(kovak);
}
//Creates frame based on teacher's tutorials.
public static void main(String args[])
{
Custom a = new Custom();
JFrame f = new JFrame("Reaction and Accuracy Test");
f.setSize(720,720);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(a);
f.setVisible(true);
}
}