So I was following a tutorial on ZetCode.com for creating basic animations (in this case, an animated star image on a black background). However, over the past few days of working with Swing, I've run into a recurring error, which I'm not sure of the reason for why it is happening. Essentially, I have the JFrame, but I can't seem to add top-level components to it. What I mean by this is that I can't add JPanels and such to the frame (I did manage to make a few buttons that for some reason showed up). I'm not sure whether it is a software issue or an error in my programming. If someone could look through the code to detect if anything is wrong, that would be awesome!
For the program, all that shows up is the 280 x 240 black screen. There is no image displaying on it.
P.S. I'm not sure what half of this stuff does. I'm kinda working through it line by line to try to figure out how to use the different libraries one at a time .
P.S.S. I'm at school right now. If there's no solution by the time I get home, I'll try running the program from my home computer to test if it is actually a software error, because in all the programs that have experienced this "blank frame" problem, there hasn't been any compile errors.
import javax.swing.JFrame; public class Star extends JFrame { public Star() { add(new Board()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(280, 240); setLocationRelativeTo(null); setTitle("Star"); setResizable(false); setVisible(true); } public static void main(String[] args) { new Star(); } }
import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.*; public class Board extends JPanel implements ActionListener { Image star; Timer t; int x, y; public Board() { setBackground(Color.BLACK); ImageIcon ii = new ImageIcon("/Desktop/images/star.png"); star = ii.getImage(); setDoubleBuffered(true); x = y = 10; t = new Timer(25, this); t.start(); } public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D)g; g2d.drawImage(star, x, y, this); Toolkit.getDefaultToolkit().sync(); g.dispose(); } public void actionPerformed(ActionEvent e) { x += 1; y += 1; if (y > 240) { y = x = -45; } repaint(); } }