Last active
August 29, 2015 13:56
-
-
Save aptavout/9225128 to your computer and use it in GitHub Desktop.
Windowed, threaded, double-buffered JFrame with Graphics2D text.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* To change this template, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
package lab; | |
import java.awt.*; | |
import javax.swing.JFrame; | |
/** | |
* Moment of truth: threaded display to move a ball around | |
* Will it appear double-buffered ? | |
* @author Core ideas from Brackeen, Holder & Bell | |
*/ | |
public class Bounce extends JFrame implements Runnable { | |
public static void main(String[] args) { | |
Bounce b = new Bounce(500,500); | |
new Thread(b).start(); | |
} | |
private boolean running = true; | |
private Image offscreenImage; | |
private Graphics offscr; | |
private int width, height; // bounds | |
public Bounce(int width, int height) { | |
super(); | |
this.width = width; | |
this.height = height; | |
setPreferredSize(new Dimension(width, height)); | |
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
setResizable(false); | |
pack(); | |
setVisible(true); | |
} | |
public void run() { | |
while (running) { | |
try { | |
repaint(); | |
System.out.println("ball moved to (" + x + "," + y + ")"); | |
try { | |
Thread.sleep(1000/30); | |
} catch (InterruptedException e) { | |
} | |
} finally { | |
} | |
} | |
} | |
float x = 0; | |
float y = 100; | |
float dx = 1; | |
float dy = 0; // purely eastward movement | |
public void paint(Graphics g) { | |
if (offscr == null) { | |
offscreenImage = createImage(getWidth(), getHeight()); | |
offscr = offscreenImage.getGraphics(); | |
} | |
// draw to offscr context here | |
// Draw checkerboard background | |
int x2 = width >> 1; | |
int y2 = height >> 1; | |
offscr.setColor(Color.gray); | |
offscr.fillRect(0, 0, x2, y2); | |
offscr.fillRect(x2, y2, width - x2, height - y2); | |
offscr.setColor(Color.white); | |
offscr.fillRect(x2, 0, width - x2, height - y2); | |
offscr.fillRect(0, y2, x2, y2); | |
// draw 'ball' | |
offscr.setColor(Color.BLUE); | |
offscr.fillOval((int)x, (int)y, 10, 10); | |
// set text anti-aliasing | |
if (offscr instanceof Graphics2D) { | |
Graphics2D g2 = (Graphics2D)offscr; | |
g2.setRenderingHint( | |
RenderingHints.KEY_TEXT_ANTIALIASING, | |
RenderingHints.VALUE_TEXT_ANTIALIAS_ON); | |
} | |
offscr.setFont(new Font("Dialog", Font.PLAIN, 24)); | |
offscr.setColor(Color.MAGENTA); | |
offscr.drawString("Hello world!", 50, 50); | |
// 'move' oval (ball) | |
x += dx; | |
y += dy; | |
g.drawImage(offscreenImage, 0, 0, null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment