Reputation: 185
I've just finished a 2D vector/transformation library that I want to use on a simple example. I have a main loop that runs efficiently and update/render methods. I've always tried to understand what people are talking about when they use Java2D or jPanels or jFrames, but none of it makes sense to me.
I've made some 2D examples before, but it is using a jFrame with a Threaded canvas that I made when following a youtube tutorial. Its problem is that it is basically an integer array that allows for individual pixel setting and you can only use integers as positions, not floats like my library uses.
so my question is: how would I go about making a simple opening/closing window, that I can draw a sprite (should sprites just be some sort of slickUtil loaded thing, or will I have to load in individual pixels as I did before?) to, and that accepts float values for Cartesian coordinates with the origin at the centre.
Upvotes: 0
Views: 1796
Reputation: 799
Derive a class from JComponent and override the paintComponent method. It gets passed a Graphics object that can be cast into a Graphics2D object. The latter one has support for changing the coordinate system.
For drawing sprites: Loading individual pixels in a loop is very slow. There is a drawImage method in Graphics2D that supports everything you need for blitting sprites.
Here's an example to setup the Graphics2D object with a centered origin in a self-contained example:
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Line2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Draw2D extends JFrame {
public Draw2D() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(new DrawPane(), BorderLayout.CENTER);
pack();
}
public static void main(String[] args) {
Draw2D drawing = new Draw2D();
drawing.setVisible(true);
}
}
class DrawPane extends JComponent {
public DrawPane() {
setPreferredSize(new Dimension(640, 640));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// use anti-aliasing for smooth lines
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// move origin to center
g2.translate(getWidth() / 2, getHeight() / 2);
// scale as you need. Using negative y so that y points upward
// note that non-square window sizes will cause a different aspect ratio,
// you probably want to use Math.min(width, height) or something
g2.scale(getWidth() / 2, -getHeight() / 2);
// set color and thickness
g2.setColor(Color.red);
g2.setStroke(new BasicStroke(0.001f));
// draw coordinate lines
g2.draw(new Line2D.Float(-1f, 0f, 1.0f, 0f));
g2.draw(new Line2D.Float(0, -1.0f, 0.0f, 1.0f));
// draw a vector
g2.draw(new Line2D.Float(0f, 0f, 0.25f, 0.25f));
}
}
Upvotes: 3