Can't draw more than one square in JFrame - java

Can't get the program to print more than one square.
My code right now
import java.awt.*;
import javax.swing.*;
public class MyApplication extends JFrame {
private static final Dimension WindowSize = new Dimension(600, 600);
private int xCord=9, yCord=32, width=80, height=80;
public MyApplication() {
//Create and set up the window
this.setTitle("Squares");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Display the window centered on the screen
Dimension screensize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int x = screensize.width / 2 - WindowSize.width / 2;
int y = screensize.height / 2 - WindowSize.height / 2;
setBounds(x, y, WindowSize.width, WindowSize.height);
setVisible(true);
}
public static void main(String args[]) {
MyApplication window = new MyApplication();
}
public void paint(Graphics g) {
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
g.setColor(Color.getHSBColor(red, green, blue));
g.fillRect(xCord, yCord, width, height);
while((yCord+height)<600){
if((xCord+width)>600){
xCord=9;
yCord+=80;
}
else xCord+=80;
repaint();
}
}
}
I'm trying to fill a 600x600 window with squares of different colours that go to a new line once a row is full.

First of all, don't.
Don't override paint of top level containers, like JFrame.
JFrame is a composite component, meaning that they're a number of layers between its surface and the user and because of the way the paint system works, these can be painted independent of the frame, which can produce weird results.
Top level containers are not double buffered, meaning your updates will flash.
DO call a paint methods super method, unless you are absolutely sure you know what you're doing.
Start by taking a look at Performing Custom Painting and Painting in AWT and Swing for more details about how painting works in Swing and how you should work with it.
This...
Dimension screensize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int x = screensize.width / 2 - WindowSize.width / 2;
int y = screensize.height / 2 - WindowSize.height / 2;
setBounds(x, y, WindowSize.width, WindowSize.height);
is a bad idea on a number of levels.
Toolkit#getScreenSize does not take into consideration the size of other UI elements which will reduce the available viewable area available on the screen, things like the taskbar/dock or menu bar on some OS
Using setBounds(x, y, WindowSize.width, WindowSize.height); on a window based class is also a bad idea, as the avaliable viewable area is the window size MINUS the window's decorations, meaning the actually viewable area is smaller then you have specified and because you're painting directly to the frame, you run the risk of painting under the frame decorations.
You can have a look at How can I set in the midst? for more details
One thing you should now about painting, painting is destructive, that is, each time a paint cycle occurs, you are expected to completely repaint the current state of the component.
Currently, this...
public void paint(Graphics g) {
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
g.setColor(Color.getHSBColor(red, green, blue));
g.fillRect(xCord, yCord, width, height);
while ((yCord + height) < 600) {
if ((xCord + width) > 600) {
xCord = 9;
yCord += 80;
} else {
xCord += 80;
}
repaint();
}
}
will only paint a single rectangle, base on the last value of xCord and yCord most likely AFTER the paint method has exited.
Swing uses a passive rendering engine, meaning that the system will make determinations about what to paint and when, you don't control it. You can make a "request" to the system through the use repaint, but it's up to the system to decide when and what will get painted, this means that multiple requests can be optimised down to a single paint pass.
Also, painting should do nothing more than paint the current state. It should avoid changing the state, directly or indirectly, especially if that change triggers a new paint pass, as this can suddenly reduce the performance of your program to 0, crippling it.
So, what's the answer?
Well, change everything...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MyApplication {
public static void main(String[] args) {
new MyApplication();
}
public MyApplication() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class TestPane extends JPanel {
private static final Dimension DESIRED_SIZE = new Dimension(600, 600);
private int width = 80, height = 80;
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return DESIRED_SIZE;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int xCord = 0, yCord = 0;
while ((yCord) < getHeight()) {
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
g2d.setColor(Color.getHSBColor(red, green, blue));
g2d.fillRect(xCord, yCord, width, height);
if ((xCord + width) > getWidth()) {
xCord = 0;
yCord += 80;
} else {
xCord += 80;
}
}
g2d.dispose();
}
}
}
Break down...
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
This creates an instance of Jframe, you don't really want extend from JFrame, you're not adding any new functionality to the class
frame.pack() is packing the window around the content, this ensures that the frame is always larger (by the amount of the frame decorations) then the desired content size
frame.setLocationRelativeTo(null); will centre the window in a system independent manner.
Next...
private static final Dimension DESIRED_SIZE = new Dimension(600, 600);
private int width = 80, height = 80;
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return DESIRED_SIZE;
}
I've used DESIRED_SIZE to provide a sizing hint to the parent containers layout manager.
Finally...
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int xCord = 0, yCord = 0;
while ((yCord) < getHeight()) {
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
g2d.setColor(Color.getHSBColor(red, green, blue));
g2d.fillRect(xCord, yCord, width, height);
if ((xCord + width) > getWidth()) {
xCord = 0;
yCord += 80;
} else {
xCord += 80;
}
}
g2d.dispose();
}
Note here, I've changed the xCord and yCord positions to zero, I no longer need to "guess" at the frame decorations. As well as making the local variables, so that when ever the method is called again, the values are reset to zero.
You don't "have" to cast the Graphics reference to Graphics2D, but Graphics2D is a more powerful API. I also like to copy it's state, but that's me, your code is simple enough so it's unlikely to have adverse effects on anything else that might be painted after your component.
Notice also, I've use getWidth and getHeight instead of "magic numbers", meaning you can resize the window and the painting will adapt.

You could try placing the whole paint mechanism inside your loop to get it done with in a one call. Therefore you wont need to call repaint inside the paint method itself:
public void paint(Graphics g) {
while((yCord+height)<600){
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
g.setColor(Color.getHSBColor(red, green, blue));
g.fillRect(xCord, yCord, width, height);
if((xCord+width)>600){
xCord=9;
yCord+=80;
}
else xCord+=80;
}
}

Related

How do I animate my java Swing graphics2d component

I'm making a gravity simulator and I need it animate live so the user can watch it. I've been able to make it trace out the path the object would take.
But as you can see it just traces it out and then displays the window. I think my problem is because all of this in the section of code that builds the JPanel but I don't know how to change it properly.
Here's what I'm doing for my window:
import java.awt.*;
import javax.swing.*;
import java.lang.Math;
public class Universe {
public static void main(String[] args) throws InterruptedException {
new Universe();
}
public Universe() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Gravity Simulator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
int paneWidth = 500;
int paneHeight = 500;
#Override
public Dimension getPreferredSize() {
return new Dimension(paneWidth, paneHeight);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int size = Math.min(getWidth()-4, getHeight()-4) / 10;
int width = getWidth() - (size * 2);
int height = getHeight() - (size * 2);
int x0=paneWidth/2; int y0=paneHeight/2; int radius0=20;
int y = (getHeight() - (size * 10)) / 2;
for (int horz = 0; horz < 2; horz++) {
int x = (getWidth() - (size * 10)) / 2;
for (int vert = 0; vert < 10; vert++) {
g.drawRect(x, y, size, size);
drawCircle(g, x+25, y+25, 5);//A massive object would go here this just proof of concept
x += size;
}
y += size;
}
double[] velocity={5,-2};
MassiveObject planet = new MassiveObject(g, 20, 50, velocity, 250, 150);
planet.draw(g);
MassiveObject rock = new MassiveObject(g, 2, 25, velocity, 275, 300);
rock.draw(g);
double sGravity = fGrav(planet, rock);
//double dis = massDis(planet, rock);
System.out.println("Distance: "+massDis(planet, rock));
System.out.println("Gravity: "+sGravity+" Newtons of force(gravity is multiplied by "+1000000+")");
double[] traj = objectTrajetory(planet, rock, rock.getMass());
int t = 0;
try {
while(true) {
//double k = sGravity/dis;
//x and y components of motion
double xm = traj[0];
double ym = traj[1];
double[] nVelocity= {xm,ym};
//////////////////////////////
//set new position of object
rock.setX(rock.getX()+(xm));
rock.setY(rock.getY()+(ym));
rock.setVelocity(nVelocity);
rock.draw(g);
t++;
System.out.println("position changed: "+rock.getCoords());
traj = objectTrajetory(planet, rock, 1);
Thread.sleep(100);
if (t> 15){break;}
}
}
catch(Exception e) {
}
//System.out.println("Distance: "+massDis(planet, rock));
//System.out.println("Gravity: "+fGrav(planet, rock)+" Newtons of force(gravity is multiplied by "+1000000+")");
g2d.dispose();
}
And here is the code for the draw function of my MassiveObject:
public void draw(Graphics g){
Graphics2D g2d = (Graphics2D) g;
Ellipse2D.Double circle = new Ellipse2D.Double(this.x0-(this.radius/2), this.y0-(this.radius/2), this.radius, this.radius);
g2d.setColor(Color.GRAY);
g2d.fill(circle);
}
So basically what I'm asking is how can I make it run that algorithm to paste the MassiveObject at its new location after the window is already pulled up so the user can watch it happening instead of it just building the window with it already on it?
The logic of your animation shouldn't be in the paintComponent() method. The paintComponent() method should just paint the current frame of animation. The code inside paintComponent() is run inside a special thread dedicated to handling all UI paints, responding to clicks etc. So for as long as paintComponent() is running, nothing else can happen in the UI, hence your application "grinds to a halt".
The logic to periodically update the state and then order a repaint should be in a separate thread (or the main thread). When it has updated the state and needs the next frame to be drawn, it then calls the panel's repaint() method. Because you're doing this in another thread, you would surround it in SwingUtilities.invokeLater(). This orders Swing to to call back into the paintComponent():
while (true) {
// Update state used by the paintComponent() method
updateObjectPositions();
// Now draw the new animation frame
SwingUtilities.invokeLater(() -> {
universePanel.repaint(0, 0, universeWidth, universeHeight);
});
Thread.sleep(...);
}
Because the drawing and updating are happening in different threads, you need to make sure that the data is shared between the threads in a thread-safe way. If you're just starting out and the calculations are very quick, then you could put the updateObjectPositions() method inside the invokeLater() so that the update to the data and the redraw happen in the UI thread. But remember that the code inside the invokeLater() will be blocking the UI for as long as it runs, so it should be as brief as possible and just handle a single frame. Crucially, your while loop and sleep should not go inside the invokeLater() or inside any UI code such as paintComponent().
Thanks a lot for the help, I was able to get the program animating the way I wanted it to and it was exactly as you all suggested. I removed my logic from the paintComponent() and put it inside the JPanel pane, ran a timer to continuously update the position, and then ran the repaint() function at the end of each loop in timer.
public class TestPane extends JPanel {
int paneWidth = 1200;
int paneHeight = 1200;
double[] velocity={4,4};
MassiveObject planet = new MassiveObject( 50, 50, velocity, paneWidth/2,paneHeight/2);
MassiveObject rock = new MassiveObject( 2, 25, velocity, 150, 200);
double[] traj = objectTrajetory(planet, rock, rock.getMass());
double xm=0.00;
double ym=0.00;
public TestPane() {
Timer timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
xm = traj[0];
ym = traj[1];
double[] nVelocity= {xm,ym};
//////////////////////////////
//set new position of object
rock.setX(rock.getX()+(xm));
rock.setY(rock.getY()+(ym));
rock.setVelocity(nVelocity);
System.out.println("position changed: "+rock.getCoords());
repaint();
traj = objectTrajetory(planet, rock, 1);
rock.setX(rock.getX()+(xm));
rock.setY(rock.getY()+(ym));
repaint();
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(paneWidth, paneHeight);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int size = Math.min(getWidth()-4, getHeight()-4) / 10;
int width = getWidth() - (size * 2);
int height = getHeight() - (size * 2);
int x0=paneWidth/2; int y0=paneHeight/2; int radius0=20;
rock.draw(g);
planet.draw(g);
g2d.dispose();
}
The program now animates pretty smoothly instead of just spitting out a plot of the path it would take.
Snap of Animated Orbit

Java Swing window size does not match AWT canvas result

I wanted to draw a rectangle with 80% width and 80% height of the original window in the JPanel.
Here's my driver class
public class driver {
public static void main(String[] args) {
System.out.println("test");
Window myWindow = new Window();
myWindow.add(new GraphPanel());
myWindow.settings();
}
}
Here's my JPanel:
import javax.swing.*;
public class Window extends JFrame {
private static final int width = 1100;
private static final int height = 600;
public void settings(){
setSize(width,height);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public static int[] getWindowSize(){
int[] output = new int[]{width, height};
return output;
}
}
and the rectangle canvas:
import java.awt.*;
public class GraphPanel extends Canvas {
public void paint(Graphics g){
setBackground(Color.WHITE);
setForeground(Color.DARK_GRAY);
int[] windowSize = Window.getWindowSize();
//Not working as intented
g.drawRect(windowSize[0]/10, windowSize[1]/10, 8*windowSize[0]/10, 8*windowSize[1]/10);
}
}
And here's the result,
I can't post image so here's a link
https://i.imgur.com/6D1gEF7.png
As you can see, this is clearly not centered, the height is off by about 30 pixels and width about 20. I have no idea how this happened, so my question is, does anyone know what might have caused this?
You might want to start by having a quick read of this to get a better understand of why you current approach isn't going to work (the way you expect).
The first thing I would do is change your GraphPanel so it defines it's preferredSize, independent of the window. This way you give control to the layout management system instead.
Next, I would use the actual physical size of the component to base your calculations on
int width = (int) (getWidth() * 0.8);
int height = (int) (getHeight() * 0.8);
I'd also recommend moving the setBackground and setBackground out of the paint method. This will cause a new pain cycle to occur and will make a mess of things.
public class GraphPanel extends Canvas {
private static final int PREF_WIDTH = 1100;
private static final int PREF_HEIGHT = 600;
public GraphPanel() {
setBackground(Color.WHITE);
setBackground(Color.DARK_GRAY);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_WIDTH, PREF_HEIGHT);
}
#Override
public void paint(Graphics g) {
super.paint(g);
int width = (int) (getWidth() * 0.8);
int height = (int) (getHeight() * 0.8);
int x = (getWidth() - width) / 2;
int y = (getHeight() - height) / 2;
//Not working as intented
g.drawRect(x, y, width, height);
}
}
I would then update your Window class so it used pack instead of setSize. This will "pack" the window around the content, taking into consideration the frame decorations.
public class Window extends JFrame {
public void settings() {
pack();
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Although, I'd question the point of extending from JFrame, but I'm getting of topic.
Speaking of which, unless you're intending to high performance graphics which requires you to have complete control over the painting sub system, I'd recommend starting with Swing based components or even JavaFX

JAVA can't paint onto JFrame from within another class

I am aware this is my error. My question is why isn't this working what am i missing i can call this is i put it a method instead of a class so i am assuming theirs something wrong with the third class?
Class 1:
package assignment.pkg1.java;
import java.awt.Color;
import javax.swing.JFrame;
public class JVMVeiwer {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
final int FRAME_WIDTH = 1000; // Frame Width
final int FRAME_HEIGHT = 800; // Frame Height
JFrame frame = new JFrame();
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); //Sets Frame Size
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("JVM Diagram");// Sets the Title
JVMComponent component = new JVMComponent();
frame.setBackground(Color.WHITE);
frame.add(component); // adds the diagram to the JFrame
frame.setVisible(true); // Makes the frame visible
}
}
Class 2:
package assignment.pkg1.java;
import java.awt.*;
import javax.swing.JComponent;
public class JVMComponent extends JComponent {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g; // recover the graphic
JVMDiagram diagram = new JVMDiagram(); // creates an instance of JVM Diagram
diagram.draw(g2);
}
}
Class 3 this is the one i i cant use o paint to the jframe:
package assignment.pkg1.java;
import java.awt.Color;
import java.awt.Graphics2D;
import javax.swing.JComponent;
public class JVMDiagram {
// Constructor
public JVMDiagram() {
}
// Draw method for shape
public void draw(Graphics2D g2) {
// Detailed instructions to draw shape
int x = getWidth();
int y = getHeight();
int temp, temp2;
int width = x / 2;
int height = x / 2;
x = (x - width) / 2;
y= (y - height) / 2;
g2.setColor(Color.RED);
g2.drawOval(x, y, width, height);
g2.drawRect(x, y, width, height);
g2.setColor(Color.RED);
g2.drawLine(x, y, width + x, height + y);
g2.drawRoundRect(x, y, width, height, y, y);
g2.drawLine(x + width, y, x, height + y);
}
}
Your problem is that you're misusing inheritance. Your JVMDiagram is extending JVMComponent and it shouldn't. Yes, you gain JVMComponent's getWidth() and getHeight() method, but they don't mean anything since JVMDiagram isn't being added to the GUI as a component, shouldn't be added as a component, and it has 0 height and width (print them out).
Rethink your design, don't use inheritance for this. Instead pass in values from one object to the other if needed. For instance, create a JVMDiagram field within JVMComponent and initialize it. Pass in the width and height with the Graphics2D in the JVMDiagram draw method in JVMComponent's paintComponent method.
Side issue: never call repaint() from within a painting method or from code that is called from within a painting method.

BufferedImage.setRGB() not updating

I am trying to do something simple. I have always had trouble getting Java GUIs working properly. I want the pixels to update when I write to them; but the for loop's drawing doesn't seem to be being drawn. What kind of update method do I need to call to get my BufferedImage to show up?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Panel;
import java.awt.image.BufferedImage;
public class DirectDrawDemo {
public static void main(String[] args) {
int width = 640;
int height = 480;
Frame frame = new Frame("Direct draw demo");
BufferedImage canvas = new BufferedImage(
width, height,
BufferedImage.TYPE_INT_RGB);
Panel panel = new Panel();
panel.setPreferredSize(new Dimension(width, height));
frame.add(panel);
frame.setVisible(true);
frame.setResizable(false);
panel.setBackground(Color.PINK);
for (int x = 1; x < width; x++)
for (int y = 0; y < height; y++)
canvas.setRGB(x, y, rgbtoint(0, 255, 0));
System.out.println(canvas.getRGB(0, 0) != canvas.getRGB(1, 0));
panel.paint(canvas.getGraphics());
panel.repaint();
frame.pack();
}
static int rgbtoint(int red, int green, int blue) {
int rgb = red;
rgb = (rgb << 8) + green;
rgb = (rgb << 8) + blue;
return rgb;
}
static int rgbtored(int rgb) {
return (rgb >> 16) & 0xFF;
}
static int rgbtogreen(int rgb) {
return (rgb >> 8) & 0xFF;
}
static int rgbtoblue(int rgb) {
return rgb & 0xFF;
}
}
Basically, what you are doing is painting the components of your panels on your image, instead of the other way around.
You seem to think that the method paint(Graphics g) puts the contents of g on the window. It doesn't. What it does is draw things on g. And it shouldn't be called directly. The usual way it works is that you create your own class that inherits from Panel (or whatever component), and override its paint() method, adding the operations that paint stuff inside it, by calling drawing methods of the Graphics object you are passed. In this case, you'd probably call g.drawImage(...).
When repaint() is called on the component, its paint() method will be called with the graphics that represents the window's "canvas" as its parameter, and whatever you added to paint() will be therefore drawn on it.
To learn more, start from the Oracle turorial on drawing primitives, and when you understand how the paint() method works, move on to drawing images.
To expand off of RealSkeptic's answer, here is an example of overriding the paintComponent method to add your custom drawing.
public static class MyPanel extends JPanel {
private int width;
private int height;
public MyPanel(int width, int height) {
this.width = width;
this.height = height;
setPreferredSize(new Dimension(width, height));
setBackground(Color.PINK);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 1; x < width; x++) {
for (int y = 0; y < height; y++) {
canvas.setRGB(x, y, new Color(0, 255, 0).getRGB());
}
}
g.drawImage(canvas, 0, 0, null);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Direct draw demo");
JPanel panel = new MyPanel(640, 480);
frame.add(panel);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}

JPanel: automatically paint at creation?

This must be rather trivial and straight forward, but I cannot figure it out.
This is what my JPanel looks like, it is added to a JFrame:
private class RadarPanel extends JPanel {
public RadarPanel() {
super();
this.repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//painting logic here
//repaint in 500 ms
this.repaint(500);
}
}
Now, when I resize the JFrame this JPanel starts getting redrawn all the time. However, when I do not resize the JFrame the JPanel's paintComponent method does not seem to get called, even though I call repaint in the constructor.
Any advice? Thanks.
UPDATE:
more complete code (everything except drawing logic):
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PlayerRadar extends JFrame {
private static final long serialVersionUID = 230324190;
//settings
private static final int windowWidth = 300;
private static final int windowHeight = 300;
private static final int maxDistance = 250;
//components
private PlayerRadar radarWindow;
private JPanel radarPanel;
public PlayerRadar(String title) {
super(title);
//set reference
radarWindow = this;
//create radar window
Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
this.setAlwaysOnTop(true);
this.setBackground(new Color(0xFFFFFF));
this.setBounds(screenSize.width - windowWidth, 0, windowWidth, windowHeight);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
radarWindow.setVisible(false);
}
});
this.setVisible(true);
//create a JPanel for drawing
radarPanel = new RadarPanel();
radarPanel.setBounds(0, 0, windowWidth, windowHeight);
radarPanel.setBackground(new Color(0xFFFFFF));
//add to frame
this.getContentPane().add(radarPanel);
}
private class RadarPanel extends JPanel {
private static final long serialVersionUID = 230324191;
private static final int repaintInterval = 500;
public RadarPanel() {
super();
}
#Override
public void paint(Graphics g) {
super.paint(g);
//draw player oval (center of the frame)
g.setColor(Color.BLUE); //blue
int ovalWidth = (int) Math.round(this.getWidth() / 30);
int ovalHeight = (int) Math.round(this.getHeight() / 30);
int playerLocalX = (int) Math.round(this.getWidth() / 2);
int playerLocalY = (int) Math.round(this.getHeight() / 2);
int ovalX = playerLocalX - ovalWidth / 2;
int ovalY = playerLocalY - ovalHeight / 2;
g.fillOval(ovalX, ovalY, ovalWidth, ovalHeight);
g.setColor(Color.BLACK); //black
g.drawOval(ovalX, ovalY, ovalWidth, ovalHeight);
//get info of the player itself
PlayerInfo thisPlayer = GameUtil.getPlayerInfo();
float playerPosZ = thisPlayer.position[0];
float playerPosX = thisPlayer.position[2];
//float playerRotRad = thisPlayer.rotation;
//set rectangle specs
int rectWidth = this.getWidth() / 40;
int rectHeight = this.getWidth() / 40;
//only continue if we have information about our player
if (thisPlayer != null) {
//get nearby players
ArrayList<PlayerInfo> playersInfo = GameUtil.getNearbyPlayers();
//for each other player, draw a rectangle
for (PlayerInfo playerInfo : playersInfo) {
//get data
float posZ = playerInfo.position[0];
float posX = playerInfo.position[2];
//float rotRad = playerInfo.rotation;
//calculate relative x and y
int rectX = playerLocalX + Math.round((posX - playerPosX) / maxDistance * this.getWidth() / 2) - rectWidth / 2;
int rectY = playerLocalY + ovalHeight / 2 + Math.round((playerPosZ - posZ) / maxDistance * this.getHeight() / 2) - rectHeight / 2;
//draw rectangle
g.setColor(Color.RED);
g.fillRect(rectX, rectY, rectWidth, rectHeight);
g.setColor(Color.BLACK);
g.drawRect(rectX, rectY, rectWidth, rectHeight);
}
}
//repaint soon
this.repaint(repaintInterval);
}
}
}
You where correct the first time. Custom painting is done in the paintComponent() method, NOT the paint() method.
You should NEVER invoke repaint() from within the paintComponent() method, since that will result in an infinite loop.
If you want to animate the painting, then you should be using a Swing Timer to schedule the animation.
You should not be using use setSize(). That is the job of the layout manager. Instead you can override the getPreferredSize() method of the panel (or use setPreferredSize()) and then you can pack() the frame, instead of setting its size.
The panel should be added to the frame BEFORE the frame is made visible otherwise it has a size of (0, 0) which means there is nothing to paint.
It won't repaint until your form is shown and graphics is initialized. I don't think calling repaint in constructor is a good idea. It will repaint once the component is visible.

Categories

Resources