Attatched are 2 methods from code that prints out a gird of 25 boxes in jframe and when you click the space bar the boxes fill up one by one with random colors. I need to modify the code so the first 13 boxes show up in shades of red and the next 12 show up only in shades of blue. Also, I need to change the background color to a random color. Thanks.
public void setColor()
{
int r = (int) (Math.random()*256);
int g = (int) (Math.random()*256);
int b = (int) (Math.random()*256);
myColors[clicked] = new Color(r,g,b);
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black);
counter = 0;
for (int x = 0; x < myFloor.length; x++)
{
for (int y = 0; y < myFloor[0].length; y++)
{
if (myColors[counter] != null)
{
for (int i = 0; i < counter+1; i++)
{
setColor();
g2.setColor(myColors[i]);
g2.fill(myFloor[x][y]);
}
}
else
{
g2.setColor(Color.BLACK);
g2.draw(myFloor[x][y]);
}
counter++;
}
}
}
I need to modify the code so the first 13 boxes show up in shades of red and the next 12 show up only in shades of blue. Also, I need to change the background color to a random color. Thanks.
You could...
Use a "color blending" algorithm, which could blend a range of colors together.
The following example basically constructs a color range of dark to light red, light blue to dark blue, split over a normalised range of 0-51% and 52-100%
This has a neat side effect of filling the first 13 squares with shades of red and the last 12 with shades of blue.
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;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private int cols = 5;
private int rows = 5;
private int cellSize = 50;
private ColorGradient colorGradient;
public TestPane() {
colorGradient = new ColorGradient(
new float[]{0f, 0.51f, 0.52f, 1f},
new Color[]{Color.RED.darker(), Color.RED.brighter(), Color.BLUE.brighter(), Color.BLUE.darker()}
);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(cols * cellSize, rows * cellSize);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Color borderColor = new Color(0, 0, 0, 64);
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
float progress = ((row * rows) + col) / (float)(rows * cols);
g2d.setColor(colorGradient.colorAt(progress));
g2d.fillRect(col * cellSize, row * cellSize, cellSize, cellSize);
g2d.setColor(borderColor);
g2d.drawRect(col * cellSize, row * cellSize, cellSize, cellSize);
}
}
g2d.dispose();
}
}
public class ColorGradient {
private float[] fractions;
private Color[] colors;
public ColorGradient(float[] fractions, Color[] colors) {
this.fractions = fractions;
this.colors = colors;
}
public Color colorAt(float progress) {
Color color = null;
if (fractions != null) {
if (colors != null) {
if (fractions.length == colors.length) {
int[] indicies = getFractionIndicies(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;
}
protected int[] getFractionIndicies(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;
}
protected 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;
}
}
}
Oh, and if you want to generate a random color, you could simply use something like...
Random rnd = new Random();
Color color = new Color(rnd.nextInt(255), rnd.nextInt(255), rnd.nextInt(255));
You could...
Define the red and blue color bands separately, and then, based on the cell index, decide which band you're going to use.
This provides more "absolute" control over the decision making process. For example, the following index allows the cells between 0-12 inclusively to draw colors from the red band and 13-24 from blue band.
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;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Range {
private int lower;
private int upper;
public Range(int lower, int upper) {
this.lower = lower;
this.upper = upper;
}
public int getLower() {
return lower;
}
public int getUpper() {
return upper;
}
public boolean contains(int value) {
return value >= getLower() && value <= getUpper();
}
public int getDistance() {
return getUpper() - getLower();
}
public float normalised(int value) {
return (value - getLower()) / (float)getDistance();
}
}
public class TestPane extends JPanel {
private int cols = 5;
private int rows = 5;
private int cellSize = 50;
private ColorBand redColorBand;
private ColorBand blueColorBand;
private Range redRange = new Range(0, 12);
private Range blueRange = new Range(13, 24);
public TestPane() {
redColorBand = new ColorBand(
new float[]{0f, 1f},
new Color[]{Color.RED.darker(), Color.RED.brighter()}
);
blueColorBand = new ColorBand(
new float[]{0f, 1f},
new Color[]{Color.BLUE.brighter(), Color.BLUE.darker()}
);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(cols * cellSize, rows * cellSize);
}
protected Color colorForSqaure(int index) {
if (redRange.contains(index)) {
return redColorBand.colorAt(redRange.normalised(index));
} else if (blueRange.contains(index)) {
return blueColorBand.colorAt(blueRange.normalised(index));
}
return Color.BLACK;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Color borderColor = new Color(0, 0, 0, 64);
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
g2d.setColor(colorForSqaure(((row * rows) + col)));
g2d.fillRect(col * cellSize, row * cellSize, cellSize, cellSize);
g2d.setColor(borderColor);
g2d.drawRect(col * cellSize, row * cellSize, cellSize, cellSize);
}
}
g2d.dispose();
}
}
public class ColorBand {
private float[] fractions;
private Color[] colors;
public ColorBand(float[] fractions, Color[] colors) {
this.fractions = fractions;
this.colors = colors;
}
public Color colorAt(float progress) {
Color color = null;
if (fractions != null) {
if (colors != null) {
if (fractions.length == colors.length) {
int[] indicies = getFractionIndicies(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;
}
protected int[] getFractionIndicies(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;
}
protected 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;
}
}
}
You could...
Predefine the colors up-front
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private int cols = 5;
private int rows = 5;
private int cellSize = 50;
private Color[] colors = new Color [] {
new Color(64, 0, 0),
new Color(79, 0, 0),
new Color(94, 0, 0),
new Color(109, 0, 0),
new Color(124, 0, 0),
new Color(139, 0, 0),
new Color(154, 0, 0),
new Color(169, 0, 0),
new Color(184, 0, 0),
new Color(199, 0, 0),
new Color(214, 0, 0),
new Color(229, 0, 0),
new Color(244, 0, 0),
new Color(0, 0, 64),
new Color(0, 0, 80),
new Color(0, 0, 96),
new Color(0, 0, 112),
new Color(0, 0, 128),
new Color(0, 0, 144),
new Color(0, 0, 160),
new Color(0, 0, 176),
new Color(0, 0, 192),
new Color(0, 0, 208),
new Color(0, 0, 224),
new Color(0, 0, 240),
};
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(cols * cellSize, rows * cellSize);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Color borderColor = new Color(0, 0, 0, 64);
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
g2d.setColor(colors[((row * rows) + col)]);
g2d.fillRect(col * cellSize, row * cellSize, cellSize, cellSize);
g2d.setColor(borderColor);
g2d.drawRect(col * cellSize, row * cellSize, cellSize, cellSize);
}
}
g2d.dispose();
}
}
}
Related
So I add 8 TextFields and wanna set their background colors. My idea is to set the first one to red (255, 0, 0) the last one to blue (0, 0, 255) and the 8 (or any number actually) others gradient between these. I'm trying to figure out how to solve it in terms of "If the 'next' variable is 0 increase this variable with same amount as previous variable is decreasing with"
So it could look like in each iteration:
setBackground(255, 0, 0);
setBackground(191, 63, 0);
setBackground(127, 127, 0);
...
setBackground(0, 0, 255);
Now I wanna try and fit this way of increase and decreasing into a for loop that will iterate n times where n is number of TextFields (now 8 for simplicity). Anyone know if there's a clever solution to this?
MRE:
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Apple{
public Apple(int width, int height) {
SwingUtilities.invokeLater(() -> initGUITest(width, height));
}
public void initGUITest(int width, int height) {
JFrame frame = new JFrame();
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
JPanel panel = new JPanel();
GridLayout gl = new GridLayout(10, 1);
panel.setLayout(gl);
frame.add(panel);
for(int i = 0; i < 8; i++) {
JTextField jtf = new JTextField("Track " + (i + 1));
jtf.setBackground(new Color(255, 0, 0)); //Start color
panel.add(jtf);
}
}
public static void main(String args[]) {
Apple a = new Apple(300, 300);
}
}
Checking if an value is zero and incrementing or decrementing a value from there is inefficient.
There are 2 ways to go about this
Linear
you calculate an blend value which is (i/stepSize) and use that to linearly interpolate between the start and end value as follows
intermediateColor[0]=(int)(start.getRed()+(end.getRed()-start.getRed())*alpha);
intermediateColor[1]=(int)(start.getGreen()+(end.getGreen()-start.getGreen())*alpha);
intermediateColor[2]=(int)(start.getBlue()+(end.getBlue()-start.getBlue())*alpha);
conversion of blend to float is necessary for interpolation to work here is logic
private static void layout1(JFrame frame)
{
Color
start=Color.RED,
end=Color.BLUE;
int[] intermediateColor=new int[3];
int steps=8;
float alpha;
for(int i=0;i<=steps;i++)
{
JTextField field=new JTextField(10);
alpha=((float)i/steps);
intermediateColor[0]=(int)(start.getRed()+(end.getRed()-start.getRed())*alpha);
intermediateColor[1]=(int)(start.getGreen()+(end.getGreen()-start.getGreen())*alpha);
intermediateColor[2]=(int)(start.getBlue()+(end.getBlue()-start.getBlue())*alpha);
field.setBackground(new Color(intermediateColor[0],intermediateColor[1],intermediateColor[2]));
frame.add(field);
}
}
Output :
KeyFrames
An more complicated example involves using key frames where you dynamically change the start and end points based on your i value
Here are the keyframes
int[] checkPoints={0,2,4,6,8};
Color[] colors={Color.RED,Color.GREEN,Color.BLUE,Color.YELLOW,Color.MAGENTA};
what this means is that for
checkboxes 0->2 interpolate between RED & GREEN
checkboxes 3->4 interpolate between GREEN & BLUE
checkboxes 5->6 interpolate between BLUE & YELLOW
checkboxes 7->8 interpolate between YELLOW & MAGENTA
The logic lies in this code
//loop through all checkpoints
for(int j=0;j<checkPoints.length-1;j++)
{
//check if i lies in between these 2 checkpoints
if(i>=checkPoints[j] && i<=checkPoints[j+1])
{
//interpolate between this & the next checkpoint
checkPoint=j;
start=colors[checkPoint];
end=colors[checkPoint+1];
//distance of i from start checkpoint/ total distance between checkpoints
alpha=(float)(i-checkPoints[checkPoint])/(checkPoints[checkPoint+1]-checkPoints[checkPoint]);
}
}
Here is the full code
public class Test
{
public static void main(String[] args)
{
JFrame frame=new JFrame("TEST");
frame.setContentPane(new JPanel(new FlowLayout(FlowLayout.LEADING,10,0)));
layout2(frame);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static void layout1(JFrame frame)
{
Color
start=Color.RED,
end=Color.BLUE;
int[] intermediateColor=new int[3];
int steps=8;
float alpha;
for(int i=0;i<=steps;i++)
{
JTextField field=new JTextField(10);
alpha=((float)i/steps);
intermediateColor[0]=(int)(start.getRed()+(end.getRed()-start.getRed())*alpha);
intermediateColor[1]=(int)(start.getGreen()+(end.getGreen()-start.getGreen())*alpha);
intermediateColor[2]=(int)(start.getBlue()+(end.getBlue()-start.getBlue())*alpha);
field.setBackground(new Color(intermediateColor[0],intermediateColor[1],intermediateColor[2]));
frame.add(field);
}
}
private static void layout2(JFrame frame)
{
int[] checkPoints={0,2,4,6,8};
Color[] colors={Color.RED,Color.GREEN,Color.BLUE,Color.YELLOW,Color.MAGENTA};
int[] intermediateColor=new int[3];
int steps=8;
int checkPoint;
float alpha=0;
Color start=null,end=null;
for(int i=0;i<=steps;i++)
{
JTextField field=new JTextField(10);
for(int j=0;j<checkPoints.length-1;j++)
{
if(i>=checkPoints[j] && i<=checkPoints[j+1])
{
checkPoint=j;
start=colors[checkPoint];
end=colors[checkPoint+1];
alpha=(float)(i-checkPoints[checkPoint])/(checkPoints[checkPoint+1]-checkPoints[checkPoint]);
}
}
intermediateColor[0]=(int)(start.getRed()+(end.getRed()-start.getRed())*alpha);
intermediateColor[1]=(int)(start.getGreen()+(end.getGreen()-start.getGreen())*alpha);
intermediateColor[2]=(int)(start.getBlue()+(end.getBlue()-start.getBlue())*alpha);
field.setBackground(new Color(intermediateColor[0],intermediateColor[1],intermediateColor[2]));
frame.add(field);
}
}
}
Output :
So, any number of ways you might do this, but for me, personally, I'd look towards using some kind of "blending" algorithm which would allow you to establish the "range" of colors you want and then based on some value (ie a index or percentage), generate a color which is blend of those colors (within the range).
For example...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.text.NumberFormat;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
ColorBlender blender = new ColorBlender(new float[] {0, 1}, new Color[] {Color.RED, Color.BLUE});
for (int index = 0; index < 8; index++) {
Color color = blender.blendedColorAt(index / 7f);
System.out.println(color);
JTextField textField = new JTextField(10);
textField.setBackground(color);
add(textField, gbc);
}
}
}
public class ColorBlender {
private float[] fractions;
private Color[] colors;
public ColorBlender(float[] fractions, Color[] colors) {
this.fractions = fractions;
this.colors = colors;
}
public Color blendedColorAt(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;
}
protected 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;
}
protected 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;
}
}
}
Okay, but I want to blend between three colors
Okay, not an issue. Simply add another "stop" and the color for that stop, for example...
ColorBlender blender = new ColorBlender(new float[] {0f, 0.5f, 1f}, new Color[] {Color.RED, Color.YELLOW, Color.BLUE});
will produce...
Want to add more fields? No worries, just change Color color = blender.blendedColorAt(index / 7f); to so that 7f becomes the number of expected fields - 1 (remember, we're starting the index at 0 😉)
Here is a class that can generate a series of colors that can transition from one color to another for a given number of steps.
Simple usage would be:
ColorTransition ct = new ColorTransition(Color.RED, Color.BLUE, 8);
If you need multiple transitions you could do:
ColorTransition ct = new ColorTransition(Color.RED, Color.BLUE, 8);
ct.transitionTo(Color.GREEN, 4);
which would then transition from BLUE to GREEN.
Once all the transition colors are generated you can access them separately:
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class ColorTransition
{
private ArrayList<Color> colors;
public ColorTransition(Color startColor, Color endColor, int steps)
{
colors = new ArrayList<>(steps);
colors.add( startColor );
transitionTo(endColor, steps);
}
public void transitionTo(Color endColor, int steps)
{
Color startColor = colors.get(colors.size() - 1);
float rDelta = endColor.getRed() - startColor.getRed();
float gDelta = endColor.getGreen() - startColor.getGreen();
float bDelta = endColor.getBlue() - startColor.getBlue();
for (int i = 1; i < steps; i++)
{
float stepIncrement = (float)i / (steps - 1);
int rValue = (int)(startColor.getRed() + (rDelta * stepIncrement));
int gValue = (int)(startColor.getGreen() + (gDelta * stepIncrement));
int bValue = (int)(startColor.getBlue() + (bDelta * stepIncrement));
Color color = new Color(rValue, gValue, bValue);
colors.add( color );
}
}
public int size()
{
return colors.size();
}
public Color getColorAt(int index)
{
return colors.get( index );
}
private static void createAndShowGUI()
{
ColorTransition ct = new ColorTransition(Color.RED, Color.BLUE, 8);
// ct.transitionTo(Color.GREEN, 4);
JPanel panel = new JPanel( new GridLayout(0, 1) );
for (int i = 0; i < ct.size(); i++)
{
JTextField textField = new JTextField(25);
textField.setBackground( ct.getColorAt(i) );
panel.add( textField );
}
JFrame frame = new JFrame("Color Transition");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
}
}
I have a BufferedImage whit some shapes drawn down on it, I'm trying to fill those whit a random color; I have made a method whit recursion to do this job, and it does it, but:
It's painfully slow
It requires a lot of stack memory (I had to scale it up to 1GB to avoid problems)
I heard that is always possible to avoid recursion but I can't come up whit a more efficient way to do it, any help would be appreciated
The method returns an ArrayList of int[] which represent all the pixel that I have to fill (then I color those pixel by pixel) It start from a random point that hasn't be colored yet.
I would like to have a result similar to the one that we can have using the instrument "fill" on Microsoft Paint
Here's the code of the method that find all points in a section:
ArrayList<int[]> populatesSection(ArrayList<int[]> section, int[] is) {
int[][] neighbors=new int[4][2];
int i;
neighbors[0][0]=is[0];
neighbors[0][1]=is[1]+1;
neighbors[1][0]=is[0]-1;
neighbors[1][1]=is[1];
neighbors[2][0]=is[0];
neighbors[2][1]=is[1]-1;
neighbors[3][0]=is[0]+1;
neighbors[3][1]=is[1];
toBeColored.remove(contains(toBeColored, is));
section.add(is);
for(i=0;i<neighbors.length;i++)
if(isValid(neighbors[i]) && contains(toBeColored, neighbors[i])>=0 && contains(section, neighbors[i])<0)
populatesSection(section, neighbors[i]);
return section;
}
initial BufferedImage:
colored BufferedImage:
I borrowed the flood method from camickr'a answer and enhanced it to auto flood fill the entire image.
I also took the long flood-related calculations off the EDT by performing it on a SwingWorker:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class FloodFill extends JPanel {
private final BufferedImage image;
private static final Color background = Color.WHITE;
private final Random rnd = new Random();
FloodFill(BufferedImage image) {
this.image = image;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(image.getWidth(), image.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0,0, this);
}
private void autoFloodFill(){
//take long process off the EDT by delegating it to a worker
new FloodFillWorker().execute();
}
private Optional<Point> findBackgrounPoint() {
int backgroundRGB = background.getRGB();
for (int x = 0; x < image.getWidth(); x++) {
for (int y = 0; y < image.getHeight(); y++) {
int imageRGB = image.getRGB(x, y);
if(imageRGB == backgroundRGB)
return Optional.of(new Point(x, y));
}
}
return Optional.empty();
}
private Color randomColor() {
return new Color(rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
}
class FloodFillWorker extends SwingWorker<Void, Void>{
//todo set sleep to 0
private final long SLEEP = 500; //used to slow sown for demo purposed.
#Override
protected Void doInBackground() throws Exception {
Optional<Point> backgroundPoint = findBackgrounPoint();
while(backgroundPoint.isPresent()){
floodFill(backgroundPoint.get(), randomColor());
SwingUtilities.invokeLater(()-> repaint()); //invoke repaint on EDT
backgroundPoint = findBackgrounPoint(); //find next point
Thread.sleep(SLEEP);
}
return null;
}
private void floodFill(Point point, Color replacement) {
int width = image.getWidth();
int height = image.getHeight();
int targetRGB = image.getRGB(point.x, point.y);
int replacementRGB = replacement.getRGB();
Queue<Point> queue = new LinkedList<>();
queue.add( point );
while (!queue.isEmpty()){
Point p = queue.remove();
int imageRGB = image.getRGB(p.x, p.y);
if (imageRGB != targetRGB) { continue; }
//Update the image and check surrounding pixels
image.setRGB(p.x, p.y, replacementRGB);
if (p.x > 0) {
queue.add( new Point(p.x - 1, p.y) );
}
if (p.x +1 < width) {
queue.add( new Point(p.x + 1, p.y) );
}
if (p.y > 0) {
queue.add( new Point(p.x, p.y - 1) );
}
if (p.y +1 < height) {
queue.add( new Point(p.x, p.y + 1) );
}
}
}
}
public static void main(String[] args) throws Exception {
String imageAdress = "https://i.stack.imgur.com/to4SE.png";
BufferedImage image = ImageIO.read(new URL(imageAdress));
FloodFill ff = new FloodFill(image);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(ff);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
ff.autoFloodFill();
}
}
A slowed down demo:
Run it on line
Here is a flood fill method I found on the web a long time ago:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import java.util.LinkedList;
import java.util.Queue;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageUtil
{
public static void floodFill(BufferedImage image, Point point, Color target, Color replacement)
{
int width = image.getWidth() - 1;
int height = image.getHeight() - 1;
int targetRGB = target.getRGB();
int replacementRGB = replacement.getRGB();
Queue<Point> queue = new LinkedList<Point>();
queue.add( point );
while (!queue.isEmpty())
{
Point p = queue.remove();
int imageRGB = image.getRGB(p.x, p.y);
Color imageColor = new Color(imageRGB);
if (imageRGB != targetRGB) continue;
// Update the image and check surrounding pixels
image.setRGB(p.x, p.y, replacementRGB);
if (p.x > 0) queue.add( new Point(p.x - 1, p.y) );
if (p.x < width) queue.add( new Point(p.x + 1, p.y) );
if (p.y > 0) queue.add( new Point(p.x, p.y - 1) );
if (p.y < height) queue.add( new Point(p.x, p.y + 1) );
}
}
public static void main(String[] args)
throws Exception
{
if (args.length != 1) {
System.err.println("ERROR: Pass filename as argument.");
return;
}
String fileName = args[0];
BufferedImage image = ImageIO.read( new File( fileName ) );
JLabel north = new JLabel( new ImageIcon( fileName ) );
JLabel south = new JLabel( new ImageIcon( image ) );
north.addMouseListener( new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
try
{
BufferedImage image = ImageIO.read( new File( fileName ) );
int rgb = image.getRGB(e.getX(), e.getY());
Color target = new Color( rgb );
floodFill(image, e.getPoint(), target, Color.ORANGE);
south.setIcon( new ImageIcon(image) );
}
catch (Exception e2) {}
}
});
JLabel label = new JLabel("Click on above image for flood fill");
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(north, BorderLayout.NORTH);
frame.add(label);
frame.add(south, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
I'll let you decide if it is any more efficient.
You'd typically use a Queue to implement a flood fill, seeded each time you detect a background (in your case white) pixel during a raster scan of the image.
static int[] xd = {-1, 0, 1, 0};
static int[] yd = { 0, 1, 0, -1};
static BufferedImage colorImage(BufferedImage im, Color background, Color[] colors) throws Exception
{
im = ensureImageType(im, BufferedImage.TYPE_INT_ARGB);
int width = im.getWidth();
int height = im.getHeight();
int[] pix = ((DataBufferInt)im.getRaster().getDataBuffer()).getData();
Queue<Integer> q = new LinkedList<>();
for (int i = 0, r = 0; i < width * height; i++)
{
if(pix[i] == background.getRGB())
{
q.add(i);
pix[i] = colors[r++ % colors.length].getRGB();
while(!q.isEmpty())
{
int pos = q.poll();
int x = pos % width;
int y = pos / width;
for(int j = 0; j < 4; j++)
{
int xn = x + xd[j];
if(xn >= 0 && xn < width)
{
int yn = y + yd[j];
if(yn >= 0 && yn < height)
{
int npos = yn * width + xn;
if(pix[npos] == background.getRGB())
{
q.add(npos);
pix[npos] = pix[i];
}
}
}
}
}
}
}
return im;
}
With the helper class:
static BufferedImage ensureImageType(BufferedImage im, int imageType)
{
if (im.getType() != imageType)
{
BufferedImage nim = new BufferedImage(im.getWidth(), im.getHeight(), imageType);
Graphics g = nim.getGraphics();
g.drawImage(im, 0, 0, null);
g.dispose();
im = nim;
}
return im;
}
Test:
Color[] colors = {Color.BLUE, Color.RED, Color.GREEN, Color.ORANGE,
Color.PINK, Color.CYAN, Color.MAGENTA, Color.YELLOW};
BufferedImage im = ImageIO.read(new File("to4SE.png"));
im = colorImage(im, Color.WHITE, colors);
ImageIO.write(im, "png", new File("color.png"));
Output:
I want to make the displayed image repainted for everytime i change the slider position.
I've already made the Every change of the Variable from JSlider is added to the pixel. But i just don't know how to repaint it.
package training;
import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.plaf.SliderUI;
import java.awt.Color;
import java.util.Arrays;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Training extends JPanel {
public BufferedImage image;
double maxw, maxh;
double w, h, ratio;
int warna, red, green, blue, abu, value;
int forT1, forT2;
int[][] bmpR;
int[][] bmpG;
int[][] bmpB;
int[][] alpha;
public Training () {
super();
try {
image = ImageIO.read(new File("src/training/V.jpg"));
}
catch (IOException e) {
//Not handled.
}
maxw = 750;
maxh = 600;
w = image.getWidth();
h = image.getHeight();
bmpR = new int[(int)w][(int)h];
bmpG = new int[(int)w][(int)h];
bmpB = new int[(int)w][(int)h];
if (w > h) {
if (w > maxw) {
ratio = maxw / w;
h = h * ratio; // Reset height to match scaled image
w = w * ratio;
}
}
if (w <= h) {
if (h > maxh) {
ratio = maxh / h;
w = w * ratio; // Reset height to match scaled image
h = h * ratio;
}
}
try {
for( int i = 0; i < w; i++ ) {
for( int j = 0; j < h; j++ ) {
Color c = new Color(image.getRGB(i, j));
bmpR [i][j] = c.getRed();
bmpG [i][j] = c.getGreen();
bmpB [i][j] = c.getBlue();
// alpha = c.getAlpha();
}
}
System.out.println(bmpB[40][40]);
}
catch (Exception e) {
System.out.println("Terjadi kesalahan saat mengambil data pixel");
e.printStackTrace();
return;
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Image i = image.getScaledInstance((int)w, (int)h,Image.SCALE_SMOOTH);
g.drawImage(i, 20, 20, null);
}
public static void main(String[] args) {
final Training ns = new Training();
System.out.println("User dir: " + System.getProperty("user.dir"));
JFrame f = new JFrame("Window");
JPanel p = new Training();
f.setSize(1100, 600);
p.setSize(750, 600);
f.add(p);
JSlider Temp = new JSlider(-50, 50, 0);
Temp.setMajorTickSpacing(10);
Temp.setMinorTickSpacing(1);
Temp.addChangeListener(new ChangeListener () {
public void stateChanged(ChangeEvent evt) {
JSlider Temp = (JSlider) evt.getSource();
if (Temp.getValueIsAdjusting()) {
ns.value = Temp.getValue();
for(ns.forT1 = 0; ns.forT1 < ns.w; ns.forT1++ ) {
for(ns.forT2 = 0; ns.forT2 < ns.h; ns.forT2++ ) {
ns.bmpB[ns.forT1][ns.forT2] = ns.bmpB[ns.forT1][ns.forT2] - ns.value;
if (ns.bmpB[ns.forT1][ns.forT2] > 255) {
ns.bmpB[ns.forT1][ns.forT2] = 255;
}
if (ns.bmpB[ns.forT1][ns.forT2] < 0) {
ns.bmpB[ns.forT1][ns.forT2] = 0;
}
ns.bmpR[ns.forT1][ns.forT2] = ns.bmpR[ns.forT1][ns.forT2] + ns.value;
if (ns.bmpR[ns.forT1][ns.forT2] > 255) {
ns.bmpR[ns.forT1][ns.forT2] = 255;
}
if (ns.bmpR[ns.forT1][ns.forT2] < 0) {
ns.bmpR[ns.forT1][ns.forT2] = 0;
}
}
}
}
ns.repaint();
}
});
f.add(Temp, BorderLayout.EAST);
f.setVisible(true);
}
}
Did i misplaced the ChangeListener or should i put paintComponent method after the change listener happens?
The random indentation of your code is making it hard to figure out exactly what's going on, but I don't see repaint() anywhere inside your ChangeListener. You need to use repaint() to trigger the repainting of your component.
I have a JLayeredPane that has four layers:
JPanel set as a background
Grid of JPanels each holding a JLabel
Grid of JPanels each holding several JLabels that are only set to visible if the label in the panel below is empty
A custom component that is only used to override the paintComponent() method to draw over everything below
For some reason if I change the background colour of the labels in layer 3 and then draw to layer 4, the labels in layer 3 are painted over the graphics painted in level 4. I have tried to set ignoreRepaint() on various components as well as playing around with the opacity and code structure but all to no avail.
Does anyone know how to prevent this from happening?
I won't attach the source code because the project is quite large but I've attached an example that runs as a stand alone program and demonstrates my problem when you hit the "add arrow" button.
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class GraphicsTest {
#SuppressWarnings("serial")
class Painter extends JComponent {
public Painter(int x, int y) {
setBounds(0, 0, x, y);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
private static final int CELL_SIZE = 40;
private static final int NOTE_SIZE = 20;
private JFrame frame;
private static JButton test;
private static JButton clear;
private static JLayeredPane pane = new JLayeredPane();
private static JPanel back = new JPanel();
private static JPanel[][] cellPanels = new JPanel[10][10];
private static JLabel[][] cells = new JLabel[10][10];
private static JPanel[][] notePanels = new JPanel[10][10];
private static JLabel[][][] notes = new JLabel[10][10][4];
private static Painter painter;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GraphicsTest window = new GraphicsTest();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GraphicsTest() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setSize(600, 700);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
pane.setBounds(50, 50, 500, 500);
pane.setLayout(null);
frame.getContentPane().add(pane);
back.setBounds(0, 0, 500, 500);
back.setBackground(Color.BLACK);
pane.add(back, new Integer(100));
for (int i = 0; i < 10; i++) {
for (int k = 0; k < 10; k++) {
String text = "";
if ((i % 2) == 1 && (k % 2) == 1) text = (i + k) + "";
cellPanels[i][k] = new JPanel();
cellPanels[i][k].setBounds(k * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE);
cellPanels[i][k].setBackground(Color.WHITE);
cellPanels[i][k].setBorder(new LineBorder(Color.BLACK, 1));
cells[i][k] = new JLabel(text);
cells[i][k].setBounds(0, 0, CELL_SIZE, CELL_SIZE);
cells[i][k].setOpaque(false);
cellPanels[i][k].add(cells[i][k]);
pane.add(cellPanels[i][k], new Integer(200));
}
}
boolean display;
for (int i = 0; i < 10; i++) {
for (int k = 0; k < 10; k++) {
if ((i % 2) == 0 && (k % 2) == 0) {
display = true;
} else {
display = false;
}
notePanels[i][k] = new JPanel();
notePanels[i][k].setBounds(k * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE);
notePanels[i][k].setBackground(Color.WHITE);
notePanels[i][k].setBorder(new LineBorder(Color.BLACK, 1));
notePanels[i][k].setLayout(null);
for (int m = 0; m < 2; m++) {
for (int p = 0; p < 2; p++) {
notes[i][k][(m * 2) + p] = new JLabel(30 + "");
notes[i][k][(m * 2) + p].setBounds(m * NOTE_SIZE, p * NOTE_SIZE, NOTE_SIZE, NOTE_SIZE);
notes[i][k][(m * 2) + p].setOpaque(true);
notePanels[i][k].add(notes[i][k][(m * 2) + p]);
}
}
if (display) {
notePanels[i][k].setVisible(true);
} else {
notePanels[i][k].setVisible(false);
}
pane.add(notePanels[i][k], new Integer(300));
}
}
painter = new Painter(500, 500);
pane.add(painter, new Integer(400));
test = new JButton("Add Arrow");
test.setBounds(50, 600, 100, 25);
test.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
highlightNotes();
Arrow.drawArrow(painter.getGraphics(), 20, 20, 400, 400, 20, 30, 40, Color.BLACK, Color.GREEN);
}
});
frame.getContentPane().add(test);
clear = new JButton("Clear");
clear.setBounds(175, 600, 100, 25);
clear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
painter.repaint();
}
});
frame.getContentPane().add(clear);
}
private static void highlightNotes() {
for (int i = 0; i < 10; i++) {
for (int k = 0; k < 10; k++) {
for (int n = 0; n < 4; n++) {
notes[i][k][n].setBackground(Color.BLUE);
}
}
}
}
static class Arrow {
public static void drawArrow(Graphics g, int tailx, int taily, int headx, int heady,
int shaftw, int headw, int headh, Color outline, Color fill) {
if ((shaftw % 2) == 0) {
shaftw--;
}
if ((headw % 2) == 0) {
headw--;
}
if ((headh % 2) == 0) {
headh--;
}
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
double length = Math.sqrt((double) (((headx - tailx) * (headx - tailx))
+ ((heady - taily) * (heady - taily))));
int tailLength = (int) (length - headw) + 1;
double theta = Math.atan2(heady - taily, headx - tailx);
Point point1 = new Point(0, -(shaftw / 2));
point1 = getTransPoint(point1, theta);
point1.x += tailx;
point1.y += taily;
Point point2 = new Point(tailLength, -(shaftw / 2));
point2 = getTransPoint(point2, theta);
point2.x += tailx;
point2.y += taily;
Point point3 = new Point(tailLength, -(headw / 2));
point3 = getTransPoint(point3, theta);
point3.x += tailx;
point3.y += taily;
Point point4 = new Point((int) length, 0);
point4 = getTransPoint(point4, theta);
point4.x += tailx;
point4.y += taily;
Point point5 = new Point(tailLength, (headw / 2));
point5 = getTransPoint(point5, theta);
point5.x += tailx;
point5.y += taily;
Point point6 = new Point(tailLength, (shaftw / 2));
point6 = getTransPoint(point6, theta);
point6.x += tailx;
point6.y += taily;
Point point7 = new Point(0, (shaftw / 2));
point7 = getTransPoint(point7, theta);
point7.x += tailx;
point7.y += taily;
//Create arrow at tail coordinates passed in
Polygon arrow = new Polygon();
arrow.addPoint(point1.x, point1.y);
arrow.addPoint(point2.x, point2.y);
arrow.addPoint(point3.x, point3.y);
arrow.addPoint(point4.x, point4.y);
arrow.addPoint(point5.x, point5.y);
arrow.addPoint(point6.x, point6.y);
arrow.addPoint(point7.x, point7.y);
//Draw and fill the arrow
g2.setColor(fill);
g2.fillPolygon(arrow);
g2.setColor(outline);
g2.drawPolygon(arrow);
}
private static Point getTransPoint(Point point, double theta) {
int x = (int) ((point.x * Math.cos(theta)) - (point.y * Math.sin(theta)));
int y = (int) ((point.y * Math.cos(theta)) + (point.x * Math.sin(theta)));
return new Point(x, y);
}
}
}
I'm trying to make a Connect Four Game in Java by using user input and drawing panel. Two people switch off turns typing the column they want their piece to go in. I'm having trouble making it so discs already placed stay on the board the next turn (because the a new drawing panel pops up with the updated board each time)(we tried using GUI but failed). I am also having trouble switching off turns and making the color change each time. Thank you so much, here is what I have so far.
import java.util.*;
import java.awt.*;
public class ConnectFour{
public static void main(String[] args){
Scanner console = new Scanner(System.in);
char [][] board = new char [7][6];
for (int i = 0; i< 7; i++){
for (int j= 0; j< 6; j++){
board[i][j] = ' ';
}
}
boolean isBlack = true ; //black discs turn
boolean isRed = false ; //red discs turn
boolean playersTurn = true ;
while (playersTurn){
if (isBlack == true ){
System.out.println("Black's Turn");
}
else {
System.out.println("Red's Turn");
}
System.out.print("Choose a column to place your disk (1-7): ");
int column = console.nextInt()-1;
if (column < 0 || column > 7) { //while loop?
System.out.print( "Column needs to be within 1-7"); //try catch?
}
drawBoard(column, board, isBlack, isRed);
// connectedFour(board);
// playersTurn = !playersTurn;
}
// isBlack = !isBlack; INVERT WHOSE TURN IT IS!!! unreachable statement??
}
public static void drawBoard(int column, char [][] board, boolean isBlack, boolean isRed) {
DrawingPanel panel = new DrawingPanel(550,550);
int rowAvailable;
Graphics g = panel.getGraphics();
g.drawLine(0,0,0,500);
g.drawLine(0,0,500,0);
g.drawLine(500,0,500,427);
g.drawLine(0,427,500,427);
for (int i = 0; i< 6; i++){
for (int j= 0; j<= 6; j++){
g.setColor(Color.YELLOW);
g.fillRect(j*71,i*71,71,71);
g.setColor(Color.WHITE);
g.fillOval(j*71,i*71,71,71);
}
}
int x = 0;
int row = 5;
while (board[column][row-x] != ' '){
x++;
}
row = 5-x;
if (isBlack == true) {
g.setColor(Color.BLACK);
board[column][row-x] = 'b';
}
else {
g.setColor(Color.RED);
board[column][row-x] = 'r';
}
// I KNOW THIS FOR LOOP DOES NOT WORK SUCCESSFULLY
for (int i = 0; i< 6; i++){
for (int j= 0; j<= 6; j++){
if(board[i][j] != 'b'){
g.fillOval((i * 71),j*71, 71,71);
}
}
}
// g.fillOval((column * 71),row*71, 71,71); //number 142 is just a test
//board[i][j] = WHOSE TURN IT IS (to update array)
// if(isBlack){
// board[column][row] = 'b';
// }
// else{
// board[column][row] = 'r';
// }
}
//get whose turn it is as parameter?? a color string? boolean?
public static boolean connectedFour( char[][] board){
int verticalCount = 0;
for (int i = 0; i< 6; i++){ //goes down each column //EXCEPTION HERE BECAUSE 0
for( int j=0; j<=6; j++){
if (board[i][j]== board[i-1][j]){
verticalCount ++;
}
}
}
int horizontalCount = 0;
for (int i =0; i<=6; i++){
for (int j =0; j<6; j++){
if (board[i][j-1] == board[i][j]){
horizontalCount++;
}
}
}
int diagonalCount = 0;
//get diagonal here
if (verticalCount >= 4 || horizontalCount >= 4|| diagonalCount >=4){
return true ; //return who the winner is. String?
//
}
else {
return false ;
}
}
}
Don't mix console based input with GUI output, these are two different user paradigms which require different work flows and approaches to manage
Don't use getGraphics, this is not how painting works. Swing has a defined paint process which you should use to ensure you are been notified when an update needs to be performed. See Painting in AWT and Swing and Performing Custom Painting for more details.
The following is a very basic example of how you might work with the API, instead of against it.
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.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.RoundRectangle2D;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ConnectFour {
public static void main(String[] args) {
new ConnectFour();
}
public ConnectFour() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new GamePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public enum Player {
RED, BLUE, NONE;
}
public class GamePane extends JPanel {
private BoardPane boardPane;
private JLabel label;
private Player player = null;
public GamePane() {
setLayout(new BorderLayout());
boardPane = new BoardPane();
add(boardPane);
label = new JLabel("...");
label.setHorizontalAlignment(JLabel.CENTER);
label.setForeground(Color.WHITE);
label.setOpaque(true);
label.setBorder(new EmptyBorder(10, 10, 10, 10));
add(label, BorderLayout.NORTH);
updatePlayer();
boardPane.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
updatePlayer();
}
});
}
protected void updatePlayer() {
String text = "...";
Color color = null;
if (player == null || player.equals(Player.BLUE)) {
player = Player.RED;
text = "Red";
color = Color.RED;
} else if (player.equals(Player.RED)) {
player = Player.BLUE;
text = "Blue";
color = Color.BLUE;
}
label.setText(text);
label.setBackground(color);
boardPane.setPlayer(player);
}
}
public class BoardPane extends JPanel {
private Player[][] board;
private Player player;
private int hoverColumn = -1;
public BoardPane() {
board = new Player[8][8];
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
board[row][col] = Player.NONE;
}
}
MouseAdapter mouseHandler = new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
hoverColumn = getColumnAt(e.getPoint());
repaint();
}
#Override
public void mouseExited(MouseEvent e) {
hoverColumn = -1;
repaint();
}
#Override
public void mouseClicked(MouseEvent e) {
if (hoverColumn > -1) {
addPieceTo(hoverColumn);
repaint();
}
}
};
addMouseMotionListener(mouseHandler);
addMouseListener(mouseHandler);
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
public void removeChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
public void setPlayer(Player player) {
this.player = player;
}
protected void addPieceTo(int col) {
boolean added = false;
if (col >= 0 && col < board[0].length) {
for (int row = 0; row < board.length; row++) {
if (board[row][col] != Player.NONE) {
if (row >= 0) {
board[row - 1][col] = player;
added = true;
}
break;
}
}
}
if (!added) {
if (board[0][col] == Player.NONE) {
board[board.length - 1][col] = player;
added = true;
}
}
if (added) {
fireStateChanged();
}
repaint();
}
protected void fireStateChanged() {
ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
if (listeners != null && listeners.length > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
protected int getColumnAt(Point p) {
int size = Math.min(getWidth() - 1, getHeight() - 1);
int xOffset = (getWidth() - size) / 2;
int yOffset = (getHeight() - size) / 2;
int padding = getBoardPadding();
int diameter = (size - (padding * 2)) / 8;
int xPos = p.x - xOffset;
int column = xPos / diameter;
return Math.min(Math.max(0, column), board[0].length - 1);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected int getBoardPadding() {
return 10;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
int size = Math.min(getWidth() - 1, getHeight() - 1);
int xOffset = (getWidth() - size) / 2;
int yOffset = (getHeight() - size) / 2;
g2d.fill(new RoundRectangle2D.Double(xOffset, yOffset, size, size, 20, 20));
int padding = getBoardPadding();
int diameter = (size - (padding * 2)) / 8;
for (int row = 0; row < board.length; row++) {
int yPos = (yOffset + padding) + (diameter * row);
for (int col = 0; col < board[row].length; col++) {
int xPos = (xOffset + padding) + (diameter * col);
switch (board[row][col]) {
case RED:
g2d.setColor(Color.RED);
break;
case BLUE:
g2d.setColor(Color.BLUE);
break;
default:
g2d.setColor(getBackground());
break;
}
g2d.fill(new Ellipse2D.Double(xPos, yPos, diameter, diameter));
}
}
if (hoverColumn > -1) {
int yPos = (yOffset + padding) + (diameter * 0);
int xPos = (xOffset + padding) + (diameter * hoverColumn);
if (player != null) {
switch (player) {
case RED:
g2d.setColor(Color.RED);
break;
case BLUE:
g2d.setColor(Color.BLUE);
break;
default:
g2d.setColor(getBackground());
break;
}
g2d.fill(new Ellipse2D.Double(xPos, yPos, diameter, diameter));
}
}
g2d.dispose();
}
}
}