Results 1 to 3 of 3
- 08-31-2011, 06:21 AM #1
Member
- Join Date
- Aug 2011
- Posts
- 1
- Rep Power
- 0
Can someone help me fix this please?
For some reason when I run this code nothing at all happens. All I want it to do is have the rectangle move across the screen. Here's my code:
Java Code:package game; import javax.swing.*; public class Game { public static void main(String[] args) { new Game(); } public Game() { JFrame f = new JFrame("My Graphics"); Panel p = new Panel(); f.setSize(800, 600); f.setLocationRelativeTo(null); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(p); f.setVisible(true); } } package game; import java.awt.*; import javax.swing.*; public class Panel extends JPanel { private int txtx, txty; private int rectx, recty; private int ovalx, ovaly; private boolean running; public Panel() { txtx = 50; txty = 50; rectx = 50; recty = 80; ovalx = 50; ovaly = 210; running = true; setBackground(Color.WHITE); setForeground(Color.BLACK); setFont(new Font("Ariel", Font.PLAIN, 20)); gameloop(); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.drawString("diz iz mah texz", txtx, txty); g2.setColor(Color.RED); g2.fillRect(rectx, recty, 100, 100); g2.setColor(Color.BLUE); g2.fillOval(ovalx, ovaly, 100, 100); } public void gameloop() { while (running) { rectx++; repaint(); try { Thread.sleep(20); } catch (Exception e) { } } } }
- 08-31-2011, 07:07 AM #2
Lesson: Concurrency in Swing (The Java™ Tutorials > Creating a GUI With JFC/Swing)
Don't run a continuously running loop or Thread#sleep(...) on the EDT. Use a Swing Timer.
db
- 08-31-2011, 01:55 PM #3


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks