I have a problem with a seemingly simple program. It is a ball that moves across the screen. However I don't know for what reason when I add to JPanel it doesn't work, the problem is created by: initComponents (); However, I need that method.
Does anyone have a solution?
Main class JFrame with JPanel:
I deleted all the parts created by Netbeans, in order to provide visibility, while of course they remain in the original code.
package newpackage;
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
jPanel1.add(new Core());
}
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
Circle JComponent class:
package newpackage;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.JComponent;
public class Circle extends JComponent {
int x, y, bounds = 80;
boolean move_up, move_left;
public Circle() {
Timer timer = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (x > getWidth() - bounds) {
move_left = true;
}
if (x < 0) {
move_left = false;
}
if (move_left) {
x -= 1;
} else {
x += 1;
}
if (y > getHeight() - bounds) {
move_up = true;
}
if (y < 0) {
move_up = false;
}
if (move_up) {
y -= 1;
} else {
y += 1;
}
repaint();
}
});
timer.start();
}
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g2d);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.RED);
g2d.fillOval(x, y, bounds, bounds);
}
}