PieChart in java not showing - java

My piechart in java isn't showing, for my class we are to make a piechart using graphics and the values are user-input based. even after trying to input any values, my piechart would not show up at all.
What am i doing wrong?
My code:
package ass15;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.HeadlessException;
import javax.swing.JFrame;
public class PieChart extends JFrame {
private int iNorth, iSouth, iEast, iWest, iMidWest;
public PieChart(int North, int South, int East, int West, int MidWest) throws HeadlessException {
super("Assignment 15");
this.iNorth = North;
this.iSouth = South;
this.iEast = East;
this.iWest = West;
this.iMidWest = MidWest;
}
public void Paint(Graphics g) {
//Integer to percent
double dNorth,dSouth,dEast,dWest,dMidWest, total;
dNorth = 0.00 + iNorth;
dSouth = 0.00 + iSouth;
dEast = 0.00 + iEast;
dWest = 0.00 + iWest;
dMidWest = 0.00 + iMidWest;
total = dNorth + dSouth + dEast + dWest + dMidWest;
//initial arc
int startAngle = 0;
double curValue = 0.00;
startAngle = (int) (curValue * 360/total);
int arcAngle = (int) (dNorth * 360/total);
g.setColor(Color.red);
g.fillArc(50, 50, 100, 100, startAngle, arcAngle);
//new arc
curValue += dNorth;
startAngle = (int) (curValue * 360/total);
arcAngle = (int) (dSouth * 360/total);
g.setColor(Color.green);
g.fillArc(50, 50, 50, 50, startAngle, arcAngle);
//new arc
curValue += dSouth;
startAngle = (int) (curValue * 360/total);
arcAngle = (int) (dEast * 360/total);
g.setColor(Color.blue);
g.fillArc(50, 50, 50, 50, startAngle, arcAngle);
//new arc
curValue += dEast;
startAngle = (int) (curValue * 360/total);
arcAngle = (int) (dWest * 360/total);
g.setColor(Color.magenta);
g.fillArc(50, 50, 50, 50, startAngle, arcAngle);
//new arc
curValue += dWest;
startAngle = (int) (curValue * 360/total);
arcAngle = (int) (dMidWest * 360/total);
g.setColor(Color.yellow);
g.fillArc(50, 50, 50, 50, startAngle, arcAngle);
//background circle
g.setColor( Color.black );
g.drawArc( 50, 50, 50, 50, 0, 360 );
}
}
and my main is:
package ass15;
import java.util.StringTokenizer;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class TestPieChart {
public static void main(String[] args) {
int north,south,east,west,midwest;
String token;
String in = "";
in = JOptionPane.showInputDialog("Input sales for regions");
StringTokenizer stk = new StringTokenizer(in, ",");
token = stk.nextToken().trim();
north = Integer.parseInt(token);
token = stk.nextToken().trim();
south = Integer.parseInt(token);
token = stk.nextToken().trim();
east = Integer.parseInt(token);
token = stk.nextToken().trim();
west = Integer.parseInt(token);
token = stk.nextToken().trim();
midwest = Integer.parseInt(token);
PieChart pi = new PieChart(north,south,east,west,midwest);
pi.setVisible(true);
pi.setSize(500, 500);
}
}
It was a stupid mistake...
ANSWER:
the method
Paint(Graphics g)
should be
paint(Graphics g)
did not realize that until i played with the code.

Related

Eclipse game window opening very small

Whenever I run my game, the game window opens up very small, like below, how can I fix this. I believe it is something to do with JFrame.setPreferredSize(new Dimension(x,y)); but I don't know where to implement this in the code for it to work.
This is what it shows:
enter image description here
Where do I implement the code? Like in the class, outside the class, or do I need to show my current code for someone to help me here?
This is my code:
public class RoadAppMain extends JFrame {
private static final int D_W = 1920; //Window dimension
private static final int D_H = 1280; //Window height
int grassWidth = 1920; //Width of grass
int vanishHeight = 768; // Height of vanishing point
int roadWidth = 900; //Width of the road
int rumbleLen = 800; //Length of each track stripe
double camDist = 0.8; //Camera distance
int N; //Size of each row or line
int playerPosX = 0; //Movement of player left and right
int playerPosY = 0; //Movement of player up and down
List<Line> lines = new ArrayList<RoadAppMain.Line>();
List<Integer> listValues = new ArrayList<Integer>();
DrawPanel drawPanel = new DrawPanel();
public RoadAppMain() {
for (int i = 0; i < 1600; i++) {
Line line = new Line();
line.z = i * rumbleLen;
int curveAngle = (int) (Math.random() * 15 + 1);
if (i > 20 && i < 70) {
line.curve = curveAngle;
}
else if (i > 100 && i < 150) {
line.curve = -curveAngle;
}
else if (i > 180 && i < 230) {
line.curve = curveAngle;
}
else if (i > 260 && i < 310) {
line.curve = -curveAngle;
}
else if (i > 340 && i < 390) {
line.curve = curveAngle;
}
else if (i > 400 && i < 420) {
}
lines.add(line);
}
N = lines.size();
//Handles action events by user
ActionListener listener = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
drawPanel.repaint();
}
};
Timer timer = new Timer(1, listener);
timer.start();
add(drawPanel);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
//Moves screen using arrow keys
private class DrawPanel extends JPanel {
public DrawPanel() {
String VK_LEFT = "VK_LEFT";
KeyStroke W = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW); //necessary
inputMap.put(W, VK_LEFT);
ActionMap actionMap = getActionMap(); //necessary
actionMap.put(VK_LEFT, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playerPosX -= 200;
drawPanel.repaint();
}
});
String VK_RIGHT = "VK_RIGHT";
KeyStroke WVK_RIGHT = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
inputMap.put(WVK_RIGHT, VK_RIGHT);
actionMap.put(VK_RIGHT, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playerPosX += 200;
drawPanel.repaint();
}
});
String VK_UP = "VK_UP";
KeyStroke WVK_UP = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
inputMap.put(WVK_UP, VK_UP);
actionMap.put(VK_UP, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playerPosY += 200;
drawPanel.repaint();
}
});
String VK_DOWN = "VK_DOWN";
KeyStroke WVK_DOWN = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
inputMap.put(WVK_DOWN, VK_DOWN);
actionMap.put(VK_DOWN, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playerPosY -= 200;
drawPanel.repaint();
}
});
}
//Drawing components feature
protected void paintComponent(Graphics g) {
drawValues(g);
g.setColor(Color.black);
g.fillRect(0, 0, 1920, 395);
}
}
private void drawValues(Graphics g) {
int startPos = playerPosY / rumbleLen;
double x = 0; //Initial X position of screen on road
double dx = 0; //Correlation between the angle of the road and player
double maxY = vanishHeight;
int camH = 1700 + (int) lines.get(startPos).y; //Height of the camera
//Starting position
for (int n = startPos; n < startPos + 300; n++) {
Line l = lines.get(n % N); //Position of line
l.project(playerPosX - (int) x, camH, playerPosY);
x += dx;
dx += l.curve;
if (l.Y > 0 && l.Y < maxY) {
maxY = l.Y;
Color grass = ((n / 2) % 2) == 0 ? new Color(21, 153, 71) : new Color(22, 102, 52); //Color for grass (first is for lighter, second for darker)
Color rumble = ((n / 2) % 2) == 0 ? new Color(255, 255, 255) : new Color(222, 4, 4); // Color for rumble (first is white, second is red)
Color road = new Color(54, 52, 52); // Color of road or asphalt
Color midel = ((n / 2) % 2) == 0 ? new Color(255, 255, 255) : new Color(54, 52, 52); //Color of hashed lines (first for white lines, second for gap)
Color car = new Color(104, 104, 104);
Color tire = new Color(0, 0, 0);
Color stripe = new Color(0, 0, 0);
Color light = new Color(253, 0, 0);
Color hood = new Color(0, 0, 0);
Color frame = new Color(0,0,255);
Line p = null;
if (n == 0) {
p = l;
} else {
p = lines.get((n - 1) % N);
}
draw(g, grass, 0, (int) p.Y, grassWidth, 0, (int) l.Y, grassWidth); //(Graphics g, Color c, int x1, int y1, int w1, int x2, int y2, int w2)
draw(g, rumble, (int) p.X, (int) p.Y, (int) (p.W * 2.03), (int) l.X, (int) l.Y, (int) (l.W * 2.03)); //Affects width of rumble
draw(g, road, (int) p.X, (int) p.Y, (int) (p.W * 1.8), (int) l.X, (int) l.Y, (int) (l.W * 1.8));
draw(g, midel, (int) p.X, (int) p.Y, (int) (p.W * 0.78), (int) l.X, (int) l.Y, (int) (l.W * 0.78)); //ADD HERE
draw(g, road, (int) p.X, (int) p.Y, (int) (p.W * 0.7), (int) l.X, (int) l.Y, (int) (l.W* 0.7)); //To cover the gap in between each midel. Must be after to allow it to colour over it
draw(g, car, 965, 927, 125, 965, 1005, 125);
draw(g, tire, 875, 1005, 35, 875, 1050, 35);
draw(g, tire, 1055, 1005, 35, 1055, 1050, 35);
draw(g, stripe, 1050, 965, 30, 870, 980, 30);
draw(g, stripe, 1050, 950, 30, 870, 965, 30);
draw(g, hood, 965, 880, 90, 965, 927, 125);
draw(g, light, 875, 950, 5, 875, 980, 5);
draw(g, light, 890, 950, 5, 890, 980, 5);
draw(g, light, 905, 950, 5, 905, 980, 5);
draw(g, light, 1025, 950, 5, 1025, 980, 5);
draw(g, light, 1040, 950, 5, 1040, 980, 5);
draw(g, light, 1055, 950, 5, 1055, 980, 5);
draw(g, frame, 965, 874, 86, 965, 880, 90);
draw(g, light, 965, 874, 35, 965, 880, 45);
}
}
}
void draw(Graphics g, Color c, int x1, int y1, int w1, int x2, int y2, int w2) {
Graphics g9d = g;
int[] x9Points = { x1 - w1, x2 - w2, x2 + w2, x1 + w1 };
int[] y9Points = { y1, y2, y2, y1 };
int n9Points = 4;
g9d.setColor(c);
g9d.fillPolygon(x9Points, y9Points, n9Points);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new RoadAppMain();
}
});
}
class Line {
double x, y, z;
double X, Y, W;
double scale, curve;
public Line() {
curve = x = y = z = 0;
}
void project(int camX, int camY, int camZ) {
scale = camDist / (z - camZ);
X = (1 + scale * (x - camX)) * grassWidth / 2;
Y = (1 - scale * (y - camY)) * vanishHeight / 2;
W = scale * roadWidth * grassWidth / 2;
}
}
}

My fractal isn't printing properly, when I use the right values, it doesn't print at all

The fractal is called Vicsek fractal .When I set midpoint's x and y values to = firstDot's x and y values / 3, i get the fractal, but my fractal is very small, and off to the side. However, when I set it to equal firstDot's values * 3/2, what is suppose to be, only the square prints, and not the fractal.
package fractals;
import java.awt.Color;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
/**
*
* #author Joshua
*/
public class SquarePanel extends JPanel {
static final int[] xPoints = new int[]{270, 270, 810, 810};//Square x coordiantes
static final int[] yPoints = new int[]{92, 632, 632, 92};//Square y coordinates
int firstDotx = 270 + (int) (Math.random() * ((810 - 270) + 1));
int firstDoty = 92 + (int) (Math.random() * ((632 - 92) + 1));
public final static int iterations = 100000;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black);
g2.drawPolygon(xPoints, yPoints, 4);
g2.drawRect(firstDotx, firstDoty, 0, 0);
for (int i = 0; i <= iterations; i++) {
int midpointX;
int midpointY;
int Vertex = (int) (Math.random() * 5 + 1);
switch (Vertex) {
case 1: //top left corner
g2.setColor(Color.blue);
midpointX = (firstDotx + 270) / 3;
midpointY = (firstDoty + 92) / 3;
g2.drawRect(midpointX, midpointY, 0, 0);
firstDotx = midpointX;
firstDoty = midpointY;
break;
case 2://bottom left
g2.setColor(Color.blue);
midpointX = (firstDotx + 270) / 3;
midpointY = (firstDoty + 632) / 3;
g2.drawRect(midpointX, midpointY, 0, 0);
firstDotx = midpointX;
firstDoty = midpointY;
break;
case 3://bottom right
g2.setColor(Color.blue);
midpointX = (firstDotx + 810) / 3;
midpointY = (firstDoty + 632) / 3;
g2.drawRect(midpointX, midpointY, 0, 0);
firstDotx = midpointX;
firstDoty = midpointY;
break;
case 4://bottom left
g2.setColor(Color.blue);
midpointX = (firstDotx + 810) / 3;
midpointY = (firstDoty + 92) / 3;
g2.drawRect(midpointX, midpointY, 0, 0);
firstDotx = midpointX;
firstDoty = midpointY;
break;
case 5:
g2.setColor(Color.red);
midpointX = (firstDotx + 540) / 3;
midpointY = (firstDoty + 384) / 3;
g2.drawRect(midpointX, midpointY, 0, 0);
firstDotx = midpointX;
firstDoty = midpointY;
break;
default:
break;
}
}
}
}
This is the class file for the Frame, im planning to add a GUI, with buttons, but I havn't gotten there yet.
package fractals;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
/**
*
* #author Joshua
*/
public class SqaureFrame {
public static void main(String[] args) {
JFrame Sframe = new JFrame("Vicsek Fractal");
Sframe.setSize(1080, 768);
Sframe.setLocation(300, 200);
Sframe.setDefaultCloseOperation(EXIT_ON_CLOSE);
SquarePanel Vicsek = new SquarePanel();
JButton Square = new JButton("Click for the Vicsek Fractal");
Sframe.add(Vicsek);
Sframe.setVisible(true);
}
}
Well thanks to everyone who looked at it, but I managed to solve it. I noticed that the size of my fractal was the same size as a quarter of the square, so I took the coordinates of each of the vertices in the square (the "+270" for example) and doubled them. My fractal now prints correctly.
For instance:
midpointY = (firstDoty + 92*2) / 3

Change Hue of Picture in Graphics

Ok so i need help changing the hue of this slider. I cant seem to figure it out. Please no #override. I need something that will run on Ready to Program. The hue will change back to normal when the slider is back at 0. I dont need to get too complex. Just a simple Hue slider will be great. Thanks!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.Applet;
import javax.swing.event.*;
import java.applet.*;
public class test extends Applet implements ActionListener, ChangeListener
{
//Widgets, Panels
JSlider slider;
Panel flow;
int colorr;
int colorg;
int colorb;
int stars;
//House Coordinates, initialized to 1. (Top Right and No Scaling)
public void init ()
{ //Set Up Input Fields for House Coordinates
resize (380, 240);
setBackground (new Color (102, 179, 255));
slider = new JSlider ();
slider.setValue (0);
slider.setBackground (new Color (102, 179, 255));
slider.setForeground (Color.white);
slider.setMajorTickSpacing (20);
slider.setMinorTickSpacing (5);
slider.setPaintTicks (true);
slider.addChangeListener (this);
//Set up layout, add widgets
setLayout (new BorderLayout ());
flow = new Panel (new FlowLayout ());
flow.add (slider);
add (flow, "South");
}
public void paint (Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
Color color1 = getBackground ();
Color color2 = color1.darker ();
int x = getWidth ();
int y = getHeight () - 30;
GradientPaint gp = new GradientPaint (
0, 0, color1,
0, y, color2);
g2d.setPaint (gp);
g2d.fillRect (0, 0, x, y);
stars (10, 10);
}
public void stars (int x, int y)
{
Graphics g = getGraphics ();
//sun
g.setColor (new Color (139, 166, 211));
g.fillOval (-200, 170, 1000, 400);
g.setColor (new Color (206, 75, 239));
g.fillOval (x, y, 10, 10); //First medium star
g.drawLine (x + 5, y, x + 5, 0);
g.drawLine (x, y + 5, 0, y + 5);
g.drawLine (x + 5, y + 10, x + 5, y + 20);
g.drawLine (x + 10, y + 5, x + 20, y + 5);
g.fillOval (x + 80, y + 30, 12, 12); //Middle medium star
g.drawLine (x + 86, y + 30, x + 86, y + 18);
g.drawLine (x + 80, y + 36, x + 68, y + 36);
g.drawLine (x + 92, y + 36, x + 104, y + 36);
g.drawLine (x + 86, y + 42, x + 86, y + 52);
colorr = (int) (Math.random () * 255) + 1;
colorg = (int) (Math.random () * 255) + 1;
colorb = (int) (Math.random () * 255) + 1;
int randomx = (int) (Math.random () * 300) + 10;
int randomy = (int) (Math.random () * 150) + 10;
stars = 50; //Change for more stars
int ax[] = new int [stars];
int ay[] = new int [stars];
for (int i = 0 ; i < stars ; i++)
{
g.setColor (new Color (colorr, colorg, colorb));
colorr = (int) (Math.random () * 255) + 1;
colorg = (int) (Math.random () * 255) + 1;
colorb = (int) (Math.random () * 255) + 1;
while ((randomx > 88 && randomx < 116) && (randomy < 65 && randomy > 15))
{
randomx = (int) (Math.random () * 300) + 10;
randomy = (int) (Math.random () * 150) + 10;
}
while ((randomx > 0 && randomx < 25) && (randomy > 5 && randomy < 35))
{
randomx = (int) (Math.random () * 300) + 10;
randomy = (int) (Math.random () * 150) + 10;
}
g.drawOval (randomx, randomy, 5, 5);
randomx = (int) (Math.random () * 300) + 10;
randomy = (int) (Math.random () * 150) + 10;
}
g.setColor (Color.white);
g.drawLine (320, 0, 315, 40);
g.drawLine (320, 0, 325, 40);
g.drawLine (320, 120, 315, 80);
g.drawLine (320, 120, 325, 80);
g.drawLine (260, 60, 300, 55);
g.drawLine (260, 60, 300, 65);
g.drawLine (380, 60, 340, 55);
g.drawLine (380, 60, 340, 65);
fillGradOval (280, 20, 80, 80, new Color (254, 238, 44), new Color (255, 251, 191), g);
g.setColor (new Color (255, 251, 191));
fillGradOval (300, 40, 40, 40, new Color (255, 251, 191), new Color (254, 238, 44), g);
}
public void fillGradOval (int X, int Y, int H2, int W2, Color c1, Color c2, Graphics g)
{
g.setColor (c1);
g.fillOval (X, Y, W2, H2);
Color Gradient = c1;
float red = (c2.getRed () - c1.getRed ()) / (W2 / 2);
float blue = (c2.getBlue () - c1.getBlue ()) / (W2 / 2);
float green = (c2.getGreen () - c1.getGreen ()) / (W2 / 2);
int scale = 1;
int r = c1.getRed ();
int gr = c1.getGreen ();
int b = c1.getBlue ();
while (W2 > 10)
{
r = (int) (r + red);
gr = (int) (gr + green);
b = (int) (b + blue);
Gradient = new Color (r, gr, b);
g.setColor (Gradient);
W2 = W2 - 2 * scale;
H2 = H2 - 2 * scale;
X = X + scale;
Y = Y + scale;
g.fillOval (X, Y, W2, H2);
}
}
public void actionPerformed (ActionEvent e)
{
}
public void stateChanged (ChangeEvent e)
{
JSlider source = (JSlider) e.getSource ();
if (!source.getValueIsAdjusting ())
{
}
}
}
I wasn't sure what 'color' you were referring to, so I made some guesses. Here is an hybrid application/applet (much easier for development and testing) that links the color of the bottom panel, as well as the bottom color of the gradient paint, to a hue as defined using the slider.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/* <applet code=HueSlider width=380 height=240></applet> */
public class HueSlider extends JApplet
{
public void init() {
add(new HueSliderGui());
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
HueSliderGui hsg = new HueSliderGui();
JOptionPane.showMessageDialog(null, hsg);
}
};
SwingUtilities.invokeLater(r);
}
}
class HueSliderGui extends JPanel implements ChangeListener {
//Widgets, Panels
JSlider slider;
JPanel flow;
int colorr;
int colorg;
int colorb;
Color bg = new Color (102, 179, 255);
int stars;
//House Coordinates, initialized to 1. (Top Right and No Scaling)
Dimension prefSize = new Dimension(380, 240);
HueSliderGui() {
initGui();
}
public void initGui()
{
//Set Up Input Fields for House Coordinates
// an applet size is set in HTML
//resize (380, 240);
setBackground (bg);
slider = new JSlider ();
slider.setValue (0);
slider.setBackground (new Color (102, 179, 255));
slider.setForeground (Color.white);
slider.setMajorTickSpacing (20);
slider.setMinorTickSpacing (5);
slider.setPaintTicks (true);
slider.addChangeListener (this);
//Set up layout, add widgets
setLayout (new BorderLayout ());
flow = new JPanel (new FlowLayout ());
flow.add (slider);
add (flow, "South");
validate();
}
#Override
public Dimension getPreferredSize() {
return prefSize;
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Color color1 = getBackground ();
Color color2 = color1.darker ();
int x = getWidth ();
int y = getHeight () - 30;
GradientPaint gp = new GradientPaint (
0, 0, color1,
0, y, flow.getBackground());
g2d.setPaint (gp);
g2d.fillRect (0, 0, x, y);
stars (10, 10, g2d);
}
public void stars (int x, int y, Graphics g)
{
// Graphics g = getGraphics (); we should never call getGraphics
//sun
g.setColor (new Color (139, 166, 211));
g.fillOval (-200, 170, 1000, 400);
g.setColor (new Color (206, 75, 239));
g.fillOval (x, y, 10, 10); //First medium star
g.drawLine (x + 5, y, x + 5, 0);
g.drawLine (x, y + 5, 0, y + 5);
g.drawLine (x + 5, y + 10, x + 5, y + 20);
g.drawLine (x + 10, y + 5, x + 20, y + 5);
g.fillOval (x + 80, y + 30, 12, 12); //Middle medium star
g.drawLine (x + 86, y + 30, x + 86, y + 18);
g.drawLine (x + 80, y + 36, x + 68, y + 36);
g.drawLine (x + 92, y + 36, x + 104, y + 36);
g.drawLine (x + 86, y + 42, x + 86, y + 52);
colorr = (int) (Math.random () * 255) + 1;
colorg = (int) (Math.random () * 255) + 1;
colorb = (int) (Math.random () * 255) + 1;
int randomx = (int) (Math.random () * 300) + 10;
int randomy = (int) (Math.random () * 150) + 10;
stars = 50; //Change for more stars
int ax[] = new int [stars];
int ay[] = new int [stars];
for (int i = 0 ; i < stars ; i++)
{
g.setColor (new Color (colorr, colorg, colorb));
colorr = (int) (Math.random () * 255) + 1;
colorg = (int) (Math.random () * 255) + 1;
colorb = (int) (Math.random () * 255) + 1;
while ((randomx > 88 && randomx < 116) && (randomy < 65 && randomy > 15))
{
randomx = (int) (Math.random () * 300) + 10;
randomy = (int) (Math.random () * 150) + 10;
}
while ((randomx > 0 && randomx < 25) && (randomy > 5 && randomy < 35))
{
randomx = (int) (Math.random () * 300) + 10;
randomy = (int) (Math.random () * 150) + 10;
}
g.drawOval (randomx, randomy, 5, 5);
randomx = (int) (Math.random () * 300) + 10;
randomy = (int) (Math.random () * 150) + 10;
}
g.setColor (Color.white);
g.drawLine (320, 0, 315, 40);
g.drawLine (320, 0, 325, 40);
g.drawLine (320, 120, 315, 80);
g.drawLine (320, 120, 325, 80);
g.drawLine (260, 60, 300, 55);
g.drawLine (260, 60, 300, 65);
g.drawLine (380, 60, 340, 55);
g.drawLine (380, 60, 340, 65);
fillGradOval (280, 20, 80, 80, new Color (254, 238, 44), new Color (255, 251, 191), g);
g.setColor (new Color (255, 251, 191));
fillGradOval (300, 40, 40, 40, new Color (255, 251, 191), new Color (254, 238, 44), g);
}
public void fillGradOval (int X, int Y, int H2, int W2, Color c1, Color c2, Graphics g)
{
g.setColor (c1);
g.fillOval (X, Y, W2, H2);
Color Gradient = c1;
float red = (c2.getRed () - c1.getRed ()) / (W2 / 2);
float blue = (c2.getBlue () - c1.getBlue ()) / (W2 / 2);
float green = (c2.getGreen () - c1.getGreen ()) / (W2 / 2);
int scale = 1;
int r = c1.getRed ();
int gr = c1.getGreen ();
int b = c1.getBlue ();
while (W2 > 10)
{
r = (int) (r + red);
gr = (int) (gr + green);
b = (int) (b + blue);
Gradient = new Color (r, gr, b);
g.setColor (Gradient);
W2 = W2 - 2 * scale;
H2 = H2 - 2 * scale;
X = X + scale;
Y = Y + scale;
g.fillOval (X, Y, W2, H2);
}
}
public void stateChanged (ChangeEvent e)
{
JSlider source = (JSlider) e.getSource ();
if (!source.getValueIsAdjusting ())
{
int i = source.getValue();
System.out.println(i);
float[] hsb = Color.RGBtoHSB(bg.getRed(),bg.getGreen(),bg.getBlue(),null);
int colorHue = Color.HSBtoRGB((float)i/100f, hsb[1], hsb[2]);
Color c = new Color(colorHue);
flow.setBackground(c);
this.repaint();
}
}
}

Get the corners of a rotating rectangle

I have a rectangle that rotates around it's middle and I have another rectangle that I want to connect to the upper right corner of the rotating rectangle. The problem is that I have no idea how to get the corner so that the second rectangle always will be stuck to that corner.
This is my sample code. Right now the second rectangle will be at the same place all the time which is not the result that I'm after.
package Test;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
class Test{
public static void main(String[] args){
new Test();
}
public Test(){
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new Graphic());
frame.setSize(1000,700);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
class Graphic extends JPanel{
private int x, y, windowW, windowH;
private double angle;
private Rectangle rect1, rect2;
private Path2D path;
private Timer timer;
private AffineTransform rotation;
public Graphic(){
windowW = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
windowH = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
path = new Path2D.Double();
rotation = new AffineTransform();
angle = 0;
x = windowW / 2;
y = windowH / 2;
timer = new Timer(100, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
angle += .1;
if(angle > 360) angle -= 360;
repaint();
}
});
timer.start();
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
rotation.setToTranslation(500, 200);
rotation.rotate(angle, 32, 32);
rect1 = new Rectangle(0, 0, 64, 64);
path = new Path2D.Double(rect1, rotation);
rect2 = new Rectangle(path.getBounds().x, path.getBounds().y, 10, 50);
g2d.fill(path);
g2d.fill(rect2);
}
}
Mathematical solution :)
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
rotation.setToTranslation(500, 200);
rotation.rotate(angle, 32, 32);
rect1 = new Rectangle(0, 0, 64, 64);
path = new Path2D.Double(rect1, rotation);
double r = 32.0 * Math.sqrt(2);
// (532, 232) - coordinates of rectangle center |
// you can change position of second rectangle by this V substraction (all you need to know is that the full circle corresponds to 2Pi)
int x2 = (int) Math.round(532 + r * Math.cos(angle - Math.PI / 4));
int y2 = (int) Math.round(232 + r * Math.sin(angle - Math.PI / 4));
rect2 = new Rectangle(x2, y2, 10, 50);
g2d.fill(path);
g2d.fill(rect2);
}
Of course, some constants should be class fields, not method variables.
I can't test this code to be sure but I believe it is the proper working code that you want
int hw = -width / 2;
int hh = -height / 2;
int cos = Math.cos( theta );
int sin = Math.sin( theta );
int x = hw * cos - hh * sin;
int y = hw * sin + hh * cos;
This will get you the top left corner based on the theta, rotation, of the square. To get the other corners you just use change the hw and hh values:
//top right corner
hw = width / 2
hh = -height / 2
//bottom right corner
hw = width / 2
hh = height / 2
//bottom left corer
hw = -width / 2
hh = height / 2
I hope this helps

Bar Chart in java

I want to change the height of each bar (for example 10 for red part and 20 for blue part). But when I increase the height value it will increase the chart from bottom whereas I want the change to top! Do you know what is wrong with it?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ChartPanel extends JPanel {
private double[] values;
private String[] names;
private String title;
public ChartPanel(double[] v, String[] n, String t) {
names = n;
values = v;
title = t;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (values == null || values.length == 0)
return;
double minValue = 0;
double maxValue = 0;
for (int i = 0; i < values.length; i++) {
if (minValue > values[i])
minValue = values[i];
if (maxValue < values[i])
maxValue = values[i];
}
Dimension d = getSize();
int clientWidth = d.width;
int clientHeight = d.height;
int barWidth = clientWidth / values.length;
Font titleFont = new Font("SansSerif", Font.BOLD, 20);
FontMetrics titleFontMetrics = g.getFontMetrics(titleFont);
Font labelFont = new Font("SansSerif", Font.PLAIN, 10);
FontMetrics labelFontMetrics = g.getFontMetrics(labelFont);
int titleWidth = titleFontMetrics.stringWidth(title);
int y = titleFontMetrics.getAscent();
int x = (clientWidth - titleWidth) / 2;
g.setFont(titleFont);
g.drawString(title, x, y);
int top = titleFontMetrics.getHeight();
int bottom = labelFontMetrics.getHeight();
if (maxValue == minValue)
return;
double scale = (clientHeight - top - bottom) / (maxValue - minValue);
y = clientHeight - labelFontMetrics.getDescent();
g.setFont(labelFont);
for (int i = 0; i < values.length; i++) {
int valueX = i * barWidth + 1;
int valueY = top;
int height = (int) (values[i] * scale);
if (values[i] >= 0)
valueY += (int) ((maxValue - values[i]) * scale);
else {
valueY += (int) (maxValue * scale);
height = -height;
}
g.setColor(Color.red);
g.fillRect(valueX, valueY, barWidth - 80, height);
g.setColor(Color.black);
g.drawRect(valueX, valueY, barWidth - 80, height);
g.setColor(Color.blue);
g.fillRect(valueX, valueY + 20, barWidth - 80, height-20 );
g.setColor(Color.black);
g.drawRect(valueX, valueY + 20, barWidth - 80, height-20 );
int labelWidth = labelFontMetrics.stringWidth(names[i]);
x = i * barWidth + (barWidth - labelWidth) / 2;
g.drawString(names[i], x, y);
}
}
public static void main(String[] argv) {
JFrame f = new JFrame();
f.setSize(400, 300);
double[] values = new double[3];
String[] names = new String[3];
values[0] = 1;
names[0] = "Item 1";
values[1] = 2;
names[1] = "Item 2";
values[2] = 4;
names[2] = "Item 3";
f.getContentPane().add(new ChartPanel(values, names, "title"));
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
f.addWindowListener(wndCloser);
f.setVisible(true);
}
}
Because Java's graphics uses the top left corner as the origin, when you add to the height it will increase down instead of up. Try changing this:
g.setColor(Color.red);
g.fillRect(valueX, valueY, barWidth - 80, height);
g.setColor(Color.black);
g.drawRect(valueX, valueY, barWidth - 80, height);
To this:
g.setColor(Color.red);
g.fillRect(valueX, valueY - 20, barWidth - 80, height);
g.setColor(Color.black);
g.drawRect(valueX, valueY - 20, barWidth - 80, height);
I tried this and it added to the red portion of the bar at the top.
Here is a shot of the original code:
And with the change:

Categories

Resources