Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
How can I produce 5 x 7 dot matrix type digits for a clock project?
Here's an example of what I'm looking for.
I manually coded the position of each dot in each digit.
Is there a better way to create dot matrix digits?
By better I mean easier to code, easier to verify, makes use of existing fonts or other components, or anything else an experienced Swing developer might consider as an important consideration.
The rest of this question is the context for the naysayers that claim I didn't put enough effort into formulating my question.
Since I'm providing an answer to this question, I'm not posting fake bad code in the question. Sure, we appreciate it when people show their efforts. The code and text in my answer should supplement the question, in my opinion.
A few days ago, as I'm writing this, someone posted a question about making a clock with dot-matrix digits. The person posting the question provided code and a picture of what they had created. The person had created a BufferedImage where they had hardcoded the position of each square dot in his 4 x 7 dot matrix digits.
I was impressed with how much work the person had put into his BufferedImage, so I went off to my Eclipse to figure out how to generalize what he had done.
While I was away, people commented and closed his question. By the time I got back with my answer, the person had deleted his question.
Since I had what I thought was a good answer, I searched for an appropriate question. When I didn't find an appropriate question, I created a question.
Sure, I focused more on my answer than my question. Silly me, I thought that the answer would help provide context for the question.
Well, I hope that this explanation sheds some more light on why I thought this topic was important enough to create a question and ask for answers.
Unfortunately, you have to code the position of each dot in each digit.
However, you can do this in a flexible way.
Here's what I mean. A 5 x 7 dot matrix digit can be represented as a two-dimensional int array. It could also be represented as a boolean array, but a matrix of 0 and 1 values is easier to visually verify.
As an example. here's a method to code the zero digit. You can see that the ones create a visual outline that can be easily verified.
private int[][] defineZeroMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 0, 1, 1, 1, 0 };
matrix[1] = new int[] { 1, 0, 0, 0, 1 };
matrix[2] = new int[] { 1, 0, 0, 0, 1 };
matrix[3] = new int[] { 1, 0, 0, 0, 1 };
matrix[4] = new int[] { 1, 0, 0, 0, 1 };
matrix[5] = new int[] { 1, 0, 0, 0, 1 };
matrix[6] = new int[] { 0, 1, 1, 1, 0 };
return matrix;
}
It took me about 15 minutes to code all of the dot matrix digit matrices.
It's possible to code a dot matrix digit using a sparse matrix. Unfortunately, that idea leads to more code that's visually harder to verify.
Here's an example of the dot matrix digit two coded as a sparse matrix of coordinates.
private Point[] defineTwoCoordinates() {
Point[] array = new Point[14];
array[0] = new Point(0, 1);
array[1] = new Point(1, 0);
array[2] = new Point(2, 0);
array[3] = new Point(3, 0);
array[4] = new Point(4, 1);
array[5] = new Point(4, 2);
array[6] = new Point(3, 3);
array[7] = new Point(2, 4);
array[8] = new Point(1, 5);
array[9] = new Point(0, 6);
array[10] = new Point(1, 6);
array[11] = new Point(2, 6);
array[12] = new Point(3, 6);
array[13] = new Point(4, 6);
return array;
}
After we've coded all of the digit matrices, we'll create an array of matrices.
private int[][][] matrices;
The leftmost index is the digit, from 0 to 9. The second index is the row of the digit matrix. The third index is the column of the digit matrix.
Finally, we extend a JPanel and override the paintComponent method to actually paint the dot matrix digit.
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(dotColor);
for (int row = 0; row < matrices[digit].length; row++) {
for (int column = 0; column < matrices[digit][row].length; column++) {
if (matrices[digit][row][column] != 0) {
int x = margin + column * pixelWidth;
int y = margin + row * pixelWidth;
g.fillOval(x, y, dotWidth, dotWidth);
}
}
}
}
Here's a complete runnable example of how you would create a dot matrix digit panel by extending a JPanel, and use several dot matrix digit panels to create whatever GUI you want.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class DotMatrixDigits implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new DotMatrixDigits());
}
#Override
public void run() {
JFrame frame = new JFrame("Dot Matrix Digits");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(defineTopPanel(), BorderLayout.BEFORE_FIRST_LINE);
frame.add(defineBottomPanel(), BorderLayout.AFTER_LAST_LINE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel defineTopPanel() {
JPanel panel = new JPanel();
panel.add(new DotMatrixDigit(0, Color.YELLOW, Color.BLACK));
panel.add(new DotMatrixDigit(1, Color.YELLOW, Color.BLACK));
panel.add(new DotMatrixDigit(2, Color.YELLOW, Color.BLACK));
panel.add(new DotMatrixDigit(3, Color.YELLOW, Color.BLACK));
panel.add(new DotMatrixDigit(4, Color.YELLOW, Color.BLACK));
return panel;
}
private JPanel defineBottomPanel() {
JPanel panel = new JPanel();
panel.add(new DotMatrixDigit(5, Color.YELLOW, Color.BLACK));
panel.add(new DotMatrixDigit(6, Color.YELLOW, Color.BLACK));
panel.add(new DotMatrixDigit(7, Color.YELLOW, Color.BLACK));
panel.add(new DotMatrixDigit(8, Color.YELLOW, Color.BLACK));
panel.add(new DotMatrixDigit(9, Color.YELLOW, Color.BLACK));
return panel;
}
/**
* <p>
* The <code>DotMatrixDigit</code> class creates a dot-matrix digit panel by
* extending <code>JPanel</code>. The dot matrix digit is 5 positions across and
* 7 positions down. The size of the dot and distance between dots are defined
* in the constructor of this class. The shape of the dot is determined in the
* <code>paintComponent</code> method.
* </p>
*
* #author Gilbert G. Le Blanc
* #version 1.8 - 20 October 2020
*
* #see JPanel
* #see Color
*/
public class DotMatrixDigit extends JPanel {
private static final long serialVersionUID = 1L;
/** int field to hold the digit to display **/
private int digit;
/** int field to hold the width of the dot in pixels **/
private int dotWidth;
/** int field to hold the distance between the
* top left corner of the dots in pixels **/
private int pixelWidth;
/** int field to hold the margin size in
* pixels surrounding the digit **/
private int margin;
private final Color dotColor;
private int[][][] matrices;
/**
* <p>
* This constructor creates a dot matrix digit panel. The preferred size of the
* panel is determined by the pixel width of each dot, including the space
* between the dots.
* </p>
*
* #param digit - The initial digit to display from 0 through 9.
* #param dotColor - The <code>Color</code> of the dots.
* #param backgroundColor - The background <code>Color</code> of the dot matrix
* digit panel.
*
*/
public DotMatrixDigit(int digit, Color dotColor, Color backgroundColor) {
this.digit = digit;
this.dotColor = dotColor;
this.dotWidth = 10;
this.pixelWidth = 15;
this.margin = dotWidth;
this.matrices = defineDigitMatricies();
int width = 4 * pixelWidth + dotWidth + margin + margin;
int height = 6 * pixelWidth + dotWidth + margin + margin;
this.setBackground(backgroundColor);
this.setPreferredSize(new Dimension(width, height));
}
private int[][][] defineDigitMatricies() {
int[][][] matrices = new int[10][][];
matrices[0] = defineZeroMatrix();
matrices[1] = defineOneMatrix();
matrices[2] = defineTwoMatrix();
matrices[3] = defineThreeMatrix();
matrices[4] = defineFourMatrix();
matrices[5] = defineFiveMatrix();
matrices[6] = defineSixMatrix();
matrices[7] = defineSevenMatrix();
matrices[8] = defineEightMatrix();
matrices[9] = defineNineMatrix();
return matrices;
}
private int[][] defineZeroMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 0, 1, 1, 1, 0 };
matrix[1] = new int[] { 1, 0, 0, 0, 1 };
matrix[2] = new int[] { 1, 0, 0, 0, 1 };
matrix[3] = new int[] { 1, 0, 0, 0, 1 };
matrix[4] = new int[] { 1, 0, 0, 0, 1 };
matrix[5] = new int[] { 1, 0, 0, 0, 1 };
matrix[6] = new int[] { 0, 1, 1, 1, 0 };
return matrix;
}
private int[][] defineOneMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 0, 0, 1, 0, 0 };
matrix[1] = new int[] { 0, 1, 1, 0, 0 };
matrix[2] = new int[] { 1, 0, 1, 0, 0 };
matrix[3] = new int[] { 0, 0, 1, 0, 0 };
matrix[4] = new int[] { 0, 0, 1, 0, 0 };
matrix[5] = new int[] { 0, 0, 1, 0, 0 };
matrix[6] = new int[] { 1, 1, 1, 1, 1 };
return matrix;
}
private int[][] defineTwoMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 0, 1, 1, 1, 0 };
matrix[1] = new int[] { 1, 0, 0, 0, 1 };
matrix[2] = new int[] { 0, 0, 0, 0, 1 };
matrix[3] = new int[] { 0, 0, 0, 1, 0 };
matrix[4] = new int[] { 0, 0, 1, 0, 0 };
matrix[5] = new int[] { 0, 1, 0, 0, 0 };
matrix[6] = new int[] { 1, 1, 1, 1, 1 };
return matrix;
}
private int[][] defineThreeMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 0, 1, 1, 1, 0 };
matrix[1] = new int[] { 1, 0, 0, 0, 1 };
matrix[2] = new int[] { 0, 0, 0, 0, 1 };
matrix[3] = new int[] { 0, 0, 1, 1, 0 };
matrix[4] = new int[] { 0, 0, 0, 0, 1 };
matrix[5] = new int[] { 1, 0, 0, 0, 1 };
matrix[6] = new int[] { 0, 1, 1, 1, 0 };
return matrix;
}
private int[][] defineFourMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 0, 0, 0, 1, 0 };
matrix[1] = new int[] { 0, 0, 1, 1, 0 };
matrix[2] = new int[] { 0, 1, 0, 1, 0 };
matrix[3] = new int[] { 1, 0, 0, 1, 0 };
matrix[4] = new int[] { 1, 1, 1, 1, 1 };
matrix[5] = new int[] { 0, 0, 0, 1, 0 };
matrix[6] = new int[] { 0, 0, 0, 1, 0 };
return matrix;
}
private int[][] defineFiveMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 1, 1, 1, 1, 1 };
matrix[1] = new int[] { 1, 0, 0, 0, 0 };
matrix[2] = new int[] { 1, 0, 0, 0, 0 };
matrix[3] = new int[] { 1, 1, 1, 1, 0 };
matrix[4] = new int[] { 0, 0, 0, 0, 1 };
matrix[5] = new int[] { 1, 0, 0, 0, 1 };
matrix[6] = new int[] { 0, 1, 1, 1, 0 };
return matrix;
}
private int[][] defineSixMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 0, 1, 1, 1, 0 };
matrix[1] = new int[] { 1, 0, 0, 0, 1 };
matrix[2] = new int[] { 1, 0, 0, 0, 0 };
matrix[3] = new int[] { 1, 1, 1, 1, 0 };
matrix[4] = new int[] { 1, 0, 0, 0, 1 };
matrix[5] = new int[] { 1, 0, 0, 0, 1 };
matrix[6] = new int[] { 0, 1, 1, 1, 0 };
return matrix;
}
private int[][] defineSevenMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 1, 1, 1, 1, 1 };
matrix[1] = new int[] { 0, 0, 0, 0, 1 };
matrix[2] = new int[] { 0, 0, 0, 0, 1 };
matrix[3] = new int[] { 0, 0, 0, 1, 0 };
matrix[4] = new int[] { 0, 0, 1, 0, 0 };
matrix[5] = new int[] { 0, 0, 1, 0, 0 };
matrix[6] = new int[] { 0, 0, 1, 0, 0 };
return matrix;
}
private int[][] defineEightMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 0, 1, 1, 1, 0 };
matrix[1] = new int[] { 1, 0, 0, 0, 1 };
matrix[2] = new int[] { 1, 0, 0, 0, 1 };
matrix[3] = new int[] { 0, 1, 1, 1, 0 };
matrix[4] = new int[] { 1, 0, 0, 0, 1 };
matrix[5] = new int[] { 1, 0, 0, 0, 1 };
matrix[6] = new int[] { 0, 1, 1, 1, 0 };
return matrix;
}
private int[][] defineNineMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 0, 1, 1, 1, 0 };
matrix[1] = new int[] { 1, 0, 0, 0, 1 };
matrix[2] = new int[] { 1, 0, 0, 0, 1 };
matrix[3] = new int[] { 0, 1, 1, 1, 1 };
matrix[4] = new int[] { 0, 0, 0, 0, 1 };
matrix[5] = new int[] { 1, 0, 0, 0, 1 };
matrix[6] = new int[] { 0, 1, 1, 1, 0 };
return matrix;
}
/**
* <p>
* The <code>setDigit</code> method sets the digit to display and repaints the
* panel.
* </p>
*
* #param digit - A digit from 0 through 9.
*/
public void setDigit(int digit) {
this.digit = digit;
this.repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(dotColor);
for (int row = 0; row < matrices[digit].length; row++) {
for (int column = 0; column < matrices[digit][row].length; column++) {
if (matrices[digit][row][column] != 0) {
int x = margin + column * pixelWidth;
int y = margin + row * pixelWidth;
g.fillOval(x, y, dotWidth, dotWidth);
}
}
}
}
}
}
Is there a better way to create dot matrix digits?
Don't know if 'better' (depends on whether effort or accuracy is the primary consideration) but there is a way to calculate the array based on the Shape of the digit.
Here is the result for a (bold) version of the default Monospaced font on this machine.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.font.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class FontToDotMatrix {
private JComponent ui = null;
Shape[] shapes = new Shape[10];
JComboBox fonts;
PixelArray[] pixelArrays = new PixelArray[10];
FontToDotMatrix() {
initUI();
}
public final void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
String[] fontFamilies = GraphicsEnvironment.
getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
fonts = new JComboBox(fontFamilies);
ui.add(fonts, BorderLayout.PAGE_START);
JPanel digitPanel = new JPanel(new GridLayout(2, 5, 4, 4));
ui.add(digitPanel);
digitPanel.setBackground(Color.RED);
for (int ii = 0; ii < 10; ii++) {
PixelArray pixelArray = new PixelArray();
pixelArrays[ii] = pixelArray;
digitPanel.add(pixelArray);
}
ActionListener listener = (ActionEvent e) -> {
for (int ii = 0; ii < 10; ii++) {
pixelArrays[ii].updatePixels(getLitPixels("" + ii));
}
};
fonts.addActionListener(listener);
fonts.setSelectedItem("Monospaced");
}
private Shape moveShapeToCenter(Shape shape) {
int w = 50;
int h = 70;
Rectangle2D b = shape.getBounds2D();
double xOff = -b.getX() + ((w - b.getWidth()) / 2d);
double yOff = -b.getY() + ((h - b.getHeight()) / 2d);
AffineTransform move = AffineTransform.getTranslateInstance(xOff, yOff);
return move.createTransformedShape(shape);
}
private boolean[][] getLitPixels(String digit) {
Font font = new Font(fonts.getSelectedItem().toString(), Font.BOLD, 70);
Shape shape = getShapeOfCharacter(font, digit);
Rectangle2D rect = shape.getBounds2D();
double h = rect.getHeight();
double ratio = 70d / h;
AffineTransform scale = AffineTransform.getScaleInstance(ratio, ratio);
shape = moveShapeToCenter(scale.createTransformedShape(shape));
boolean[][] bools = new boolean[5][7];
for (int yy = 0; yy < 7; yy++) {
for (int xx = 0; xx < 5; xx++) {
Point point = new Point((xx * 10) + 5, (yy * 10) + 5);
bools[xx][yy] = shape.contains(point);
}
}
return bools;
}
public JComponent getUI() {
return ui;
}
private Shape getShapeOfCharacter(Font font, String digit) {
BufferedImage bi = new BufferedImage(
1, 1, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
FontRenderContext frc = g.getFontRenderContext();
GlyphVector gv = font.createGlyphVector(frc, digit);
return gv.getOutline();
}
public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
FontToDotMatrix o = new FontToDotMatrix();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}
class PixelArray extends JPanel {
JLabel[][] labels = new JLabel[5][7];
PixelArray() {
setLayout(new GridLayout(7, 5));
BufferedImage bi = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB);
ImageIcon icon = new ImageIcon(bi);
for (int yy = 0; yy < labels[0].length; yy++) {
for (int xx = 0; xx < labels.length; xx++) {
JLabel l = new JLabel(icon);
labels[xx][yy] = l;
l.setOpaque(true);
add(l);
}
}
}
public void updatePixels(boolean[][] bools) {
for (int xx = 0; xx < labels.length; xx++) {
for (int yy = 0; yy < labels[0].length; yy++) {
JLabel l = labels[xx][yy];
if (bools[xx][yy]) {
l.setBackground(Color.WHITE);
} else {
l.setBackground(Color.BLACK);
}
}
}
}
}
i'm trying to create a game using Kinect where you have to use your hand movements to wipe away an image to make it disappear revealing another image beneath it within 30 seconds. Now I have already done the code for the loosing condition where if you do not wipe away the image under 30 seconds, the loosing screen will pop up.
However, I am not sure how to code the part to detect when the entire PNG image has been "wiped away". Does this involve using get()? I am not sure how to approach this.
Imagine there are 2 Pimages moondirt.png and moonsurface.png
The Kinect controls the wiping and making Pimage moondirt.png transparent to reveal moonsurface.png
void kinect() {
//----------draw kinect------------
// Draw moon surface
image(moonSurface, 0, 0, width, height);
// Draw the moon dirt
image(moonDirt, 0, 0, width, height);
// Threshold the depth image
int[] rawDepth = kinect.getRawDepth();
for (int i=0; i < rawDepth.length; i++) {
if (rawDepth[i] >= minDepth && rawDepth[i] <= maxDepth) {
depthImg.pixels[i] = color(255);
maskingImg.pixels[i] = color(255);
} else {
depthImg.pixels[i] = color(0);
}
}
//moonDirt.resize(640, 480); //(640, 480);
moonDirt.loadPixels();
for (int i=0; i < rawDepth.length; i++) {
if ( maskingImg.pixels[i] == color(255) ) {
moonDirt.pixels[i] = color( 0, 0, 0, 0 );
}
}
moonDirt.updatePixels();
image(moonDirt, 0, 0, width, height);
color c = moonDirt.get(width, height);
updatePixels();
//--------timer-----
if (countDownTimer.complete() == true){
if (timeLeft > 1 ) {
timeLeft--;
countDownTimer.start();
} else {
state = 4;
redraw();
}
}
//show countDown TIMER
String s = "Time Left: " + timeLeft;
textAlign(CENTER);
textSize(30);
fill(255,0,0);
text(s, 380, 320);
}
//timer
class Timer {
int startTime;
int interval;
Timer(int timeInterval) {
interval = timeInterval;
}
void start() {
startTime = millis();
}
boolean complete() {
int elapsedTime = millis() - startTime;
if (elapsedTime > interval) {
return true;
}else {
return false;
}
}
}
I see the confusion in this section:
moonDirt.loadPixels();
for (int i=0; i < rawDepth.length; i++) {
if ( maskingImg.pixels[i] == color(255) ) {
moonDirt.pixels[i] = color( 0, 0, 0, 0 );
}
}
moonDirt.updatePixels();
image(moonDirt, 0, 0, width, height);
color c = moonDirt.get(width, height);
You are already using pixels[] which is more efficient than get() which is great.
Don't forget to call updatePixels() when you're done. You already do that for moonDirt, but not for maskingImg
If you want to find out if an image has been cleared (where clear means transparent black (color(0,0,0,0)) in this case).
It looks like you're already familiar with functions that take parameters and return values. The count function will need to:
take 2 arguments: the image to process and the colour to check and count
return the total count
iterate through all pixels: if any pixels match the 2nd argument, the total count increments
Something like this:
/**
* countPixels - counts pixels of of a certain colour within an image
* #param image - the PImage to loop through
* #param colorToCount - the colour to count pixels present in the image
* return int - the number of found pixels (between 0 and image.pixels.length)
*/
int countPixels(PImage image,color colorToCount){
// initial transparent black pixel count
int count = 0;
// make pixels[] available
image.loadPixels();
// for each pixel
for(int i = 0 ; i < image.pixels.length; i++){
// check if it's transparent black
if(image.pixels[i] == colorToCount){
// if so, increment the counter
count++;
}
}
// finally return the count
return count;
}
Within your code you could use it like so:
...
// Threshold the depth image
int[] rawDepth = kinect.getRawDepth();
for (int i=0; i < rawDepth.length; i++) {
if (rawDepth[i] >= minDepth && rawDepth[i] <= maxDepth) {
depthImg.pixels[i] = color(255);
maskingImg.pixels[i] = color(255);
} else {
depthImg.pixels[i] = color(0);
}
}
maskingImg.updatePixels();
//moonDirt.resize(640, 480); //(640, 480);
moonDirt.loadPixels();
for (int i=0; i < rawDepth.length; i++) {
if ( maskingImg.pixels[i] == color(255) ) {
moonDirt.pixels[i] = color( 0, 0, 0, 0 );
}
}
moonDirt.updatePixels();
image(moonDirt, 0, 0, width, height);
int leftToReveal = moonDirt.pixels.length;
int revealedPixels = countPixels(moonDirt,color(0,0,0,0));
int percentageClear = round(((float)revealedPixels / leftToReveal) * 100);
println("revealed " + revealedPixels + " of " + leftToReveal + " pixels -> ~" + percentageClear + "% cleared");
...
You have the option to set the condition for all pixels to be cleared or a ratio/percentage (e.g. if more 90% is clear, that's good enough) to then change the game state accordingly.
I want to make a colorized HorizontalBarChart with rounded edges using MPAndroidChart. I'm trying to change HorizontalBarChartRenderer for my chart for it. Here is my code:
HorizontalBarChart initialization:
List<Float> values = new ArrayList<>();
List<Integer> colors = new ArrayList<>();
// initializing
float[] valuesArray = new float[values.size()];
for (int i = 0; i < values.size(); i++) {
valuesArray[i] = values.get(i);
}
List<BarEntry> yValues = valuesArray.length <= 0
? Collections.<BarEntry>emptyList()
: Collections.singletonList(new BarEntry(valuesArray, 0));
BarDataSet barDataSet = new BarDataSet(yValues, "");
barDataSet.setColors(colors);
barDataSet.setValueFormatter(new ValueFormatter() {
#Override
public String getFormattedValue(float value, Entry entry,
int dataSetIndex, ViewPortHandler viewPortHandler) {
return "";
}
});
chartView.setData(new BarData(new String[]{"sleep"}, barDataSet));
And extended HorizontalBarChartRenderer:
#Override
protected void drawDataSet(Canvas c, IBarDataSet dataSet, int index) {
// ...
c.drawRoundRect(new RectF(buffer.buffer[j], buffer.buffer[j + 1] + 10, buffer.buffer[j + 2], buffer.buffer[j + 3] - 10), 20, 20, mRenderPaint);
}
The result is:
How can I make rounded edges only for outer sides?
Something like this:
I suggest that you draw all bars except the last one in "normal" mode, and start by drawing the top (rounded) bar first and let it stretch across the whole length of all bars.
In that way the other bars which are not rounded will cover up the unwanted roundings at the bottom of the first-drawn (rounded) bar.
I found a solution. My idea is to draw data as usual and after clearing some areas to make the edges rounded.
My code:
public class CircleHorizontalBarChartRenderer extends HorizontalBarChartRenderer {
public CircleHorizontalBarChartRenderer(BarDataProvider chart, ChartAnimator animator, ViewPortHandler viewPortHandler) {
super(chart, animator, viewPortHandler);
}
#Override
protected void drawDataSet(Canvas c, IBarDataSet dataSet, int index) {
Transformer trans = mChart.getTransformer(dataSet.getAxisDependency());
mShadowPaint.setColor(dataSet.getBarShadowColor());
float phaseX = mAnimator.getPhaseX();
float phaseY = mAnimator.getPhaseY();
// initialize the buffer
BarBuffer buffer = mBarBuffers[index];
buffer.setPhases(phaseX, phaseY);
buffer.setBarSpace(dataSet.getBarSpace());
buffer.setDataSet(index);
buffer.setInverted(mChart.isInverted(dataSet.getAxisDependency()));
buffer.feed(dataSet);
trans.pointValuesToPixel(buffer.buffer);
int length = buffer.buffer.length;
float left = 0;
float right = 0;
float top = buffer.buffer[length - 3];
float bot = buffer.buffer[length - 1];
boolean leftSaved = false;
for (int j = 0; j < buffer.size(); j += 4) {
if (!mViewPortHandler.isInBoundsTop(buffer.buffer[j + 3]))
break;
if (!mViewPortHandler.isInBoundsBottom(buffer.buffer[j + 1]))
continue;
// Set the color for the currently drawn value.
// If the index is
// out of bounds, reuse colors.
int color = dataSet.getColor(j / 4);
mRenderPaint.setColor(color);
if (color != 0 && !leftSaved) {
leftSaved = true;
left = buffer.buffer[j];
}
if (j > 4) { // it works but its ugly
right = buffer.buffer[j - 2];
}
c.drawRect(buffer.buffer[j], buffer.buffer[j + 1] + 10, buffer.buffer[j + 2],
buffer.buffer[j + 3] - 10, mRenderPaint);
}
Paint erasePaint = new Paint();
erasePaint.setAntiAlias(true);
erasePaint.setStyle(Paint.Style.STROKE);
int paintWidth = 20;
erasePaint.setStrokeWidth(paintWidth);
erasePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
c.drawRoundRect(new RectF(left - paintWidth / 2, top, right + paintWidth / 2, bot), 30, 30, erasePaint);
}
}
PorterDuff.Mode.CLEAR will work only if you set layer type as software. So you need to call
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
for chartView or for its parent view. If you don't need a transparent background, and background color in known, you can set this color for erasePaint, and do without sowtware layer type, which can worsen performance. And erasePaint.setXfermode also won't be needed for this case.
Final result:
I edited Nick Kober's solution. Here is the code;
public class CircleHorizontalBarChartRenderer extends HorizontalBarChartRenderer {
public CircleHorizontalBarChartRenderer(BarDataProvider chart, ChartAnimator animator, ViewPortHandler viewPortHandler) {
super(chart, animator, viewPortHandler);
}
#Override
protected void drawDataSet(Canvas c, IBarDataSet dataSet, int index) {
Transformer trans = mChart.getTransformer(dataSet.getAxisDependency());
mShadowPaint.setColor(dataSet.getBarShadowColor());
float phaseX = mAnimator.getPhaseX();
float phaseY = mAnimator.getPhaseY();
// initialize the buffer
BarBuffer buffer = mBarBuffers[index];
buffer.setPhases(phaseX, phaseY);
buffer.setBarWidth(dataSet.getBarBorderWidth());
buffer.setDataSet(index);
buffer.setInverted(mChart.isInverted(dataSet.getAxisDependency()));
buffer.feed(dataSet);
trans.pointValuesToPixel(buffer.buffer);
int timeToChange = buffer.size() / 4;
for (int j = 0; j < buffer.size(); j += 4) {
if (!mViewPortHandler.isInBoundsTop(buffer.buffer[j + 3]))
break;
if (!mViewPortHandler.isInBoundsBottom(buffer.buffer[j + 1]))
continue;
// Set the color for the currently drawn value.
// If the index is
// out of bounds, reuse colors.
int color = dataSet.getColor(j / 4);
mRenderPaint.setColor(color);
if (j/4 == 0) {
c.drawRoundRect(new RectF(buffer.buffer[j], buffer.buffer[j + 1] + 10, buffer.buffer[j+2], buffer.buffer[j + 3] - 10), 20, 20, mRenderPaint);
c.drawRect(new RectF(buffer.buffer[j] + 10 , buffer.buffer[j + 1] + 10, buffer.buffer[j+2], buffer.buffer[j + 3] - 10), mRenderPaint);
}
else if (j/4 < timeToChange - 1) {
c.drawRect(new RectF(buffer.buffer[j] , buffer.buffer[j + 1] + 10, buffer.buffer[j+2], buffer.buffer[j + 3] - 10), mRenderPaint);
}
else if (j/4 == timeToChange - 1) {
c.drawRoundRect(new RectF(buffer.buffer[j], buffer.buffer[j + 1] + 10, buffer.buffer[j+2], buffer.buffer[j + 3] - 10), 20, 20, mRenderPaint);
c.drawRect(new RectF(buffer.buffer[j], buffer.buffer[j + 1] + 10, buffer.buffer[j+2] - 10, buffer.buffer[j + 3] - 10), mRenderPaint);
}
}
}
Again, you should write your own custom Renderer class as Nick does. I added the last part (if-else if blocks).
I thought like this, for the first bar draw rounded rectangle. Then above that draw a rectangle by shifting left side to right. By shifting, left side stays rounded. For the inner ones, draw all of them as rectangles. And for the last one draw rounded rectangle. Then above that draw a rectangle by shifting right side to left. By shifting, right side stays rounded.
I used variable "timeToChange" to understand which bar currently I am drawing.
And the output is like this
I have a new problem with the repaint methode.
There is a frame in which I paint several graphics together. When I click in a specific range of coordinates, it should change the status of one graphic and then repaint this specific range. But this repaint doesn't work...
This is the method that initialize the graphics (the declaration of the graphics isn't shown):
private void initComponents() {
Painter painter = new Painter();
setExtendedState(MAXIMIZED_BOTH);
int width = (int) getContentPane().getBounds().getWidth();
int height = (int) getContentPane().getBounds().getHeight();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
g0 = new Gleis(25, 1, 4, 0, 0);
g1 = new Gleis(26, 1, 0, 1, 0);
k0 = new KnopfRot(26, 1, 0, false);
g2 = new Gleis(27, 1, 0, 2, 0);
g3 = new Gleis(28, 1, 0, 3, 0);
g4 = new Gleis(29, 1, 0, 4, 0);
g5 = new Gleis(30, 1, 0, 5, 0);
g6 = new Gleis(31, 1, 0, 6, 0);
g7 = new Gleis(32, 1, 0, 7, 0);
g8 = new Gleis(33, 1, 0, 8, 0);
g9 = new Gleis(34, 1, 0, 9, 0);
g10 = new Gleis(35, 1, 0, 10, 0);
g11 = new Gleis(36, 1, 0, 11, 0);
g12 = new Gleis(37, 1, 0, 12, 0);
g13 = new Gleis(38, 1, 0, 13, 0);
k1 = new KnopfRot(38, 1, 1, false);
painter.addGleis(g0);
painter.addGleis(g1);
painter.addKnopfRot(k0);
painter.addGleis(g2);
painter.addGleis(g3);
painter.addGleis(g4);
painter.addGleis(g5);
painter.addGleis(g6);
painter.addGleis(g7);
painter.addGleis(g8);
painter.addGleis(g9);
painter.addGleis(g10);
painter.addGleis(g11);
painter.addGleis(g12);
painter.addGleis(g13);
painter.addKnopfRot(k1);
this.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
double x = e.getX();
double y = e.getY();
frameMouseClicked(x, y);
}
});
this.getContentPane().add(painter);
this.setVisible(true);
}
public void frameMouseClicked(double x, double y) {
if(x >= 306 && x <= 314 && y >= 55 && y <= 63){ //x+11 y+32
Painter painter = new Painter();
painter.updateKnopfRot(k0, 26, 1, 306, 55);
repaint();
}
else{}
}
Then my class KnopfRot:
public class KnopfRot {
int xposition;
int yposition;
int type;
int id;
boolean status;
//Konstruktor
public KnopfRot(int xpos, int ypos, int id, boolean status){
this.xposition = xpos * 11 + 12;
this.yposition = ypos * 11 + 12;
this.id = id; //zur eindeutigen Bezeichnung der Gleiselemente
this.status = status;
}
public void draw(Graphics2D g) {
if (!status) {
Ellipse2D.Double aussen = new Ellipse2D.Double(xposition, yposition, 8, 8);
Ellipse2D.Double innen = new Ellipse2D.Double(xposition + 1, yposition + 1, 6, 6);
g.setColor(Color.black);
g.fill(aussen);
g.setColor(Color.red);
g.fill(innen);
}
else if (status){
Ellipse2D.Double aussen = new Ellipse2D.Double(xposition, yposition, 7, 7);
Ellipse2D.Double innen = new Ellipse2D.Double(xposition + 1, yposition + 1, 5, 5);
g.setColor(Color.black);
g.fill(aussen);
g.setColor(Color.red);
g.fill(innen);
}
else {}
}
}
And the Painter-Class with the method updateKnopfRot which is callen in the MouseEvent:
public class Painter extends JPanel {
private List<Gleis> gleisList = new ArrayList<>();
private List<KnopfRot> knopfList = new ArrayList<>();
//fügt ein neues Element der Liste gleisList hinzu
public void addGleis(Gleis gleis) {
gleisList.add(gleis);
}
public void addKnopfRot(KnopfRot knopf) {
knopfList.add(knopf);
}
public void updateKnopfRot(KnopfRot knopf, int x, int y, int xpos, int ypos) {
knopfList.remove(knopf);
addKnopfRot(new KnopfRot(x, y, 0, true));
}
//paint-Methode geht jedes Element der Liste gleisList durch und führt die draw-Methode in Gleis.java aus
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (Gleis gleis : gleisList) {
gleis.draw(g2);
}
for (KnopfRot knopf : knopfList) {
knopf.draw(g2);
}
}
}
Sorry for so much code but I can't reduce it to explain/show the problem.
Can somebody help?
You're creating a new Painter(...) object within your frameMouseClicked(...) method, and then changing the state of this object, but this will have no effect on the completely different visualized Painter object. Your solution -- don't create a new Painter object, but rather use a reference to the original, and then try to change its state.
Regarding:
Sorry for so much code but I can't reduce it to explain/show the problem.
If this answer doesn't solve your problem, then yes, you can reduce this code and make it runnable as we've discussed in the past. Yes it will take some effort on your part to create and post a valid MCVE, but it's worth it.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
issue with my main method in my connect4 game
Hi,
on my connect4 game, whenever i click on any square it places the oval on that specific square, how do i get it so that it places the oval on the lowest square in that column so that it can stack up?
package Game;
import java.util.ArrayList;
public class ConnectFourBoard {
// This constant is used to indicate the width and height, in cells,
// of the board. Since we want an 8x8 board, we'll set it to 8.
private static final int WIDTH = 8;
private static final int HEIGHT = 8;
private ConnectFourCell[][] currentPlayer;
// The current state the Othello board is defined with these two
// fields: a two-dimensional array holding the state of each cell,
// and a boolean value indicating whether it's the black player's
// turn (true) or the white player's turn (false).
private ConnectFourCell[][] cells;
private boolean isBlueTurn;
// Since the board is a model and it needs to notify views of changes,
// it will employ the standard "listener" mechanism of tracking a list
// of listeners and firing "events" (by calling methods on those
// listeners) when things change.
private ArrayList<ConnectFourListener> listeners;
public ConnectFourBoard()
{
// Arrays, in Java, are objects, which means that variables of
// array types (like cells, which has type OthelloCell[][]) are
// really references that say where an array lives. By default,
// references point to null. So we'll need to create an actual
// two-dimensional array for "cells" to point to.
cells = new ConnectFourCell[WIDTH][HEIGHT];
listeners = new ArrayList<ConnectFourListener>();
reset();
isBlueTurn = true;
}
public void reset(){
for (int i = 0; i<WIDTH ; i++){
for (int j = 0; j<HEIGHT; j++){
cells[i][j] = ConnectFourCell.NONE;
}
}
isBlueTurn = true;
}
public void addConnectFourListener(ConnectFourListener listener)
{
listeners.add(listener);
}
public void removeConnectFourListener(ConnectFourListener listener)
{
if (listeners.contains(listener))
{
listeners.remove(listener);
}
}
// These are fairly standard "fire event" methods that we've been building
// all quarter, one corresponding to each method in the listener interface.
private void fireBoardChanged()
{
for (ConnectFourListener listener : listeners)
{
listener.boardChanged();
}
}
private void fireGameOver()
{
for (ConnectFourListener listener : listeners)
{
listener.gameOver();
}
}
// isBlackTurn() returns true if it's the black player's turn, and false
// if it's the white player's turn.
public boolean isBlueTurn()
{
return isBlueTurn;
}
public int getWidth()
{
return WIDTH;
}
public int getHeight(){
return HEIGHT;
}
// getBlackScore() calculates the score for the black player.
public int getBlackScore()
{
return getScore(ConnectFourCell.BLUE);
}
// getWhiteScore() calculates the score for the white player.
public int getWhiteScore()
{
return getScore(ConnectFourCell.RED);
}
// getScore() runs through all the cells on the board and counts the
// number of cells that have a particular value (e.g., BLACK or WHITE).
// This method uses the naive approach of counting them each time
// it's called; it might be better to keep track of this score as we
// go, updating it as tiles are added and flipped.
private int getScore(ConnectFourCell cellValue)
{
int score = 0;
for (int i = 0; i < WIDTH; i++)
{
for (int j = 0; j < HEIGHT; j++)
{
if (cells[i][j] == cellValue)
{
score++;
}
}
}
return score;
}
// getWhiteScore() calculates the score for the white player.
public int getRedScore()
{
return getScore(ConnectFourCell.RED);
}
public int getBlueScore() {
// TODO Auto-generated method stub
return getScore(ConnectFourCell.BLUE);
}
public ConnectFourCell getCell(int x, int y)
{
if (!isValidCell(x, y))
{
throw new IllegalArgumentException(
"(" + x + ", " + y + ") is not a valid cell");
}
return cells[x][y];
}
/**
* The drop method.
*
* Drop a checker into the specified HEIGHT,
* and return the WIDTH that the checker lands on.
*/
int drop(int HEIGHT) {
if (hasWon()) {
return -1;
}
for ( ; WIDTH<6 && HEIGHT != 0; WIDTH++) { };
if (WIDTH==6) {
// if the WIDTH is 6, it went through all 6 WIDTHs
// of the cells, and couldn't find an empty one.
// Therefore, return false to indicate that this
// drop operation failed.
return -1;
}
// fill the WIDTH of that HEIGHT with a checker.
cells[HEIGHT][WIDTH] = currentPlayer[HEIGHT][WIDTH];
// alternate the players
//currentPlayer = (currentPlayer%2)+1;
return WIDTH;
}
/**
* The toString method
*
* Returns a String representation of this
* Connect Four (TM) game.
*/
public String toString() {
String returnString = "";
for (int WIDTH=5; WIDTH>=0; WIDTH--) {
for (int HEIGHT=0; HEIGHT<7; HEIGHT++) {
returnString = returnString + cells[HEIGHT][WIDTH];
}
returnString = returnString + "\n";
}
return returnString;
}
/**
* The hasWon method.
*
* This method returns true if one of the
* players has won the game.
*/
public boolean hasWon()
{
// First, we'll establish who the current player and the opponent is.
//ConnectFourCell
ConnectFourCell myColor =
isBlueTurn() ? ConnectFourCell.BLUE : ConnectFourCell.RED;
ConnectFourCell otherColor =
isBlueTurn() ? ConnectFourCell.RED : ConnectFourCell.BLUE;
return true;
}
public void validMove( ){
}
public void makeAMove(int x, int y){
//System.out.println(x+" "+y);
// cells[x][y] = ConnectFourCell.BLUE;
//Check who's turn it is. Set to that color.
ConnectFourCell myColor = null;
if ( isBlueTurn == true){
myColor = myColor.BLUE;
}
else {
myColor = myColor.RED;
}
cells[x][y] = myColor;
//Check if it's a valid move. If there is a piece there. can't
// Look at the column. play piece in the highest available slot
//Check if there are 4 in a row.
for (int WIDTH=0; WIDTH<6; WIDTH++) {
for (int HEIGHT=0; HEIGHT<4; HEIGHT++) {
if (!(cells[HEIGHT][WIDTH] == ConnectFourCell.NONE) &&
cells[HEIGHT][WIDTH] == cells[HEIGHT+1][WIDTH] &&
cells[HEIGHT][WIDTH] == cells[HEIGHT+2][WIDTH] &&
cells[HEIGHT][WIDTH] == cells[HEIGHT+3][WIDTH]) {
}
}
}
// check for a vertical win
for (int WIDTH=0; WIDTH<3; WIDTH++) {
for (int HEIGHT=0; HEIGHT<7; HEIGHT++) {
if (!(cells[HEIGHT][WIDTH] == ConnectFourCell.NONE) &&
cells[HEIGHT][WIDTH] == cells[HEIGHT][WIDTH+1] &&
cells[HEIGHT][WIDTH] == cells[HEIGHT][WIDTH+2] &&
cells[HEIGHT][WIDTH] == cells[HEIGHT][WIDTH+3]) {
}
}
}
// check for a diagonal win (positive slope)
for (int WIDTH=0; WIDTH<3; WIDTH++) {
for (int HEIGHT=0; HEIGHT<4; HEIGHT++) {
if (!(cells[HEIGHT][WIDTH] == ConnectFourCell.NONE) &&
cells[HEIGHT][WIDTH] == cells[HEIGHT+1][WIDTH+1] &&
cells[HEIGHT][WIDTH] == cells[HEIGHT+2][WIDTH+2] &&
cells[HEIGHT][WIDTH] == cells[HEIGHT+3][WIDTH+3]) {
}
}
}
// check for a diagonal win (negative slope)
for (int WIDTH=3; WIDTH<6; WIDTH++) {
for (int HEIGHT=0; HEIGHT<4; HEIGHT++) {
if (!(cells[HEIGHT][WIDTH] == ConnectFourCell.NONE) &&
cells[HEIGHT][WIDTH] == cells[HEIGHT+1][WIDTH-1] &&
cells[HEIGHT][WIDTH] == cells[HEIGHT+2][WIDTH-2] &&
cells[HEIGHT][WIDTH] == cells[HEIGHT+3][WIDTH-3]) {
}
}
}
fireBoardChanged();
isBlueTurn = !isBlueTurn;
}
private boolean isValidCell(int x, int y)
{
return x >= 0 && x < WIDTH
&& x>= 0 && x<HEIGHT
&& y >= 0 && y < WIDTH
&& y>= 0 && y<HEIGHT;
}
}
package UI;
import java.awt.*;
import javax.swing.*;
import UI.ConnectFourBoardPanel;
import Game.ConnectFourBoard;
import Game.ConnectFourListener;
public class ConnectFourFrame extends JFrame implements ConnectFourListener {
// Variables
private ConnectFourBoard board;
private JLabel scoreLabel;
private ConnectFourBoardPanel boardPanel;
private JLabel statusLabel;
public ConnectFourFrame()
{
// The frame builds its own model.
board = new ConnectFourBoard();
// We want the frame to receive notifications from the board as its
// state changes.
System.out.println(this);
board.addConnectFourListener(this);
setTitle("Informatics 45 Spring 2011: ConnectFour Game");
setSize(700, 700);
setResizable(true);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setBackground(Color.BLACK);
buildUI();
refreshUI();
}
private void buildUI()
{
GridBagLayout layout = new GridBagLayout();
getContentPane().setLayout(layout);
Font labelFont = new Font("SansSerif", Font.BOLD, 18);
scoreLabel = new JLabel();
scoreLabel.setForeground(Color.WHITE);
scoreLabel.setFont(labelFont);
layout.setConstraints(
scoreLabel,
new GridBagConstraints(
0, 0, 1, 1, 1.0, 0.0,
GridBagConstraints.CENTER,
GridBagConstraints.NONE,
new Insets(10, 10, 10, 10), 0, 0));
getContentPane().add(scoreLabel);
boardPanel = new ConnectFourBoardPanel(board);
layout.setConstraints(
boardPanel,
new GridBagConstraints(
0, 1, 1, 1, 1.0, 1.0,
GridBagConstraints.CENTER,
GridBagConstraints.BOTH,
new Insets(10, 10, 10, 10), 0, 0));
getContentPane().add(boardPanel);
statusLabel = new JLabel();
statusLabel.setForeground(Color.WHITE);
statusLabel.setFont(labelFont);
layout.setConstraints(
statusLabel,
new GridBagConstraints(
0, 2, 1, 1, 1.0, 0.0,
GridBagConstraints.CENTER,
GridBagConstraints.NONE,
new Insets(10, 10, 10, 10), 0, 0));
getContentPane().add(statusLabel);
}
private void refreshUI()
{
// Refreshing the UI means to change the text in each of the
// two labels (the score and the status) and also to ask the
// board to repaint itself.
scoreLabel.setText(
"Blue: " + board.getBlueScore() +
" Red: " + board.getRedScore());
if ( board.isBlueTurn() == false){
statusLabel.setText("Blue's Turn: ");
}
if ( board.isBlueTurn() == true){
statusLabel.setText("Red's Turn: ");
}
boardPanel.repaint();
}
// These are the ConnectFourBoardListener event-handling methods.
public void boardChanged()
{
// When the board changes, we'll refresh the entire UI. (There
// are times when this approach is too inefficient, but it will
// work fine for our relatively simple UI.)
refreshUI();
}
public void gameOver()
{
// When the game is over, we'll pop up a message box showing the final
// score, then, after the user dismisses the message box, dispose of
// this window and end the program.
JOptionPane.showMessageDialog(
this,
"Game over!\nFinal score: " + scoreLabel.getText(),
"Game Over",
JOptionPane.INFORMATION_MESSAGE);
dispose();
}
}
Welcome to StackOverflow. You're question is fine - but pasting your whole program, in general, is a bad idea. You should describe your program, and include the snippet where you calculate how the ovals are filled in.
Having said that, here's a crack at the answer :
- You want to look at the tile thats currently selected, and if the tile underneath it is occupied, fill in that cell. If its not occupied, set the current tile to the underneath tile, and repeat. You want to do this until you get to the bottom row.
The answer above doesn't incude checking if the selected tile is already occupied, but I'm sure you can easily figure that out.