Java custom control repaint causes incorrect (different) drawing - java

I have just started Java in school and I'm trying out custom controls and graphics. I'm currently working on a pattern lock and it started out perfectly fine, but all of a sudden it's drawing incorrectly. I did change some code, but as soon as I saw the error, I changed it right back (undo, ftw), but it still gives me the same error.
The problem is that when I repaint, the way my points are drawn, changes,- even though it isn't supposed to....
Here's a couple of images describing what I mean:
http://imgur.com/a/ObmFa
Hopefully this was clear enough, otherwise leave a comment instead of a minus point.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import javax.swing.JPanel;
public class Lock extends JPanel
{
class Line
{
//Properties
public Point start;
public Point end;
public float thickness;
public Color color = new Color(63, 152, 137);
public Color highlightColor = new Color(73, 162, 147);
public Color borderColor = Color.BLACK;
public Line()
{
}
public Line(Point start, Point end, float thickness)
{
this.start = start;
this.end = end;
this.thickness = thickness;
}
public Line(Point start, Point end, float thickness, Color color, Color borderColor, Color highlightColor)
{
this.start = start;
this.end = end;
this.thickness = thickness;
this.color = color;
this.borderColor = borderColor;
this.highlightColor = highlightColor;
}
public void Draw(Graphics2D g)
{
//Set the line thickness
g.setStroke(new BasicStroke(thickness));
//Border
g.setColor(borderColor);
g.drawLine(start.x, start.y, end.x, end.y);
//Highlight
g.setStroke(new BasicStroke(thickness - 1));
g.setColor(highlightColor);
g.drawLine(start.x, start.y, end.x, end.y);
//Base color
g.setStroke(new BasicStroke(thickness - 2));
g.setColor(color);
g.drawLine(start.x, start.y, end.x, end.y);
//Reset the line thickness
g.setStroke(new BasicStroke(Lock.this.drawnLineThickness));
}
}
//Properties
public Dimension gridSize = new Dimension(3, 3);
public Dimension pointSize = new Dimension(50, 50);
public boolean stealth = false;
public Color backgroundColor = new Color(255, 0, 0, 0); //Transparent
public float drawingLineThickness = 1;
public float drawnLineThickness = 12;
public Color drawingLineColor = new Color(0, 128, 128); //Teal
public Color drawnLineColor = new Color(63, 152, 137); //Teal like color
public Color drawnLineBorderColor = Color.BLACK;
public Color drawnLineHighlightColor = new Color(73, 162, 147); //Teal like color
private static final long serialVersionUID = 1L;
private ArrayList<Rectangle> Points = new ArrayList<Rectangle>();
private ArrayList<Line> Lines = new ArrayList<Line>();
private boolean Dragging, Done;
private Point LineStartPoint, LineEndPoint;
private Rectangle StartPoint;
class MouseEventHandler extends MouseAdapter
{
#Override
public void mousePressed(MouseEvent e)
{
if(!Done)
{
for(Rectangle Point : Points)
{
if(IsInCircle(new Point(e.getX(), e.getY()), Point))
{
StartPoint = Point;
LineStartPoint = new Point(StartPoint.x + (StartPoint.width / 2), StartPoint.y + (StartPoint.height / 2));
}
}
}
}
#Override
public void mouseDragged(MouseEvent e)
{
Dragging = true;
LineEndPoint = new Point(e.getX(), e.getY());
for(Rectangle Point : Points)
{
//If the mouse is within one of the points and it's not the start point
if(IsInCircle(new Point(e.getX(), e.getY()), Point) && Point != StartPoint)
{
LineEndPoint = new Point(Point.x + (Point.width / 2), Point.y + (Point.height / 2));
Line LineToAdd = new Line(LineStartPoint, LineEndPoint, drawnLineThickness, drawnLineColor, drawnLineBorderColor, drawnLineHighlightColor);
if(CheckLines(LineToAdd))
{
Lines.add(LineToAdd);
LineStartPoint = LineEndPoint;
}
}
}
Lock.this.repaint();
}
#Override
public void mouseReleased(MouseEvent e)
{
//If the Lines array size is more than 0, that means that a line has been created and the control should now be "locked"
if(Lines.size() > 0)
{
Done = true; //We are now done and should not be able to add more lines.
}
//We are no longer dragging, so we set this to false, so that we won't be drawing a line on the control after we are done
Dragging = false;
//Update controls graphics
Lock.this.repaint();
}
}
public Lock()
{
CreateGrid();
addMouseListener(new MouseEventHandler());
addMouseMotionListener(new MouseEventHandler());
}
public void paintComponent(Graphics oldG)
{
super.paintComponent(oldG);
//Create a Graphics2D object as this class has more options
Graphics2D g = (Graphics2D) oldG;
//Rendering hints: https://docs.oracle.com/javase/tutorial/2d/advanced/quality.html
//Change render quality to be prettier
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
//Set the controls background color
g.setColor(backgroundColor);
g.fillRect(0, 0, getWidth(), getHeight());
if(!stealth)
{
if(Dragging)
{
g.setStroke(new BasicStroke(3));
g.setColor(new Color(0, 128, 128));
g.drawLine(LineStartPoint.x, LineStartPoint.y, LineEndPoint.x, LineEndPoint.y);
}
for(Line Line : Lines)
{
Line.Draw(g);
}
}
for(Rectangle Point : Points)
{
//Outer ring (black)
GradientPaint Black = new GradientPaint(Point.x, Point.y, new Color(24, 25, 24), Point.width, Point.height, new Color(14, 15, 14));
g.setPaint(Black);
g.fill(new Ellipse2D.Double(Point.x, Point.y, Point.width, Point.height));
//Outer ring highlight
g.setColor(new Color(255, 255, 255, 20));
g.draw(new Ellipse2D.Double(Point.x + 1, Point.y + 1, Point.width - 3, Point.height - 3));
//Inner ring (teal)
GradientPaint Teal = new GradientPaint(Point.x + (Point.width / 4) - 1, Point.y + (Point.height / 4) - 1, new Color(63, 152, 137), Point.width / 2 + 3, Point.height / 2 + 3, new Color(0, 128, 128));
g.setPaint(Teal);
g.fill(new Ellipse2D.Double(Point.x + (Point.width / 4) - 1, Point.y + (Point.height / 4) - 1, Point.width / 2 + 3, Point.height / 2 + 3));
//Inner ring highlight
g.setColor(new Color(0, 0, 0));
g.draw(new Ellipse2D.Double(Point.x + (Point.width / 4) - 1, Point.y + (Point.height / 4) - 1, Point.width / 2 + 3, Point.height / 2 + 3));
g.setColor(new Color(255, 255, 255, 30));
g.draw(new Ellipse2D.Double(Point.x + (Point.width / 4) - 2, Point.y + (Point.height / 4) - 2, Point.width / 2 + 4, Point.height / 2 + 4));
}
}
//Method is used to check whether a point is inside a rectangle/circle
private boolean IsInCircle(Point MouseLocation, Rectangle Rectangle)
{
boolean Result;
//Get center of rectangle/circle
Point CenterPoint = new Point(Rectangle.x + (Rectangle.width / 2), Rectangle.y + (Rectangle.height / 2));
//Get distance from centerpoint to mouselocation
int DistanceX = Math.abs(CenterPoint.x - MouseLocation.x);
int DistanceY = Math.abs(CenterPoint.y - MouseLocation.y);
//The distance squared
int DistanceSquared = (int) Math.sqrt(DistanceX * DistanceX + DistanceY * DistanceY);
//The radious
int Radius = Rectangle.width / 2;
//If the radious is more or equal to the distance squared, the point is inside the circle
Result = Radius >= DistanceSquared;
return Result;
}
//Method is used to check whether a line has previously been drawn to a specific point
private boolean CheckLines(Line Line)
{
boolean Result = true;
for(Line _Line : Lines)
{
//If a point has previously been drawn to, return false to not make it possible to draw another line to that point
if(_Line.end.getX() == Line.end.getX() && _Line.end.getY() == Line.end.getY() || _Line.start.getX() == Line.start.getX() && _Line.start.getY() == Line.start.getY())
{
Result = false;
}
}
//Same idea as above
if(Lines.contains(Line))
{
Result = false;
}
return Result;
}
//Method is used to generate a grid of points
private void CreateGrid()
{
int X = 0, Y = 0, ControlHeight = 0;
for(int i = 0; i < gridSize.width; i++)
{
for(int ii = 0; ii < gridSize.height; ii++)
{
Points.add(new Rectangle(X, Y, pointSize.width, pointSize.height));
Y += pointSize.height * 2;
ControlHeight = Y;
if(ii == gridSize.height - 1)
{
Y = 0;
}
}
X += pointSize.width * 2;
}
this.setMinimumSize(new Dimension(X - pointSize.width + 1, ControlHeight - pointSize.height + 1));
this.setMaximumSize(new Dimension(X - pointSize.width + 1, ControlHeight - pointSize.height + 1));
this.setSize(new Dimension(X - pointSize.width + 1, ControlHeight - pointSize.height + 1));
}
//Method is used to get the current pattern code as a string
public String GetPattern()
{
String Result = "";
for(Line Line : Lines)
{
Result += Line.start.toString() + ";" + Line.end.toString() + ": \n";
}
return Result;
}
//Method is used to clear the current pattern
public void ClearPattern()
{
//Clear the lines
Lines.clear();
//Reset the *
Done = false;
//Repaint the control to show that there no longer are any lines.
this.repaint();
}
}

I found the problem....
This line of code was the problem. The BasicStroke value was not the orignal value I had entered (c+p), but something close to the name.
//Reset the line thickness
g.setStroke(new BasicStroke(Lock.this.drawnLineThickness));
I fixed it by correcting the code to the original:
//Reset the line thickness
g.setStroke(new BasicStroke(Lock.this.drawingLineThickness));

Related

Move game screen diagonally using arrow keys

I'm creating a car game where it creates a 3D pseudo effect by moving the screen backwards and the car itself just stays still on the map, using the arrow keys. It only takes in one input at a time, meaning you have to let go of an arrow key first. I have some code that I've got to show what I'm aiming for the screen to do as well, as the screen only moves forwards, backwards, left, and right.
Example of what I want the screen to do:
public class Main extends JFrame {
private static final long serialVersionUID = 7722803326073073681L;
private boolean left = false;
private boolean up = false;
private boolean down = false;
private boolean right = false;
public JLabel lbl = new JLabel ("mn");
public Main() {
// Just setting up the window and objects
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
lbl.setBounds(100, 100, 20, 20);
add(lbl);
setLocationRelativeTo(null);
// Key listener, will not move the JLabel, just set where to
addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) left = false;
if (e.getKeyCode() == KeyEvent.VK_RIGHT) right = false;
if (e.getKeyCode() == KeyEvent.VK_UP) up = false;
if (e.getKeyCode() == KeyEvent.VK_DOWN) down = false;
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) left = true;
if (e.getKeyCode() == KeyEvent.VK_RIGHT) right = true;
if (e.getKeyCode() == KeyEvent.VK_UP) up = true;
if (e.getKeyCode() == KeyEvent.VK_DOWN) down = true;
}
});
// This thread will read the 4 variables left/right/up/down at every 30 milliseconds
// It will check the combination of keys (left and up, right and down, just left, just up...)
// And move the label 3 pixels
new Thread(new Runnable() {
#Override
public void run() {
try {
while (true) {
if (left && up) {
lbl.setBounds(lbl.getX() - 10, lbl.getY() - 10, 20, 20);
} else if (left && down) {
lbl.setBounds(lbl.getX() - 10, lbl.getY() + 10, 20, 20);
} else if (right && up) {
lbl.setBounds(lbl.getX() + 10, lbl.getY() - 10, 20, 20);
} else if (right && down) {
lbl.setBounds(lbl.getX() + 10, lbl.getY() + 10, 20, 20);
} else if (left) {
lbl.setBounds(lbl.getX() - 10, lbl.getY(), 20, 20);
} else if (up) {
lbl.setBounds(lbl.getX(), lbl.getY() - 10, 20, 20);
} else if (right) {
lbl.setBounds(lbl.getX() + 10, lbl.getY(), 20, 20);
} else if (down) {
lbl.setBounds(lbl.getX(), lbl.getY() + 10, 20, 20);
}
Thread.sleep(30);
}
} catch (Exception ex) {
ex.printStackTrace();
System.exit(0);
}
}
}).start();
}
public static void main(String[] args) {
new Main();
}
}
However, since the code above only moves the letters, I'm having a lot of difficulty in implementing it in the game as well. This is what I'm currently using to move the screen. (If I were to delete this method, nothing would appear).
What is currently happening:
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 - THIS IS THE PART IM TALKING ABOUT
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;
}
}
}
How could I implement that movement into my game as well?

Loop for 256*256*256 colors such that colors are gradually changing and similar shades don't repeat in later iterations of loop?

When you use following loop to generate all the possible colors.
for (int red = 0; red < 256; red++) {
for (int green = 0; green < 256; green++) {
for (int blue = 0; blue < 256; blue++) {
}
}
}
It generates something like this
I want a loop such that color is gradually changing (i.e. gradient must not repeat. For instance all the possible shades of green are together, then all the possible shades of blue and so on) and all the possible colors are covered in the loop.
This is part of a "color blending" algorithm I've been using for awhile. It basically takes a series of colors and series of normalised points and calculates the "blending" between those colors/points automatically
So, at the heart of the solution, we have the colors, from black to fully "coloured" (ie green/blue/red)
private Color[] colors = new Color[]{
new Color(0, 0, 0), new Color(0, 255, 0), // Green
new Color(0, 0, 0), new Color(0, 0, 255), // Blue
new Color(0, 0, 0), new Color(255, 0, 0), // Red
};
We then have the fraction of the area we want those colors to cover, note, there is a point for each color change, the algorithm then blends the color from the start to end point automatically.
private float[] fractions = new float[]{
0f, 0.33f,
0.34f, 0.66f,
0.67f,1f};
The example simply then generates a number of bands (100 in this case) to "fake" the blending effect
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.text.NumberFormat;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ColorFade {
public static void main(String[] args) {
new ColorFade();
}
public ColorFade() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ColorFadePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ColorFadePane extends JPanel {
private float[] fractions = new float[]{
0f, 0.33f,
0.34f, 0.66f,
0.67f,1f};
private Color[] colors = new Color[]{
new Color(0, 0, 0), new Color(0, 255, 0),
new Color(0, 0, 0), new Color(0, 0, 255),
new Color(0, 0, 0), new Color(255, 0, 0),
};
public ColorFadePane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 100);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int width = getWidth();
int height = getHeight();
int bandWidth = width / 100;
for (int index = 0; index < 100; index++) {
float progress = (float) index / (float) 100;
Color color = blendColors(fractions, colors, progress);
int x = bandWidth * index;
int y = 0;
g2d.setColor(color);
g2d.fillRect(x, y, bandWidth, height);
}
g2d.dispose();
}
}
public static Color blendColors(float[] fractions, Color[] colors, float progress) {
Color color = null;
if (fractions != null) {
if (colors != null) {
if (fractions.length == colors.length) {
int[] indicies = getFractionIndicies(fractions, progress);
float[] range = new float[]{fractions[indicies[0]], fractions[indicies[1]]};
Color[] colorRange = new Color[]{colors[indicies[0]], colors[indicies[1]]};
float max = range[1] - range[0];
float value = progress - range[0];
float weight = value / max;
color = blend(colorRange[0], colorRange[1], 1f - weight);
} else {
throw new IllegalArgumentException("Fractions and colours must have equal number of elements");
}
} else {
throw new IllegalArgumentException("Colours can't be null");
}
} else {
throw new IllegalArgumentException("Fractions can't be null");
}
return color;
}
public static int[] getFractionIndicies(float[] fractions, float progress) {
int[] range = new int[2];
int startPoint = 0;
while (startPoint < fractions.length && fractions[startPoint] <= progress) {
startPoint++;
}
if (startPoint >= fractions.length) {
startPoint = fractions.length - 1;
}
range[0] = startPoint - 1;
range[1] = startPoint;
return range;
}
public static Color blend(Color color1, Color color2, double ratio) {
float r = (float) ratio;
float ir = (float) 1.0 - r;
float rgb1[] = new float[3];
float rgb2[] = new float[3];
color1.getColorComponents(rgb1);
color2.getColorComponents(rgb2);
float red = rgb1[0] * r + rgb2[0] * ir;
float green = rgb1[1] * r + rgb2[1] * ir;
float blue = rgb1[2] * r + rgb2[2] * ir;
if (red < 0) {
red = 0;
} else if (red > 255) {
red = 255;
}
if (green < 0) {
green = 0;
} else if (green > 255) {
green = 255;
}
if (blue < 0) {
blue = 0;
} else if (blue > 255) {
blue = 255;
}
Color color = null;
try {
color = new Color(red, green, blue);
} catch (IllegalArgumentException exp) {
NumberFormat nf = NumberFormat.getNumberInstance();
System.out.println(nf.format(red) + "; " + nf.format(green) + "; " + nf.format(blue));
exp.printStackTrace();
}
return color;
}
}
LinearGradientPaint
Now, if you want to be really boring, you could just use a LinearGradientPaint instead...
public class ColorFadePane extends JPanel {
private float[] fractions = new float[]{
0f, 0.33f,
0.34f, 0.66f,
0.67f, 1f};
private Color[] colors = new Color[]{
new Color(0, 0, 0), new Color(0, 255, 0),
new Color(0, 0, 0), new Color(0, 0, 255),
new Color(0, 0, 0), new Color(255, 0, 0),};
public ColorFadePane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 100);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int width = getWidth();
int height = getHeight();
LinearGradientPaint lgp = new LinearGradientPaint(new Point(0, 0), new Point(width, 0), fractions, colors);
g2d.setPaint(lgp);
g2d.fillRect(0, 0, width, height);
g2d.dispose();
}
}
But I need to generate the result as a image/file
Okay, fine, so, create a BufferedImage and paint to it instead and save it using ImageIO.write
If you really want to show a total of 16 million colors, then you have to give up some of your criteria. You can't have all the shades of red then all the shades of green then all the shades of blue because that doesn't explain the mixing of the colors. All the shades of red and green mixed together -- is that all the shades of red or all the shades of green. Expecially because now you're going to add some blue to the mix.
You also said you want it gradually shifting, so what you could do is (in metacode):
for (int red = 0; red < 256; ++red) {
bool redIsEven = (red % 2) == 0;
int greenStart = redIsEven ? 0 : 255;
int greenEnd = redIsEven ? 256 : -1;
int greenDirection = redIsEven ? 1 : -1;
for (int green = greenStart; green != greenEnd; green += greenDirection) {
... similar code for blue, but based on green, not red
}
}
That is... you'll do red = 0 and green will go from 0 to 255. For green = 0, blue also goes 0...255, but when it's 1, it goes backwards, so it's flowing evenly. Then green counts downwards, then upwards, then downwards...
So you get a smooth flow with none of the 16 million choices repeated.
Is that what you're trying to do?

Java Swing Line Graph

I'm attempting to draw a line graph based on data held in array. I have managed to get the X and Y axis drawn. However when I draw the line with the data onto the graph it does not line up with the X and Y axis values. I am unsure of how this can be fixed. I have shown the code below:
public void drawLineG(Graphics g, int yCoords[]) {
String maxY = Integer.toString(getMax(yCoords));
String minY = Integer.toString(getMin(yCoords));
String maxX = Double.toString((xInterval * yCoords.length) - xInterval);
String minX = Double.toString(xStart);
g.setColor(Color.BLUE);
int height = (getHeight() / 2);
int x = 200; // start x point
// previous coord positions.
int prevX = x;
int prevY = yCoords[0];
g.setColor(Color.BLACK);
g.drawLine(prevX, getHeight() / 2, 500, getHeight() / 2);
g.drawLine(prevX, 200, 200, getHeight() / 2);
g.setColor(Color.BLUE);
g.drawString(minY, 190, (getHeight() / 2));
g.drawString(maxY, 180, (getHeight() / 2) - 255);
g.drawString(yLabel, 140, (getHeight() / 2) - 100);
g.drawString(minX, 192, (getHeight() / 2) + 20);
g.drawString(maxX, 500, (getHeight() / 2) + 20);
g.drawString(xLabel, 350, (getHeight() / 2) + 50);
for (int y : yCoords) {
g.setColor(Color.RED);
g.drawLine(prevX, height - prevY, x, height - y);
prevX = x;
prevY = y;
// add an increment to the X pos.
x = x + 50;
}
}
The array of data I have been testing contains the values: 0, 3, 4, 7, 5, 10, 3
However when this is plotted on the graph it doesn't line up with the values on the x and y axis.
Current: https://i.stack.imgur.com/Ju8BQ.jpg
What I am trying to achieve: https://i.stack.imgur.com/n9Aio.jpg
Any help?
Thanks
Your problem is your scale, you're trying to draw your yCoords as they're given, (3, 10 and so on) but they should be like: 30, 100 to fit the window's scale (Window = your program window).
For example in my code below, each "square" or each "unit" are of 30 x 30 pixels each, so I must convert yCoord = 3 to it's equivalent which would be 3 * 30 = 90 but as the axis is below starting at 400 I must substract it so I get the coord from the axis or from the bottom of the window to the real yCoord which would be 400 - 90 = 310, now this is my real point that I must paint.
However the painting should be done in the paintComponent method.
For my example I didn't draw the Strings for 0, 10, 0.0, 90.0 but you can do it later if you wish
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GraphSample {
private JFrame frame;
public static void main(String[] args) {
SwingUtilities.invokeLater(new GraphSample()::createAndShowGui);
}
private void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
GraphDrawer drawer = new GraphDrawer(new int[] {0, 3, 4, 7, 5, 10, 3});
frame.add(drawer);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#SuppressWarnings("serial")
class GraphDrawer extends JPanel {
private int[] yCoords;
private int startX = 100;
private int startY = 100;
private int endX = 400;
private int endY = 400;
private int unitX = (endX - startX) / 10;
private int unitY = (endY - startY) / 10;
private int prevX = startX;
private int prevY = endY;
public GraphDrawer(int[] yCoords) {
this.yCoords = yCoords;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
//We draw in the following 2 loops the grid so it's visible what I explained before about each "unit"
g2d.setColor(Color.BLUE);
for (int i = startX; i <= endX; i += unitX) {
g2d.drawLine(i, startY, i, endY);
}
for (int i = startY; i <= endY; i += unitY) {
g2d.drawLine(startX, i, endX, i);
}
//We draw the axis here instead of before because otherwise they would become blue colored.
g2d.setColor(Color.BLACK);
g2d.drawLine(startX, startY, startX, endY);
g2d.drawLine(startX, endY, endX, endY);
//We draw each of our coords in red color
g2d.setColor(Color.RED);
for (int y : yCoords) {
g2d.drawLine(prevX, prevY, prevX += unitX, prevY = endY - (y * unitY));
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(endX + 100, endY + 100);
}
}
}
I hope it's clear what the error was.
This is a sample of what the output looks like with a 10 x 10 grid

Java Draw Arc Between 2 Points

I'm having trouble drawing the smallest arc described by 3 points: the arc center, an "anchored" end point, and a second point that gives the other end of the arc by determining a radius. I used the law of cosines to determine the length of the arc and tried using atan for the starting degree, but the starting position for the arc is off.
I managed to get the arc to lock onto the anchor point (x1,y1) when it's in Quadrant 2, but that will only work when it is in Quadrant 2.
Solutions I can see all have a bunch of if-statements to determine the location of the 2 points relative to each other, but I'm curious if I'm overlooking something simple. Any help would be greatly appreciated.
SSCCE:
import javax.swing.JComponent;
import javax.swing.JFrame;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.*;
import java.awt.*;
import java.util.*;
class Canvas extends JComponent {
float circleX, circleY, x1, y1, x2, y2, dx, dy, dx2, dy2, radius, radius2;
Random random = new Random();
public Canvas() {
//Setup.
x1 = random.nextInt(250);
y1 = random.nextInt(250);
//Cant have x2 == circleX
while (x1 == 150 || y1 == 150)
{
x1 = random.nextInt(250);
y1 = random.nextInt(250);
}
circleX = 150; //circle center is always dead center.
circleY = 150;
//Radius between the 2 points must be equal.
dx = Math.abs(circleX-x1);
dy = Math.abs(circleY-y1);
//c^2 = a^2 + b^2 to solve for the radius
radius = (float) Math.sqrt((float)Math.pow(dx, 2) + (float)Math.pow(dy, 2));
//2nd random point
x2 = random.nextInt(250);
y2 = random.nextInt(250);
//I need to push it out to radius length, because the radius is equal for both points.
dx2 = Math.abs(circleX-x2);
dy2 = Math.abs(circleY-y2);
radius2 = (float) Math.sqrt((float)Math.pow(dx2, 2) + (float)Math.pow(dy2, 2));
dx2 *= radius/radius2;
dy2 *= radius/radius2;
y2 = circleY+dy2;
x2 = circleX+dx2;
//Radius now equal for both points.
}
public void paintComponent(Graphics g2) {
Graphics2D g = (Graphics2D) g2;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_BEVEL));
Arc2D.Float centerPoint = new Arc2D.Float(150-2,150-2,4,4, 0, 360, Arc2D.OPEN);
Arc2D.Float point1 = new Arc2D.Float(x1-2, y1-2, 4, 4, 0, 360, Arc2D.OPEN);
Arc2D.Float point2 = new Arc2D.Float(x2-2, y2-2, 4, 4, 0, 360, Arc2D.OPEN);
//3 points drawn in black
g.setColor(Color.BLACK);
g.draw(centerPoint);
g.draw(point1);
g.draw(point2);
float start = 0;
float distance;
//Form a right triangle to find the length of the hypotenuse.
distance = (float) Math.sqrt(Math.pow(Math.abs(x2-x1),2) + Math.pow(Math.abs(y2-y1), 2));
//Law of cosines to determine the internal angle between the 2 points.
distance = (float) (Math.acos(((radius*radius) + (radius*radius) - (distance*distance)) / (2*radius*radius)) * 180/Math.PI);
float deltaY = circleY - y1;
float deltaX = circleX - x1;
float deltaY2 = circleY - y2;
float deltaX2 = circleX - x2;
float angleInDegrees = (float) ((float) Math.atan((float) (deltaY / deltaX)) * 180 / Math.PI);
float angleInDegrees2 = (float) ((float) Math.atan((float) (deltaY2 / deltaX2)) * 180 / Math.PI);
start = angleInDegrees;
//Q2 works.
if (x1 < circleX)
{
if (y1 < circleY)
{
start*=-1;
start+=180;
} else if (y2 > circleX) {
start+=180;
start+=distance;
}
}
//System.out.println("Start: " + start);
//Arc drawn in blue
g.setColor(Color.BLUE);
Arc2D.Float arc = new Arc2D.Float(circleX-radius, //Center x
circleY-radius, //Center y Rotates around this point.
radius*2,
radius*2,
start, //start degree
distance, //distance to travel
Arc2D.OPEN); //Type of arc.
g.draw(arc);
}
}
public class Angle implements MouseListener {
Canvas view;
JFrame window;
public Angle() {
window = new JFrame();
view = new Canvas();
view.addMouseListener(this);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 400, 400);
window.getContentPane().add(view);
window.setVisible(true);
}
public static void main(String[] a) {
new Angle();
}
#Override
public void mouseClicked(MouseEvent arg0) {
window.getContentPane().remove(view);
view = new Canvas();
window.getContentPane().add(view);
view.addMouseListener(this);
view.revalidate();
view.repaint();
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
Perhaps this will help. It tests with click and drag to set the two points rather than random numbers. It's considerably simpler than what you were attempting and other solutions posted so far.
Notes:
Math.atan2() is a friend in problems like this.
Little helper functions make it easier to reason about your code.
It's best practice to use instance variables for independent values only and compute the dependent values in local variables.
My code fixes some Swing usage problems like calling Swing functions from the main thread.
Code follows:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
class TestCanvas extends JComponent {
float x0 = 150f, y0 = 150f; // Arc center. Subscript 0 used for center throughout.
float xa = 200f, ya = 150f; // Arc anchor point. Subscript a for anchor.
float xd = 150f, yd = 50f; // Point determining arc angle. Subscript d for determiner.
// Return the distance from any point to the arc center.
float dist0(float x, float y) {
return (float)Math.sqrt(sqr(x - x0) + sqr(y - y0));
}
// Return polar angle of any point relative to arc center.
float angle0(float x, float y) {
return (float)Math.toDegrees(Math.atan2(y0 - y, x - x0));
}
#Override
protected void paintComponent(Graphics g0) {
Graphics2D g = (Graphics2D) g0;
// Can always draw the center point.
dot(g, x0, y0);
// Get radii of anchor and det point.
float ra = dist0(xa, ya);
float rd = dist0(xd, yd);
// If either is zero there's nothing else to draw.
if (ra == 0 || rd == 0) { return; }
// Get the angles from center to points.
float aa = angle0(xa, ya);
float ad = angle0(xd, yd); // (xb, yb) would work fine, too.
// Draw the arc and other dots.
g.draw(new Arc2D.Float(x0 - ra, y0 - ra, // box upper left
2 * ra, 2 * ra, // box width and height
aa, angleDiff(aa, ad), // angle start, extent
Arc2D.OPEN));
dot(g, xa, ya);
// Use similar triangles to get the second dot location.
float xb = x0 + (xd - x0) * ra / rd;
float yb = y0 + (yd - y0) * ra / rd;
dot(g, xb, yb);
}
// Some helper functions.
// Draw a small dot with the current color.
static void dot(Graphics2D g, float x, float y) {
final int rad = 2;
g.fill(new Ellipse2D.Float(x - rad, y - rad, 2 * rad, 2 * rad));
}
// Return the square of a float.
static float sqr(float x) { return x * x; }
// Find the angular difference between a and b, -180 <= diff < 180.
static float angleDiff(float a, float b) {
float d = b - a;
while (d >= 180f) { d -= 360f; }
while (d < -180f) { d += 360f; }
return d;
}
// Construct a test canvas with mouse handling.
TestCanvas() {
addMouseListener(mouseListener);
addMouseMotionListener(mouseListener);
}
// Listener changes arc parameters with click and drag.
MouseInputAdapter mouseListener = new MouseInputAdapter() {
boolean mouseDown = false; // Is left mouse button down?
#Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
mouseDown = true;
xa = xd = e.getX();
ya = yd = e.getY();
repaint();
}
}
#Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
mouseDown = false;
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (mouseDown) {
xd = e.getX();
yd = e.getY();
repaint();
}
}
};
}
public class Test extends JFrame {
public Test() {
setSize(400, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new TestCanvas());
}
public static void main(String[] args) {
// Swing code must run in the UI thread, so
// must invoke setVisible rather than just calling it.
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test().setVisible(true);
}
});
}
}
package curve;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
public class Main
{
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
PointF pFrom = new PointF(-10f, 30.0f);
PointF pTo = new PointF(-100f, 0.0f);
List<PointF> points = generateCurve(pFrom, pTo, 100f, 7f, true, true);
System.out.println(points);
// Calculate the bounds of the curve
Rectangle2D.Float bounds = new Rectangle2D.Float(points.get(0).x, points.get(0).y, 0, 0);
for (int i = 1; i < points.size(); ++i) {
bounds.add(points.get(i).x, points.get(i).y);
}
bounds.add(pFrom.x, pFrom.y);
bounds.add(pTo.x, pTo.y);
BufferedImage img = new BufferedImage((int) (bounds.width - bounds.x + 50), (int) (bounds.height - bounds.y + 50), BufferedImage.TYPE_4BYTE_ABGR_PRE);
Graphics2D g = img.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.translate(25.0f - bounds.getX(), 25.0f - bounds.getY());
g.setStroke(new BasicStroke(1.0f));
g.setColor(Color.DARK_GRAY);
g.drawLine(-1000, 0, 1000, 0);
g.drawLine(0, -1000, 0, 1000);
g.setColor(Color.RED);
for (int i = 0; i < points.size(); ++i) {
if (i > 0) {
Line2D.Float f = new Line2D.Float(points.get(i - 1).x, points.get(i - 1).y, points.get(i).x, points.get(i).y);
System.out.println("Dist : " + f.getP1().distance(f.getP2()));
// g.draw(f);
}
g.fill(new Ellipse2D.Float(points.get(i).x - 0.8f, points.get(i).y - 0.8f, 1.6f, 1.6f));
}
g.setColor(Color.BLUE);
g.fill(new Ellipse2D.Float(pFrom.x - 1, pFrom.y - 1, 3, 3));
g.fill(new Ellipse2D.Float(pTo.x - 1, pTo.y - 1, 3, 3));
g.dispose();
ImageIO.write(img, "PNG", new File("result.png"));
}
static class PointF
{
public float x, y;
public PointF(float x, float y)
{
this.x = x;
this.y = y;
}
#Override
public String toString()
{
return "(" + x + "," + y + ")";
}
}
private static List<PointF> generateCurve(PointF pFrom, PointF pTo, float pRadius, float pMinDistance, boolean shortest, boolean side)
{
List<PointF> pOutPut = new ArrayList<PointF>();
// Calculate the middle of the two given points.
PointF mPoint = new PointF(pFrom.x + pTo.x, pFrom.y + pTo.y);
mPoint.x /= 2.0f;
mPoint.y /= 2.0f;
System.out.println("Middle Between From and To = " + mPoint);
// Calculate the distance between the two points
float xDiff = pTo.x - pFrom.x;
float yDiff = pTo.y - pFrom.y;
float distance = (float) Math.sqrt(xDiff * xDiff + yDiff * yDiff);
System.out.println("Distance between From and To = " + distance);
if (pRadius * 2.0f < distance) {
throw new IllegalArgumentException("The radius is too small! The given points wont fall on the circle.");
}
// Calculate the middle of the expected curve.
float factor = (float) Math.sqrt((pRadius * pRadius) / ((pTo.x - pFrom.x) * (pTo.x - pFrom.x) + (pTo.y - pFrom.y) * (pTo.y - pFrom.y)) - 0.25f);
PointF circleMiddlePoint = new PointF(0, 0);
if (side) {
circleMiddlePoint.x = 0.5f * (pFrom.x + pTo.x) + factor * (pTo.y - pFrom.y);
circleMiddlePoint.y = 0.5f * (pFrom.y + pTo.y) + factor * (pFrom.x - pTo.x);
} else {
circleMiddlePoint.x = 0.5f * (pFrom.x + pTo.x) - factor * (pTo.y - pFrom.y);
circleMiddlePoint.y = 0.5f * (pFrom.y + pTo.y) - factor * (pFrom.x - pTo.x);
}
System.out.println("Middle = " + circleMiddlePoint);
// Calculate the two reference angles
float angle1 = (float) Math.atan2(pFrom.y - circleMiddlePoint.y, pFrom.x - circleMiddlePoint.x);
float angle2 = (float) Math.atan2(pTo.y - circleMiddlePoint.y, pTo.x - circleMiddlePoint.x);
// Calculate the step.
float step = pMinDistance / pRadius;
System.out.println("Step = " + step);
// Swap them if needed
if (angle1 > angle2) {
float temp = angle1;
angle1 = angle2;
angle2 = temp;
}
boolean flipped = false;
if (!shortest) {
if (angle2 - angle1 < Math.PI) {
float temp = angle1;
angle1 = angle2;
angle2 = temp;
angle2 += Math.PI * 2.0f;
flipped = true;
}
}
for (float f = angle1; f < angle2; f += step) {
PointF p = new PointF((float) Math.cos(f) * pRadius + circleMiddlePoint.x, (float) Math.sin(f) * pRadius + circleMiddlePoint.y);
pOutPut.add(p);
}
if (flipped ^ side) {
pOutPut.add(pFrom);
} else {
pOutPut.add(pTo);
}
return pOutPut;
}
}
and the use the generateCurve method like this to have a curve between the from and to points..
generateCurve(pFrom, pTo, 100f, 7f, true, false);
Okay, here it is, testing and working. The problems were based on the fact that I don't use graphics much, so I have to remind myself that the coordinate systems are backward, and on the fact that the Javadoc description of the Arc2D constructor is atrocious.
In addition to these, I found that your point creation (for the two points to be connected) was extremely inefficient given the requirements. I had assumed you actually had to receive two arbitrary points and then calculate their angles, etc., but based on what you put on Pastebin, we can define the two points however we please. This benefits us.
Anyway, here's a working version, with none of that gobbledegook from before. Simplified code is simplified:
import javax.swing.JComponent;
import java.awt.geom.*;
import java.awt.*;
import java.util.*;
public class Canvas extends JComponent {
double circleX, circleY, x1, y1, x2, y2, dx, dy, dx2, dy2, radius, radius2;
Random random = new Random();
double distance;
private static double theta1;
private static double theta2;
private static double theta;
// private static double radius;
private Point2D point1;
private Point2D point2;
private Point2D center;
private static int direction;
private static final int CW = -1;
private static final int CCW = 1;
public Canvas() {
/*
* You want two random points on a circle, so let's start correctly,
* by setting a random *radius*, and then two random *angles*.
*
* This has the added benefit of giving us the angles without having to calculate them
*/
radius = random.nextInt(175); //your maximum radius is higher, but we only have 200 pixels in each cardinal direction
theta1 = random.nextInt(360); //angle to first point (absolute measurement)
theta2 = random.nextInt(360); //angle to second point
//build the points
center = new Point2D.Double(200, 200); //your frame is actually 400 pixels on a side
point1 = new Point2D.Double(radius * Math.cos(toRadians(theta1)) + center.getX(), center.getY() - radius * Math.sin(toRadians(theta1)));
point2 = new Point2D.Double(radius * Math.cos(toRadians(theta2)) + center.getX(), center.getY() - radius * Math.sin(toRadians(theta2)));
theta = Math.abs(theta1 - theta2) <= 180 ? Math.abs(theta1 - theta2) : 360 - (Math.abs(theta1 - theta2));
if ((theta1 + theta) % 360 == theta2) {
direction = CCW;
} else {
direction = CW;
}
System.out.println("theta1: " + theta1 + "; theta2: " + theta2 + "; theta: " + theta + "; direction: " + (direction == CCW ? "CCW" : "CW"));
System.out.println("point1: (" + (point1.getX() - center.getX()) + ", " + (center.getY() - point1.getY()) + ")");
System.out.println("point2: (" + (point2.getX() - center.getX()) + ", " + (center.getY() - point2.getY()) + ")");
// Radius now equal for both points.
}
public double toRadians(double angle) {
return angle * Math.PI / 180;
}
public double toDegrees(double angle) {
return angle * 180 / Math.PI;
}
public void paintComponent(Graphics g2) {
Graphics2D g = (Graphics2D) g2;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_BEVEL));
//centerpoint should be based on the actual center point
Arc2D.Double centerPoint = new Arc2D.Double(center.getX() - 2, center.getY() - 2, 4, 4, 0,
360, Arc2D.OPEN);
//likewise these points
Arc2D.Double point11 = new Arc2D.Double(point1.getX() - 2, point1.getY() - 2, 4, 4, 0, 360,
Arc2D.OPEN);
Arc2D.Double point22 = new Arc2D.Double(point2.getX() - 2, point2.getY() - 2, 4, 4, 0, 360,
Arc2D.OPEN);
// 3 points drawn in black
g.setColor(Color.BLACK);
g.draw(centerPoint);
g.draw(point11);
g.draw(point22);
// Arc drawn in blue
g.setColor(Color.BLUE);
g.draw(new Arc2D.Double(center.getX() - radius, center.getY() - radius, 2 * radius, 2 * radius, theta1, theta * direction, Arc2D.OPEN));
}
}

How can I change the shape of a JTabbedPane tab?

I am trying to change the shape of the tabs in a JTabbedPane. Using setTabComponentAt(0, someComponent); doesn't change the exterior of the tab, which is a rectangle with a diagonal top-left corner. What may be done to change the shape?
correct way is only to change Look and Feel, nice example from Old.Java.Forums.Sun
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
public class TabbedPane extends JPanel {
private static final long serialVersionUID = 1L;
public TabbedPane() {
setLayout(new BorderLayout());
JPanel jp = new JPanel();
jp.setLayout(new BorderLayout());
JTabbedPane tb = new JTabbedPane();
tb.setUI(new CustomTabbedPaneUI());
tb.add("Tab1", new JTextArea(""));
tb.add("Tab2", new JTextArea(""));
tb.add("Tab3", new JTextArea(""));
tb.add("Tab4", new JTextArea(""));
tb.add("Tab5", new JTextArea(""));
jp.add(tb, BorderLayout.CENTER);
add(jp, BorderLayout.CENTER);
tb.setEnabledAt(1, false);
tb.setEnabledAt(3, false);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new TabbedPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 200);
frame.setVisible(true);
}
}
and
import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.*;
import javax.swing.text.View;
public class CustomTabbedPaneUI extends BasicTabbedPaneUI {
private Color selectColor;
private Color deSelectColor;
private int inclTab = 4;
private int anchoFocoV = inclTab;
private int anchoFocoH = 4;
private int anchoCarpetas = 18;
private Polygon shape;
public static ComponentUI createUI(JComponent c) {
return new CustomTabbedPaneUI();
}
#Override
protected void installDefaults() {
super.installDefaults();
selectColor = new Color(250, 192, 192);
deSelectColor = new Color(197, 193, 168);
tabAreaInsets.right = anchoCarpetas;
}
#Override
protected void paintTabArea(Graphics g, int tabPlacement, int selectedIndex) {
if (runCount > 1) {
int lines[] = new int[runCount];
for (int i = 0; i < runCount; i++) {
lines[i] = rects[tabRuns[i]].y + (tabPlacement == TOP ? maxTabHeight : 0);
}
Arrays.sort(lines);
if (tabPlacement == TOP) {
int fila = runCount;
for (int i = 0; i < lines.length - 1; i++, fila--) {
Polygon carp = new Polygon();
carp.addPoint(0, lines[i]);
carp.addPoint(tabPane.getWidth() - 2 * fila - 2, lines[i]);
carp.addPoint(tabPane.getWidth() - 2 * fila, lines[i] + 3);
if (i < lines.length - 2) {
carp.addPoint(tabPane.getWidth() - 2 * fila, lines[i + 1]);
carp.addPoint(0, lines[i + 1]);
} else {
carp.addPoint(tabPane.getWidth() - 2 * fila, lines[i] + rects[selectedIndex].height);
carp.addPoint(0, lines[i] + rects[selectedIndex].height);
}
carp.addPoint(0, lines[i]);
g.setColor(hazAlfa(fila));
g.fillPolygon(carp);
g.setColor(darkShadow.darker());
g.drawPolygon(carp);
}
} else {
int fila = 0;
for (int i = 0; i < lines.length - 1; i++, fila++) {
Polygon carp = new Polygon();
carp.addPoint(0, lines[i]);
carp.addPoint(tabPane.getWidth() - 2 * fila - 1, lines[i]);
carp.addPoint(tabPane.getWidth() - 2 * fila - 1, lines[i + 1] - 3);
carp.addPoint(tabPane.getWidth() - 2 * fila - 3, lines[i + 1]);
carp.addPoint(0, lines[i + 1]);
carp.addPoint(0, lines[i]);
g.setColor(hazAlfa(fila + 2));
g.fillPolygon(carp);
g.setColor(darkShadow.darker());
g.drawPolygon(carp);
}
}
}
super.paintTabArea(g, tabPlacement, selectedIndex);
}
#Override
protected void paintTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) {
Graphics2D g2D = (Graphics2D) g;
GradientPaint gradientShadow;
int xp[] = null; // Para la forma
int yp[] = null;
switch (tabPlacement) {
case LEFT:
xp = new int[]{x, x, x + w, x + w, x};
yp = new int[]{y, y + h - 3, y + h - 3, y, y};
gradientShadow = new GradientPaint(x, y, new Color(100, 100, 255), x, y + h, Color.ORANGE);
break;
case RIGHT:
xp = new int[]{x, x, x + w - 2, x + w - 2, x};
yp = new int[]{y, y + h - 3, y + h - 3, y, y};
gradientShadow = new GradientPaint(x, y, new Color(100, 100, 255), x, y + h, new Color(153, 186, 243));
break;
case BOTTOM:
xp = new int[]{x, x, x + 3, x + w - inclTab - 6, x + w - inclTab - 2, x + w - inclTab, x + w - 3, x};
yp = new int[]{y, y + h - 3, y + h, y + h, y + h - 1, y + h - 3, y, y};
gradientShadow = new GradientPaint(x, y, new Color(100, 100, 255), x, y + h, Color.BLUE);
break;
case TOP:
default:
xp = new int[]{x, x, x + 3, x + w - inclTab - 6, x + w - inclTab - 2, x + w - inclTab, x + w - inclTab, x};
yp = new int[]{y + h, y + 3, y, y, y + 1, y + 3, y + h, y + h};
gradientShadow = new GradientPaint(0, 0, Color.ORANGE, 0, y + h / 2, new Color(240, 255, 210));
break;
}
// ;
shape = new Polygon(xp, yp, xp.length);
if (isSelected) {
g2D.setColor(selectColor);
g2D.setPaint(gradientShadow);
} else {
if (tabPane.isEnabled() && tabPane.isEnabledAt(tabIndex)) {
g2D.setColor(deSelectColor);
GradientPaint gradientShadowTmp = new GradientPaint(0, 0, new Color(255, 255, 200), 0, y + h / 2, new Color(240, 255, 210));
g2D.setPaint(gradientShadowTmp);
} else {
GradientPaint gradientShadowTmp = new GradientPaint(0, 0, new Color(240, 255, 210), 0, y + 15 + h / 2, new Color(204, 204, 204));
g2D.setPaint(gradientShadowTmp);
}
}
//selectColor = new Color(255, 255, 200);
//deSelectColor = new Color(240, 255, 210);
g2D.fill(shape);
if (runCount > 1) {
g2D.setColor(hazAlfa(getRunForTab(tabPane.getTabCount(), tabIndex) - 1));
g2D.fill(shape);
}
g2D.fill(shape);
}
#Override
protected void paintText(Graphics g, int tabPlacement, Font font, FontMetrics metrics, int tabIndex, String title, Rectangle textRect, boolean isSelected) {
super.paintText(g, tabPlacement, font, metrics, tabIndex, title, textRect, isSelected);
g.setFont(font);
View v = getTextViewForTab(tabIndex);
if (v != null) {
// html
v.paint(g, textRect);
} else {
// plain text
int mnemIndex = tabPane.getDisplayedMnemonicIndexAt(tabIndex);
if (tabPane.isEnabled() && tabPane.isEnabledAt(tabIndex)) {
g.setColor(tabPane.getForegroundAt(tabIndex));
BasicGraphicsUtils.drawStringUnderlineCharAt(g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent());
} else { // tab disabled
g.setColor(Color.BLACK);
BasicGraphicsUtils.drawStringUnderlineCharAt(g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent());
g.setColor(tabPane.getBackgroundAt(tabIndex).darker());
BasicGraphicsUtils.drawStringUnderlineCharAt(g, title, mnemIndex, textRect.x - 1, textRect.y + metrics.getAscent() - 1);
}
}
}
/*protected void paintText(Graphics g, int tabPlacement, Font font, FontMetrics metrics, int tabIndex, String title, Rectangle textRect, boolean isSelected) {
g.setFont(font);
View v = getTextViewForTab(tabIndex);
if (v != null) {
// html
v.paint(g, textRect);
} else {
// plain text
int mnemIndex = tabPane.getDisplayedMnemonicIndexAt(tabIndex);
if (tabPane.isEnabled() && tabPane.isEnabledAt(tabIndex)) {
Color fg = tabPane.getForegroundAt(tabIndex);
if (isSelected && (fg instanceof UIResource)) {
Color selectedFG = UIManager.getColor("TabbedPane.selectedForeground");
if (selectedFG != null) {
fg = selectedFG;
}
}
g.setColor(fg);
SwingUtilities2.drawStringUnderlineCharAt(tabPane, g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent());
} else { // tab disabled
//PAY ATTENTION TO HERE
g.setColor(tabPane.getBackgroundAt(tabIndex).brighter());
SwingUtilities2.drawStringUnderlineCharAt(tabPane, g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent());
g.setColor(tabPane.getBackgroundAt(tabIndex).darker());
SwingUtilities2.drawStringUnderlineCharAt(tabPane, g, title, mnemIndex,
textRect.x - 1, textRect.y + metrics.getAscent() - 1);
}
}
}*/
#Override
protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) {
return 20 + inclTab + super.calculateTabWidth(tabPlacement, tabIndex, metrics);
}
#Override
protected int calculateTabHeight(int tabPlacement, int tabIndex, int fontHeight) {
if (tabPlacement == LEFT || tabPlacement == RIGHT) {
return super.calculateTabHeight(tabPlacement, tabIndex, fontHeight);
} else {
return anchoFocoH + super.calculateTabHeight(tabPlacement, tabIndex, fontHeight);
}
}
#Override
protected void paintTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) {
}
#Override
protected void paintFocusIndicator(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect, boolean isSelected) {
if (tabPane.hasFocus() && isSelected) {
g.setColor(UIManager.getColor("ScrollBar.thumbShadow"));
g.drawPolygon(shape);
}
}
protected Color hazAlfa(int fila) {
int alfa = 0;
if (fila >= 0) {
alfa = 50 + (fila > 7 ? 70 : 10 * fila);
}
return new Color(0, 0, 0, alfa);
}
}
The shape is under the aegis of the tabbed pane's UI delegate, which descends from TabbedPaneUI. The MetalTabbedPaneUI subclass is an example that may help you decide how badly you want to replace the delegate.
You can put html tags into the first parameter of addTab method as following :
MyJTabbedPane.addTab("<html><h1 style='padding:20px;'>TEST</h1></html>", new JPanel());

Categories

Resources