How to do different drawings in different methods using paintComponent? [closed] - java

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have 2 classes, one which extends a panel and other which extends a frame.
First class, the panel(used for drawings):
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GraficPne extends JPanel{
public int dim1 = 0, dim2 = 0;
public JLabel lblSem1GraficPne, lblSem2GraficPne;
public GraficPne(){
super();
this.setLayout(null);
this.setupComponents();
}
public void setupComponents(){
lblSem1GraficPne = new JLabel("Sem I");
lblSem2GraficPne = new JLabel("Sem II");
lblSem1GraficPne.setFont(new Font("Serif", Font.PLAIN, 12));
lblSem2GraficPne.setFont(new Font("Serif", Font.PLAIN, 12));
this.add(lblSem1GraficPne);
this.add(lblSem2GraficPne);
}
public void layComponents(int firstConv, int secondConv){
lblSem1GraficPne.setBounds(20, getHeight() - firstConv - 20, 100, 20);
lblSem2GraficPne.setBounds(100, getHeight() - secondConv - 20, 100, 20);
}
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.BLACK);
g.drawRect(0, 0, getWidth()-1, getHeight()-1);
this.setBackground(Color.GREEN);
g.setColor(Color.RED);
g.fillRect(20, getHeight()-dim1, 40, dim1);
g.setColor(Color.BLUE);
g.fillRect(100, getHeight()-dim2, 40, dim2);
}
public void setData(int dim1, int dim2){
this.dim1 = dim1;
this.dim2 = dim2;
}
}
Second class, the frame, used to add the panel on it:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class GraficFrm extends JFrame implements ActionListener{
private JButton btnApply;
private JLabel lblSem1, lblSem2;
private JTextField txtSem1, txtSem2;
private GraficPne ob; //the object from first class
private int firstConv = 0, secondConv = 0;
public GraficFrm() {
super("Grafic soft");
initSettings();
setupComponents();
}
private void initSettings() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(null);
this.setSize(400, 450);
this.setLocation(100, 100);
this.setResizable(false);
}
private void setupComponents() {
ob = new GraficPne();
lblSem1 = new JLabel("Sem I");
txtSem1 = new JTextField();
lblSem2 = new JLabel("Sem II");
txtSem2 = new JTextField();
btnApply = new JButton("Apply");
ob.setBounds(30, 50, 340, 200);
lblSem1.setBounds(30, 280, 100, 20);
txtSem1.setBounds(150, 280, 220, 20);
lblSem2.setBounds(30, 330, 100, 20);
txtSem2.setBounds(150, 330, 220, 20);
btnApply.setBounds(170, 380, 80, 30);
this.add(lblSem1);
this.add(ob);
this.add(txtSem1);
this.add(lblSem2);
this.add(txtSem2);
this.add(btnApply);
btnApply.addActionListener(this);
}
public void getConvertedValues(){
String txtField1 = txtSem1.getText();
firstConv = Integer.parseInt(txtField1);
String txtField2 = txtSem2.getText();
secondConv = Integer.parseInt(txtField2);
}
public void getHighValues(){
if((firstConv > 100) || (secondConv > 100)) {
JOptionPane.showMessageDialog(this, "Only values < 100 are allowed");
firstConv = 0;
secondConv = 0;
txtSem1.setText("");
txtSem2.setText("");
ob.removeAll();
ob.repaint();
}
}
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(btnApply)){
try{
new GraficFrm();
getConvertedValues();
getHighValues();
ob.setData(firstConv, secondConv);
ob.layComponents(firstConv,secondConv);
ob.repaint();
}catch(NumberFormatException ex1){
JOptionPane.showMessageDialog(this, "Only natural numbers are allowed");
}
}
}
public static void main(String[] args) {
GraficFrm frm = new GraficFrm();
frm.setVisible(true);
}
}
All I want to do is to create a new method called getNegativeValues(), which would be called by pressing the Apply button, and this method to be executed when firstConv or secondConv would be < than 0. The block of my method, getNegativeValues(), i want to keep only the green background of the panel, as it is in paint(Graphics g), but to draw a center horizontal line(g.drawLine(0, getHeight()/2, getWidth(), getHeight()/2);). Then, when i execute the program and i type, let's say the value 55 for the first textfield and -40 for the second one, to draw 55 over my center horizontal line and -40 under my center horizontal line, and the 0 point would be on this center horizontal line.
LE:
#nIcE cOw i'll make a short recap: So, first, when i execute my app, i just want to appear my green panel and those 2 labels which have 2 textfields, as in my example(try to follow my example, please)(all good, i already did this, so this part is done). After, when i complete those 2 textfields let's say with 2 positive values, and then when i press the Apply button to happen exactly like in my example(without any center vertical line)(so already did this, also). All good, but my problem is: If complete one of those 2 textfields with a negative value and other with a positive one, and after i press the Apply button, i want that my application to recognize that there is a negative value typped in one of my textfields, thus to draw me on my green panel a center horizontal line(after i press the Apply button) and to draw those 2 rectangles exactly as you did in your first picture uploaded. Please help me, as i said i'll help you to understand what i want to do, and also i want to say i really appreciate your effort and i'm sorry (again) if i was confused(again).

I guess, what you looking for is a method as presented below, that might can calculate, the starting point of Rectangles that you are trying to draw on the JPanel. Here pos is Positive Value and neg is Negative Value:
public void setValues(int above, int below)
{
midPoint = getHeight() / 2;
heightAbove = Math.abs(above);
heightBelow = Math.abs(below);
/*
* If both are negative values,
* we need a Mid-Point in this case.
*/
if (above < 0 && below < 0)
{
rectAbove = midPoint;
diff = 120;
rectBelow = midPoint;
flag = true;
}
else if (above >= 0 && below >= 0)
{
rectAbove = getHeight() - heightAbove;
diff = 120;
rectBelow = getHeight() - heightBelow;
flag = false;
}
else if (above < 0 && below >= 0)
{
rectAbove = midPoint;
diff = 40;
rectBelow = midPoint - heightBelow;
flag = true;
}
else if (above >= 0 && below < 0)
{
rectAbove = midPoint - heightAbove;
diff = 40;
rectBelow = midPoint;
flag = true;
}
repaint();
}
Here is the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PaintingRectangles
{
private JTextField aboveField;
private JTextField belowField;
private JButton applyButton;
private MyCanvas canvas;
private void displayGUI()
{
JFrame frame = new JFrame("Painting Rectangles Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new GridLayout(3, 1, 5, 5));
aboveField = new JTextField(10);
belowField = new JTextField(10);
applyButton = new JButton("Apply");
applyButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
int above = 0;
int below = 0;
try
{
above = Integer.parseInt(aboveField.getText());
below = Integer.parseInt(belowField.getText());
}
catch(NumberFormatException nfe)
{
aboveField.setText("0");
belowField.setText("0");
above = 0;
below = 0;
nfe.printStackTrace();
}
canvas.setValues(above, below);
}
});
rightPanel.add(aboveField);
rightPanel.add(belowField);
rightPanel.add(applyButton);
canvas = new MyCanvas();
contentPane.add(canvas, BorderLayout.CENTER);
contentPane.add(rightPanel, BorderLayout.LINE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new PaintingRectangles().displayGUI();
}
});
}
}
class MyCanvas extends JPanel
{
private int midPoint = getHeight() / 2;
private int rectAbove = getHeight() / 2;
private int rectBelow = getHeight() / 2;
private int width = 40;
private int heightAbove = 0;
private int heightBelow = 0;
private int diff = 0;
private boolean flag = false;
public MyCanvas()
{
setBackground(Color.GREEN);
}
public void setValues(int above, int below)
{
midPoint = getHeight() / 2;
heightAbove = Math.abs(above);
heightBelow = Math.abs(below);
/*
* If both are negative values,
* we need a Mid-Point in this case.
*/
if (above < 0 && below < 0)
{
rectAbove = midPoint;
diff = 120;
rectBelow = midPoint;
flag = true;
}
else if (above >= 0 && below >= 0)
{
rectAbove = getHeight() - heightAbove;
diff = 120;
rectBelow = getHeight() - heightBelow;
flag = false;
}
else if (above < 0 && below >= 0)
{
rectAbove = midPoint;
diff = 40;
rectBelow = midPoint - heightBelow;
flag = true;
}
else if (above >= 0 && below < 0)
{
rectAbove = midPoint - heightAbove;
diff = 40;
rectBelow = midPoint;
flag = true;
}
repaint();
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(400, 400));
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.BLACK);
g.drawRect(0, 0, getWidth(), getHeight());
if (flag)
g.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2);
makeRectangles(g);
}
private void makeRectangles(Graphics g)
{
g.setColor(Color.RED);
g.fillRect(40, rectAbove, width, heightAbove);
g.setColor(Color.BLUE);
g.fillRect(diff, rectBelow, width, heightBelow);
g.dispose();
}
}
Here is the output:

Related

Why arent the squares being painted?

I started a Chess Project reusing some older code to paint a map everything basically has been copy pasted. The problem is the squares dont show up? I tried fixing it for a while now and got to no solution. Here are probably the three most important methods and a zip with the whole project. Some of it is in German.
https://drive.google.com/file/d/1nnZHLB0Ycy04eMyYbEmduMwbGhVLZ2VB/view?usp=sharing
public SchachFrame() {
super();
contentPane = new JPanel();
setContentPane(contentPane);
setBounds(0, 0, window.width, window.height);
contentPane.setBackground(Color.darkGray);
contentPane.setVisible(true);
ge = new GameEnvironment(this);
ge.setBounds(window.width/2 - 500, window.height/2 - 500, 1000, 1000);
ge.setVisible(true);
contentPane.add(ge);
Thread gameEnvironment = new Thread(ge);
gameEnvironment.start();
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void createMap(int width, int length, GameEnvironment ge) {
map = new Spielfeld[length][width];
Spielfeld.width = 1000/width;
Spielfeld.height = 1000/length;
for(int i = 0; i < length; i++) {
for(int j = 0; j < width; j++) {
this.map[i][j] = new Spielfeld(j, i, null);
this.map[i][j].setBounds(ge.getX() + j * Spielfeld.width, ge.getY() + i * Spielfeld.height, Spielfeld.width, Spielfeld.height);
this.map[i][j].setVisible(true);
ge.add(this.map[i][j]);
}
}
}
public void paintComponent(Graphics g) {
if((this.px + this.py) % 2 == 0) {
g.setColor(Color.blue);
} else {
g.setColor(Color.cyan);
}
g.fillRect(this.getX(), this.getY(), this.getWidth(), this.getHeight());
repaint();
}
Do not call repaint() in paintComponent. Otherwise you will never exit the EDT and lock up your code. And the first statement in paintComponent(Graphics g) should be super.paintComponent(g);
Updated to include an example
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DrawSquareComponent extends JPanel {
static int WIDTH = 600;
static int HEIGHT = 600;
JFrame frame = new JFrame();
public static void main(String[] args) {
new DrawSquareComponent().start();
}
public void start() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
setBackground(Color.white);
MyComponent my =new MyComponent();
add(my); // add my component to panel
Random r = new Random();
for (int i = 0; i < 20; i++) {
int size = r.nextInt(50)+50;
int x = r.nextInt(WIDTH-size)+1;
int y = r.nextInt(HEIGHT-size)+1;
my.setBounds(x,y,size,size);
frame.repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
}
}
public Dimension getPreferredSize() {
return new Dimension(WIDTH, HEIGHT);
}
}
class MyComponent extends JPanel {
#Override
public void paintComponent(Graphics g) {
Graphics gg = g.create();
super.paintComponent(gg);
// location relative to parent's.
// used to check location in parent's coordinate space.
Point p = getLocation();
if ((p.x + p.y) % 2 == 0) {
gg.setColor(Color.blue);
} else {
gg.setColor(Color.cyan);
}
// paint this component so location is always 0,0.
// all you're doing is painting this squares background
gg.fillRect(0,0, this.getWidth(), this.getHeight());
gg.dispose();
}
}

Printing a timer that updates every second into a simple game

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.Timer;
public class FinalFlappy implements ActionListener, MouseListener,
KeyListener
{
public static FinalFlappy finalFlappy;
public final int WIDTH = 800, HEIGHT = 800;
public FinalFlappyRend renderer;
public Rectangle bee;
public ArrayList<Rectangle> rect_column;
public int push, yMotion, score;
public boolean gameOver, started;
public Random rand;
public FinalFlappy()
{
JFrame jframe = new JFrame();
Timer timer = new Timer(16, this);
renderer = new FinalFlappyRend();
rand = new Random();
jframe.add(renderer);
jframe.setTitle("Flappy Bee");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(WIDTH, HEIGHT);
jframe.addMouseListener(this);
jframe.addKeyListener(this);
jframe.setResizable(false);
jframe.setVisible(true);
bee = new Rectangle(WIDTH / 2 - 10, HEIGHT / 2 - 10, 40, 40);
rect_column = new ArrayList<Rectangle>();
addColumn(true);
addColumn(true);
addColumn(true);
addColumn(true);
timer.start();
}
public void addColumn(boolean start)
{
int space = 300;
int width = 60;
int height = 50 + rand.nextInt(300);
if (start)
{
rect_column.add(new Rectangle(WIDTH + width + rect_column.size() * 300, HEIGHT - height - 120, width, height));
rect_column.add(new Rectangle(WIDTH + width + (rect_column.size() - 1) * 300, 0, width, HEIGHT - height - space));
}
else
{
rect_column.add(new Rectangle(rect_column.get(rect_column.size() - 1).x + 600, HEIGHT - height - 120, width, height));
rect_column.add(new Rectangle(rect_column.get(rect_column.size() - 1).x, 0, width, HEIGHT - height - space));
}
}
public void jump()
{
if (gameOver)
{
bee = new Rectangle(WIDTH / 2 - 10, HEIGHT / 2 - 10, 40, 40);
rect_column.clear();
yMotion = 0;
score = 0;
addColumn(true);
addColumn(true);
addColumn(true);
addColumn(true);
gameOver = false;
}
if (!started)
{
started = true;
}
else if (!gameOver)
{
if (yMotion > 0)
{
yMotion = 0;
}
yMotion -= 10;
}
}
#Override
public void actionPerformed(ActionEvent e)
{
int speed = 10;
push++;
if (started)
{
for (int i = 0; i < rect_column.size(); i++)
{
Rectangle column = rect_column.get(i);
column.x -= speed;
}
if (push % 2 == 0 && yMotion < 15)
{
yMotion += 2;
}
for (int i = 0; i < rect_column.size(); i++)
{
Rectangle column = rect_column.get(i);
if (column.x + column.width < 0)
{
rect_column.remove(column);
if (column.y == 0)
{
addColumn(false);
}
}
}
bee.y += yMotion;
for (Rectangle column : rect_column)
{
if (column.y == 0 && bee.x + bee.width / 2 > column.x + column.width / 2 - 10 && bee.x + bee.width / 2 < column.x + column.width / 2 + 10)
{
score++;
}
if (column.intersects(bee))
{
gameOver = true;
if (bee.x <= column.x)
{
bee.x = column.x - bee.width;
}
else
{
if (column.y != 0)
{
bee.y = column.y - bee.height;
}
else if (bee.y < column.height)
{
bee.y = column.height;
}
}
}
}
if (bee.y > HEIGHT - 120 || bee.y < 0)
{
gameOver = true;
}
if (bee.y + yMotion >= HEIGHT - 120)
{
bee.y = HEIGHT - 120 - bee.height;
gameOver = true;
}
}
renderer.repaint();
}
public void paintColumn(Graphics g, Rectangle column)
{
g.setColor(Color.green.darker());
g.fillRect(column.x, column.y, column.width, column.height);
g.fillRect(column.x-20, column.y+column.height-10, column.width+40, 10);
g.fillRect(column.x-20, column.y-10, column.width+40, 10);
}
public void repaint(Graphics g)
{
g.setColor(new Color(153,204,255));
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(new Color(255,255,255));
g.fillOval(50, 50, 100, 100);
g.setColor(Color.YELLOW);
g.fillOval(600, 50, 100, 100);
g.setColor(new Color(156,93,82));
g.fillRect(0, HEIGHT - 120, WIDTH, 120);
g.setColor(new Color(128,255,0));
g.fillRect(0, HEIGHT - 120, WIDTH, 20);
g.setColor(Color.YELLOW);
g.fillRect(bee.x, bee.y, bee.width, bee.height);
for (Rectangle column : rect_column)
{
paintColumn(g, column);
}
g.setColor(Color.white);
g.setFont(new Font("Times New Roman", 1, 100));
if (!started)
{
g.drawString("Push A to start", 100, HEIGHT / 2 - 50);
}
if (gameOver)
{
g.drawString("Game Over", 100, HEIGHT / 2 - 50);
g.drawString("A to replay", 100, HEIGHT / 2 + 90);
}
}
public static void main(String[] args)
{
finalFlappy = new FinalFlappy();
}
#Override
public void mouseClicked(MouseEvent e)
{
jump();
}
#Override
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_A)
{
jump();
}
}
#Override
public void mousePressed(MouseEvent e)
{
}
#Override
public void mouseReleased(MouseEvent e)
{
}
#Override
public void mouseEntered(MouseEvent e)
{
}
#Override
public void mouseExited(MouseEvent e)
{
}
#Override
public void keyTyped(KeyEvent e)
{
}
#Override
public void keyPressed(KeyEvent e)
{
}
}
import java.awt.Graphics;
import javax.swing.JPanel;
public class FinalFlappyRend extends JPanel
{
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
FinalFlappy.finalFlappy.repaint(g);
}
}
I am working on making a Flappy bird game and I am stuck on how to make and display a timer that updates every second onto the screen
How do I make it start as the game starts and end as the game over pops up?
There are a few ways you might achieve what you're asking. The important thing to remember is, any solution is going to have a degree of drift, meaning that it's unlikely to absolutely accurate, the degree of drift will depend on a lot of factors, so just beware.
You could use a Swing Timer
It's among the safest means for updating the UI on a regular basis, it's also useful if your main loop is already based on a Swing Timer
See How to Use Swing Timers for more details
You could...
Maintain some kind of counter within in your main loop. This assumes that you're using a separate thread (although you can do the same thing with a Swing Timer) and are simply looping at some consistent rate
long tick = System.nanoTime();
long lastUpdate = -1;
while (true) {
long diff = System.nanoTime() - tick;
long seconds = TimeUnit.SECONDS.convert(diff, TimeUnit.NANOSECONDS);
if (seconds != lastUpdate) {
lastUpdate = seconds;
updateTimerLabel(seconds);
}
Thread.sleep(100);
}
This basically runs a while-loop, which calculates the difference between a given point in time (tick) and now, if it's a "second" difference, it then updates the UI (rather than constantly updating the UI with the same value)
The updateTimerLabel method basically updates the label with the specified time, but does so in a manner which is thread safe
protected void updateTimerLabel(long seconds) {
if (EventQueue.isDispatchThread()) {
timerLabel.setText(Long.toString(seconds));
} else {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
updateTimerLabel(seconds);
}
});
}
}
To make and display a timer that updates every second, Put this code in your main class:
private Timer timer = new Timer();
private JLabel timeLabel = new JLabel(" ", JLabel.CENTER);
timer.schedule(new UpdateUITask(), 0, 1000);
private class UpdateUITask extends TimerTask {
int nSeconds = 0;
#Override
public void run() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
timeLabel.setText(String.valueOf(nSeconds++));
}
});
}
}

JButtons keep redrawing

I'm trying to make a goal organizer program and want to be able to zoom in and out with the buttons moving with the border of the rectangle, but when I press the zoom in or out button it leaves the original where it is and creates a new one over it. Also the buttons are shown in the position I coded for, but they also show up at the top of the screen.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Screen extends JPanel implements Runnable{
/**
*
*/
private static final long serialVersionUID = 1L;
Frame frame;
Thread thread = new Thread(this);
public JButton one;
public JButton two;
public JButton zoomIn;
public JButton zoomOut;
public JButton next;
public JButton xv;
int buttonW = 100;
int buttonH = 50;
int zoomLevel = 5;
int fps;
public boolean running = true;
public Screen(Frame frame) {
this.frame = frame;
thread.start();
}
public void run() {
long lastFrame = System.currentTimeMillis();
int frames = 0;
running = true;
while(running){
repaint();
frames++;
if(System.currentTimeMillis() - 1000 >= lastFrame){
fps = frames;
frames = 0;
lastFrame = System.currentTimeMillis();
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void paintComponent(Graphics g){
Color bgc = new Color (192,192,192);
int screenW = this.getWidth();
int screenH = this.getHeight();
int centerH = screenH / 2;
int centerW = screenW / 2;
g.setColor(bgc);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
/*---------------------------button-stuff------------------------------ **/
Icon plus = new ImageIcon("res/buttons/plus.png");
Icon minus = new ImageIcon("res/buttons/minus.png");
/*---------------------------zoom buttons------------------------------**/
zoomOut = new JButton("", minus);
zoomOut.setBounds(screenW - 30, 32, 20, 20);
zoomOut.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
buttonH = buttonH-10;
buttonW = buttonW-20;
zoomLevel = zoomLevel-1;
}
});
zoomIn = new JButton("", plus);
zoomIn.setBounds(screenW - 30, 10, 20, 20);
zoomIn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
buttonH = buttonH+10;
buttonW = buttonW+20;
zoomLevel = zoomLevel+1;
}
});
/*------------------------------------Next--------------------------------------------------------**/
next = new JButton("");
next.setBounds(centerW + ((buttonW / 2) - 5), centerH - 5, 10, 10);
next.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
JButton oo = new JButton("new");
oo.setBounds(10,10,10,10);
add(oo);
}
});
xv = new JButton("");
add(xv);
xv.setBounds(centerW -10, centerH - ((buttonH / 2) + 10), 20, 20);
/*------------------------------Add Buttons----------------------------------------------------------**/
add(zoomOut);
add(zoomIn);
add(next);
g.setColor(Color.GREEN);
g.fillRect(centerW - (buttonW / 2), centerH - (buttonH / 2), buttonW, buttonH);
}
}

Filling a HUD in Java

I've decided on making a HUD with the picture above, but I don't know what command in Java I need to use so as I can fill the top half and the bottom half separately.
I only know how to use the g.fillRect(); command, and it will take around twenty of these commands to fill said half.
public class HUD {
private Player player;
private BufferedImage image;
private Font font;
private Font font2;
private int Phealth = Player.getHealth();
public HUD(Player p) {
player = p;
try {
image = ImageIO.read(getClass().getResourceAsStream("/HUD/HUD_TEST.gif"));
font = new Font("Arial", Font.PLAIN, 10);
font2 = new Font("SANS_SERIF", Font.BOLD, 10);
}
catch(Exception e) {
e.printStackTrace();
}
}
public void draw(Graphics2D g) {
g.drawImage(image, 0, 10, null);
g.setFont(font2);
g.setColor(Color.black);
g.drawString("Health:", 30, 22);
g.drawString("Mana:", 25, 47);
g.setFont(font);
g.drawString(Player.getHealth() + "/" + player.getMaxHealth(), 64, 22);
g.drawString(player.getCubes() / 100 + "/" + player.getMaxCubes() / 100, 55, 47);
g.setColor(Color.red);
g.fillRect(1, 25, Phealth * 25, 4);
g.setColor(Color.blue);
g.fillRect(1, 31, player.getCubes() / 33, 4);
}
}
This is the code for the HUD so far.
Any help in filling the shape will help.
Removed Idea #1! (It didn't seem to work.)
Okay, Idea #2:
Image1
Image2
Image3
So, there are 3 .png images.
Draw Image1 first, followed by drawing Image2 and Image3 directly on top of it.
To fill up either the red/blue bars, clip Image2 and Image3 accordingly (i.e. cut away their left sides)
Take a look at this on clipping.
This will require some minor calculations on how much to clip, based on the HP/Mana of the Player, but it should be good enough.
This is what it should look like (Clipping and overlaying done in Paint)
UPDATE (Problem solved, using Idea #2!):
Code:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
#SuppressWarnings("serial")
public class TestGraphics extends JFrame implements ActionListener
{
JPanel utilBar = new JPanel();
JButton hpUpBtn = new JButton("HP++");
JButton hpDownBtn = new JButton("HP--");
JButton mpUpBtn = new JButton("MP++");
JButton mpDownBtn = new JButton("MP--");
GraphicsPanel drawingArea = new GraphicsPanel();
TestGraphics()
{
setSize(600, 500);
setLayout(new BorderLayout());
add(utilBar, BorderLayout.NORTH);
utilBar.setLayout(new GridLayout(1, 4));
utilBar.add(hpUpBtn);
utilBar.add(hpDownBtn);
utilBar.add(mpUpBtn);
utilBar.add(mpDownBtn);
add(drawingArea, BorderLayout.CENTER);
hpUpBtn.addActionListener(this);
hpDownBtn.addActionListener(this);
mpUpBtn.addActionListener(this);
mpDownBtn.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == hpUpBtn) {
drawingArea.incHp();
}
else if (e.getSource() == hpDownBtn) {
drawingArea.decHp();
}
else if (e.getSource() == mpUpBtn) {
drawingArea.incMp();
}
else if (e.getSource() == mpDownBtn) {
drawingArea.decMp();
}
System.out.println("Player HP: " + drawingArea.getHp() +
" Player MP: " + drawingArea.getMp());
drawingArea.revalidate();
drawingArea.repaint();
}
public static void main(String[]agrs)
{
new TestGraphics();
}
}
#SuppressWarnings("serial")
class GraphicsPanel extends JPanel {
private static int baseX = 150;
private static int baseY = 150;
private static final int BAR_FULL = 287;
private static final int BAR_EMPTY = 8;
private BufferedImage image1 = null;
private BufferedImage image2 = null;
private BufferedImage image3 = null;
private int playerHp = 100;
private int playerMp = 100;
public GraphicsPanel() {
try {
// All 3 images are the same as those posted in answer
image1 = ImageIO.read(
getClass().getResourceAsStream("/Image1.png"));
image2 = ImageIO.read(
getClass().getResourceAsStream("/Image2.png"));
image3 = ImageIO.read(
getClass().getResourceAsStream("/Image3.png"));
} catch (Exception e) {
e.printStackTrace();
}
}
public void incHp() { playerHp += (playerHp < 100) ? 5 : 0; }
public void decHp() { playerHp -= (playerHp > 0) ? 5 : 0; }
public void incMp() { playerMp += (playerMp < 100) ? 5 : 0; }
public void decMp() { playerMp -= (playerMp > 0) ? 5 : 0; }
public int getHp() { return playerHp; }
public int getMp() { return playerMp; }
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Clear the graphics
g.setClip(null);
g.setColor(Color.BLACK);
g.fillRect(0, 0, 600, 600);
g.drawImage(image1, baseX, baseY, null);
int hpPerc = (int) ((BAR_FULL - BAR_EMPTY) * (playerHp / 100.0));
g.setClip(baseX + BAR_EMPTY + hpPerc, 0, 600, 500);
g.drawImage(image2, baseX, baseY, null);
g.setClip(null);
int mpPerc = (int) ((BAR_FULL - BAR_EMPTY) * (playerMp / 100.0));
g.setClip(baseX + BAR_EMPTY + mpPerc, 0, 600, 500);
g.drawImage(image3, baseX, baseY + 78, null);
g.setClip(null);
}
}

How to slowly change object color from one to another?

I am trying to achieve a scenario where the color of an object changes slowly from one color to another color.
I have the initial color as targetColor and final color as updateColor. The changingSpeed variable is set to 5.
The mechanism that I have to use is
Use getRed(), getGreen(), getBlue() to obtain the red, green and blue color
Compute the difference of color of target bytargetColor–color = [ dr dg db]
Normalize [ dr dg db] by dividing the norm of the vector [ dr dg db] T(Beware of div by zero)
Multiply it by changingSpeed to control the speed in changing the color
Update the color to color + [ dr’ dg’ db’ ]
So far, i have been able to make the following code:
dr=targetColor.getRed()-updateColor.getRed();
dg=targetColor.getGreen()-updateColor.getGreen();
db=targetColor.getBlue()-updateColor.getBlue();
double nrml= Math.sqrt((dr*dr)+(dg*dg)+(db*db));
dr=dr/nrml;
dg=dg/nrml;
db=db/nrml;
How to execute the 4th and 5th steps?
Can please anyone specify how to do this via code example?
Also please check if the above code is correct.
Here is an example the fades the background as you move from component to component:
import java.awt.*;
import java.awt.event.*;
import java.util.Hashtable;
import java.util.ArrayList;
import javax.swing.*;
public class Fader
{
// background color when component has focus
private Color fadeColor;
// steps to fade from original background to fade background
private int steps;
// apply transition colors at this time interval
private int interval;
// store transition colors from orginal background to fade background
private Hashtable backgroundColors = new Hashtable();
/*
* Fade from a background color to the specified color using
* the default of 10 steps at a 50 millisecond interval.
*
* #param fadeColor the temporary background color
*/
public Fader(Color fadeColor)
{
this(fadeColor, 10, 50);
}
/*
* Fade from a background color to the specified color in the
* specified number of steps at the default 5 millisecond interval.
*
* #param fadeColor the temporary background color
* #param steps the number of steps to fade in the color
*/
public Fader(Color fadeColor, int steps)
{
this(fadeColor, steps, 50);
}
/*
* Fade from a background color to the specified color in the
* specified number of steps at the specified time interval.
*
* #param fadeColor the temporary background color
* #param steps the number of steps to fade in the color
* #param intevral the interval to apply color fading
*/
public Fader(Color fadeColor, int steps, int interval)
{
this.fadeColor = fadeColor;
this.steps = steps;
this.interval = interval;
}
/*
* Add a component to this fader.
*
* The fade color will be applied when the component gains focus.
* The background color will be restored when the component loses focus.
*
* #param component apply fading to this component
*/
public Fader add(JComponent component)
{
// Get colors to be used for fading
ArrayList colors = getColors( component.getBackground() );
// FaderTimer will apply colors to the component
new FaderTimer( colors, component, interval );
return this;
}
/*
** Get the colors used to fade this background
*/
private ArrayList getColors(Color background)
{
// Check if the color ArrayList already exists
Object o = backgroundColors.get( background );
if (o != null)
{
return (ArrayList)o;
}
// Doesn't exist, create fader colors for this background
ArrayList colors = new ArrayList( steps + 1 );
colors.add( background );
int rDelta = ( background.getRed() - fadeColor.getRed() ) / steps;
int gDelta = ( background.getGreen() - fadeColor.getGreen() ) / steps;
int bDelta = ( background.getBlue() - fadeColor.getBlue() ) / steps;
for (int i = 1; i < steps; i++)
{
int rValue = background.getRed() - (i * rDelta);
int gValue = background.getGreen() - (i * gDelta);
int bValue = background.getBlue() - (i * bDelta);
colors.add( new Color(rValue, gValue, bValue) );
}
colors.add( fadeColor );
backgroundColors.put(background, colors);
return colors;
}
class FaderTimer implements FocusListener, ActionListener
{
private ArrayList colors;
private JComponent component;
private Timer timer;
private int alpha;
private int increment;
FaderTimer(ArrayList colors, JComponent component, int interval)
{
this.colors = colors;
this.component = component;
component.addFocusListener( this );
timer = new Timer(interval, this);
}
public void focusGained(FocusEvent e)
{
alpha = 0;
increment = 1;
timer.start();
}
public void focusLost(FocusEvent e)
{
alpha = steps;
increment = -1;
timer.start();
}
public void actionPerformed(ActionEvent e)
{
alpha += increment;
component.setBackground( (Color)colors.get(alpha) );
if (alpha == steps || alpha == 0)
timer.stop();
}
}
public static void main(String[] args)
{
// Create test components
JComponent textField1 = new JTextField(10);
textField1.setBackground( Color.YELLOW );
JComponent textField3 = new JTextField(10);
JComponent textField4 = new JTextField(10);
JComponent button = new JButton("Start");
JComponent checkBox = new JCheckBox("Check Box");
JFrame frame = new JFrame("Fading Background");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.getContentPane().add(textField1, BorderLayout.NORTH );
frame.getContentPane().add(button, BorderLayout.SOUTH );
frame.getContentPane().add(textField3, BorderLayout.WEST );
frame.getContentPane().add(textField4, BorderLayout.EAST );
frame.getContentPane().add(checkBox);
// Gradual Fading (using defaults)
// Fader fader = new Fader( new Color(155, 255, 155) );
Fader fader = new Fader( new Color(155, 255, 155), 10, 50 );
fader.add( textField1 );
fader.add( textField3 );
fader.add( checkBox );
// Instant Fading
fader = new Fader( new Color(255, 155, 155), 1, 1 );
fader.add( textField4 );
fader.add( button );
frame.pack();
frame.setVisible( true );
}
}
It uses a Timer to update the backgrounds at the specified interval. It then just interpolates between the two color based on the number of steps desired.
Look at this example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test {
public static void main(String args[]) {
final JFrame frame = new JFrame();
frame.setBounds(100, 100, 300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set some random initial color
final Component comp = frame.getContentPane();
comp.setBackground(new Color(
(float) Math.random(),
(float) Math.random(),
(float) Math.random()));
frame.setVisible(true);
final Timer timer = new Timer(50, new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
final Color targetColor = new Color(30,40,50);
final int changingSpeed = 5;
final Color currentColor = comp.getBackground();
// step 1
int r = currentColor.getRed();
int g = currentColor.getGreen();
int b = currentColor.getBlue();
// step 2
double dr = targetColor.getRed() - r;
double dg = targetColor.getGreen() - g;
double db = targetColor.getBlue() - b;
// step 3
double norm = Math.sqrt(dr*dr+dg*dg+db*db);
if (norm < .001) {
((Timer)(evt.getSource())).stop();
return;
}
dr /= norm;
dg /= norm;
db /= norm;
// step 4
dr *= Math.min(changingSpeed, norm);
dg *= Math.min(changingSpeed, norm);
db *= Math.min(changingSpeed, norm);
// step 5
r += dr;
g += dg;
b += db;
comp.setBackground(new Color(r,g,b));
frame.repaint();
}
});
timer.start();
}
}
A few things to note:
Use a timer to fire the updates. This ensures, they are done in the EventThread, what is mandatory for manipulating Swing GUIs.
Test the norm for beeing very small. This means, your delta is near zero and you should stop updating the color.
Use the minimum of the norm and your changing speed. If your changing speed is high enough, your color will alternate around the target color and your delta will swap the sign forever and the process doesn't terminate. So if your delta is smaller than your changing speed, use the delta!
Don't forget to call repaint, when you are done with manipulating the color.
Yea, instead of using the for loop in line
while(i<=10);
you can actually use your changing speed. Meanwhile your changingSpeed should
be an array of length 3 because the different offset of colors interval i.e
dr, dg, db so that they can be taking care of independently.
like this...
int [] changingSpeed(int []Offset){
int loop = 5;
// 5 means the color should be change 5 times
int [] changeSpeed = new int[3];
changeSpeed[0]= offset[0]/loop;
changeSpeed[1]= offset[1]/loop;
changeSpeed[2]= offset[2]/loop;
return changeSpeed;
}
// your update method will now look like this
updateColor(int [] changeSpeed) throws AWTException{
int dr = changeSpeed[0];
int dg = changeSpeed[1];
int db = changeSpeed[2];
Robot slow = new Robot();
int i=0;
int f= loop; // the number of time you want the color to change
while(i<=f){
slow.delay(1000)
//sleep will sleep for 1000ms
setColor(targetColor.getRed() + dr/10, targetColor.getGreen(),targetColor.getBlue());
setColor(targetColor.getRed(), targetColor.getGreen() + (dg/10),targetColor.getBlue());
setColor(targetColor.getRed(), targetColor.getGreen(),targetColor.getBlue() + db/10);
i++;
}
}
I wouldnt rely on a specific delay time to compute the next step in an animation as this will certainly provide different execution times in different machines, although it might not be a relevant difference.
Instead of a changing speed factor your could use a long representing the animation total time and use a Thread (or another multithreading mecanism) to control the animation lifecycle (such as calculating how much time has passed since the last repaint and whats the percentage of completion for the next iteration).
I don't know if I followed your math instructions.
I created a Swing GUI so i could watch the transition from one color to another.
The Reset Colors button generates a random starting color and a random finishing color. The Start button transforms the bottom panel from the starting color to the finishing color. Each transformation moves about 5 values in either the red, green, or blue dimension, with a delay of 300 milliseconds.
I tended to watch the numbers change, rather than the color. I wanted to make sure that the transformation was fairly even.
Anyway, here's the code. You can use this to model other Swing GUI's. I put all the classes together in one file so I could paste the code here. You should separate the classes into separate files.
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ColorChangeTest implements Runnable {
private static final Insets normalInsets = new Insets(10, 10, 0, 10);
private Color currentColor;
private Color targetColor;
private ColorPanel changingColorPanel;
private ColorPanel currentColorPanel;
private ColorPanel targetColorPanel;
private JLabel changingLabel;
private JLabel currentLabel;
private JLabel targetLabel;
public static void main(String args[]) {
SwingUtilities.invokeLater(new ColorChangeTest());
}
#Override
public void run() {
JFrame frame = new JFrame("Color Change Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(createColorPanel(), BorderLayout.NORTH);
mainPanel.add(createChangingPanel(), BorderLayout.CENTER);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createColorPanel() {
JPanel colorPanel = new JPanel();
setNewColors();
JPanel currentPanel = new JPanel();
currentPanel.setLayout(new BorderLayout());
JPanel currentLabelPanel = new JPanel();
currentLabelPanel.setLayout(new BorderLayout());
JLabel startLabel = new JLabel("Starting Color");
startLabel.setHorizontalAlignment(JLabel.CENTER);
currentLabelPanel.add(startLabel, BorderLayout.NORTH);
currentLabel = new JLabel(getColorString(currentColor));
currentLabel.setHorizontalAlignment(JLabel.CENTER);
currentLabelPanel.add(currentLabel, BorderLayout.SOUTH);
currentPanel.add(currentLabelPanel, BorderLayout.NORTH);
currentColorPanel = new ColorPanel(100, 100, currentColor);
currentPanel.add(currentColorPanel, BorderLayout.CENTER);
colorPanel.add(currentPanel);
JPanel targetPanel = new JPanel();
targetPanel.setLayout(new BorderLayout());
JPanel targetLabelPanel = new JPanel();
targetLabelPanel.setLayout(new BorderLayout());
JLabel finishLabel = new JLabel("Finishing Color");
finishLabel.setHorizontalAlignment(JLabel.CENTER);
targetLabelPanel.add(finishLabel, BorderLayout.NORTH);
targetLabel = new JLabel(getColorString(targetColor));
targetLabel.setHorizontalAlignment(JLabel.CENTER);
targetLabelPanel.add(targetLabel, BorderLayout.SOUTH);
targetPanel.add(targetLabelPanel, BorderLayout.NORTH);
targetColorPanel = new ColorPanel(100, 100, targetColor);
targetPanel.add(targetColorPanel, BorderLayout.CENTER);
colorPanel.add(targetPanel);
colorPanel.add(createButtonPanel());
return colorPanel;
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
int gridy = 0;
JButton resetButton = new JButton("Reset Colors");
resetButton.addActionListener(new ResetColorsListener(this));
addComponent(buttonPanel, resetButton, 0, gridy++, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JButton startButton = new JButton("Start");
startButton.addActionListener(new ColorChangeListener(this));
addComponent(buttonPanel, startButton, 0, gridy++, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
return buttonPanel;
}
private JPanel createChangingPanel() {
JPanel changingPanel = new JPanel();
changingPanel.setLayout(new BorderLayout());
changingLabel = new JLabel(getColorString(currentColor));
changingLabel.setHorizontalAlignment(JLabel.CENTER);
changingPanel.add(changingLabel, BorderLayout.NORTH);
changingColorPanel = new ColorPanel(300, 200, currentColor);
changingPanel.add(changingColorPanel, BorderLayout.CENTER);
return changingPanel;
}
public void setChangingColorLabelText(Color color) {
changingLabel.setText(getColorString(color));
}
public void setNewColors() {
currentColor = getRandomColor();
targetColor = getRandomColor();
}
public void displayNewColors() {
currentLabel.setText(getColorString(currentColor));
targetLabel.setText(getColorString(targetColor));
changingLabel.setText(getColorString(currentColor));
currentColorPanel.setColor(currentColor);
targetColorPanel.setColor(targetColor);
changingColorPanel.setColor(currentColor);
}
public Color getCurrentColor() {
return currentColor;
}
public Color getTargetColor() {
return targetColor;
}
public ColorPanel getChangingColorPanel() {
return changingColorPanel;
}
private Color getRandomColor() {
return new Color((float) Math.random(), (float) Math.random(),
(float) Math.random());
}
private String getColorString(Color color) {
int r = color.getRed();
int g = color.getGreen();
int b = color.getBlue();
return "(" + r + ", " + g + ", " + b + ")";
}
private void addComponent(Container container, Component component,
int gridx, int gridy, int gridwidth, int gridheight, Insets insets,
int anchor, int fill) {
GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
gridwidth, gridheight, 1.0D, 1.0D, anchor, fill, insets, 0, 0);
container.add(component, gbc);
}
public class ColorPanel extends JPanel {
private static final long serialVersionUID = -2894328511698328096L;
private Color color;
public ColorPanel(int width, int height, Color color) {
this.color = color;
this.setPreferredSize(new Dimension(width, height));
}
public void setColor(Color color) {
this.color = color;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillRect(0, 0, getWidth(), getHeight());
}
}
public class ResetColorsListener implements ActionListener {
private ColorChangeTest colorChangeTest;
public ResetColorsListener(ColorChangeTest colorChangeTest) {
this.colorChangeTest = colorChangeTest;
}
#Override
public void actionPerformed(ActionEvent event) {
colorChangeTest.setNewColors();
colorChangeTest.displayNewColors();
}
}
public class ColorChangeListener implements ActionListener {
private ColorChangeTest colorChangeTest;
public ColorChangeListener(ColorChangeTest colorChangeTest) {
this.colorChangeTest = colorChangeTest;
}
#Override
public void actionPerformed(ActionEvent event) {
ColorChange colorChange = new ColorChange(colorChangeTest);
new Thread(colorChange).start();
}
}
public class ColorChange implements Runnable {
private static final long sleepTime = 300L;
private double r, g, b, dr, dg, db;
private int tr, tg, tb, cr, cg, cb;
private ColorChangeTest colorChangeTest;
public ColorChange(ColorChangeTest colorChangeTest) {
this.colorChangeTest = colorChangeTest;
}
#Override
public void run() {
calculateColorChange();
sleep(sleepTime);
while (calculateNextColor()) {
sleep(sleepTime);
}
setColor(colorChangeTest.getTargetColor());
}
private void calculateColorChange() {
double increment = 5D;
// step 1
r = cr = colorChangeTest.getCurrentColor().getRed();
g = cg = colorChangeTest.getCurrentColor().getGreen();
b = cb = colorChangeTest.getCurrentColor().getBlue();
// step 2
tr = colorChangeTest.getTargetColor().getRed();
tg = colorChangeTest.getTargetColor().getGreen();
tb = colorChangeTest.getTargetColor().getBlue();
dr = tr - cr;
dg = tg - cg;
db = tb - cb;
// step 3
double d = Math.sqrt(dr * dr + dg * dg + db * db);
int steps = (int) (d / increment);
dr /= (double) steps;
dg /= (double) steps;
db /= (double) steps;
setColor(new Color(cr, cg, cb));
}
private boolean calculateNextColor() {
// step 5
r += dr;
g += dg;
b += db;
if (isFinished()) {
return false;
} else {
setColor(new Color(round(r), round(g), round(b)));
return true;
}
}
private boolean isFinished() {
return isColorFinished(cr, tr, round(r))
|| isColorFinished(cg, tg, round(g))
|| isColorFinished(cb, tb, round(b));
}
private int round(double value) {
return (int) Math.round(value);
}
private boolean isColorFinished(int original, int target, int current) {
boolean isFinished = false;
if (current < 0 || current > 255) {
isFinished = true;
} else if ((target >= original) && (current >= target)) {
isFinished = true;
} else if ((target <= original) && (current <= target)) {
isFinished = true;
}
return isFinished;
}
private void setColor(final Color color) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
colorChangeTest.getChangingColorPanel().setColor(color);
colorChangeTest.setChangingColorLabelText(color);
}
});
}
private void sleep(long sleepTime) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
}
}
}
}
In order to achieve the act of slowness, it might be a good idea to use the instance of Robot class.
//Method to obtain the offset of the color
static int [] getColorOffset(Color initial, Color final){
int [] colorOffset = new int[3];
colorOffset[0]= final.getRed()-initial.getRed();
colorOffset[1] = final.getGreen()-initial.getGreen();
colorOffset[2]= final.getBlue()-initial.getBlue();
return colorOffset;
}
updateColor(int [] colorOffset) throws AWTException{
int dr = colorOffset[0];
int dg = colorOffset[1];
int db = colorOffset[2];
Robot slow = new Robot();
int i=0;
while(i<=10){
slow.delay(1000)
//sleep will sleep for 1000ms
setColor(targetColor.getRed() + dr/10, targetColor.getGreen(),targetColor.getBlue());
setColor(targetColor.getRed(), targetColor.getGreen() + (dg/10),targetColor.getBlue());
setColor(targetColor.getRed(), targetColor.getGreen(),targetColor.getBlue() + db/10);
i++;
}
}
public static void main(String args[]) throws AWTException{
Color initial = Color.black;
Color final = Color,white;
int [] colorOffset = getColorOffset(initial, final);
updateColor(colorOffset);
}

Categories