Sudoku: Selection image does not appear - java

I am building a Sudoku game. I have drawn a grid so far and programmed the selection of a field, but my chosen picture for selection does not appear. My Class for the selector is:
package com.brendenbunker;
import javax.swing.*;
public class Selection {
public JLabel boxSelected;
public ImageIcon selected;
int x, y;
public Selection(){
x = 0;
y = 0;
selected = new ImageIcon(getClass().getResource("/Selected.png"));
boxSelected = new JLabel("");
boxSelected.setIcon(selected);
boxSelected.setBounds((x * (selected.getIconWidth() + 4) + (x / 3) * 4) + 4, (y * (selected.getIconWidth() + 4) + (y / 3) * 4) + 4, selected.getIconWidth(), selected.getIconHeight());
}
public Selection(int x, int y){
this.x = x;
this.y = y;
selected = new ImageIcon(getClass().getResource("/Selected.png"));
boxSelected = new JLabel("");
boxSelected.setIcon(selected);
boxSelected.setBounds((x * (selected.getIconWidth() + 4) + (x / 3) * 4) + 4, (y * (selected.getIconWidth() + 4) + (y / 3) * 4) + 4, selected.getIconWidth(), selected.getIconHeight());
}
public void setNewSelection(int x, int y) {
this.x = x;
this.y = y;
boxSelected.setBounds((x * (selected.getIconWidth() + 4) + (x / 3) * 4) + 4, (y * (selected.getIconWidth() + 4) + (y / 3) * 4) + 4, selected.getIconWidth(), selected.getIconHeight());
}
}
The code which displays everything is:
package com.brendenbunker;
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class ScreenGenerator extends JFrame{
//Intro Components
//JLabel temp;
JLabel[] gridLabel, numbLabel, numbBackLabel;
JLabel[][] numbDisp;
ImageIcon gridPic, numbPic, numbBackPic;
Rectangle[][] boxArea;
Selection selection;
Random random;
//intro Vars
public ScreenGenerator() {
setLayout(null);
random = new Random();
selection = new Selection();
gridPic = new ImageIcon(getClass().getResource("/Grid_Unified.png"));
numbBackPic = new ImageIcon(getClass().getResource("/Square.png"));
gridLabel = new JLabel[9];
numbLabel = new JLabel[9];
numbBackLabel = new JLabel[9];
boxArea = new Rectangle[9][9];
numbDisp = new JLabel[9][9];
for (int i=0; i<9; i++) {
gridLabel[i] = new JLabel("");
gridLabel[i].setBounds(((i+1)%3)*gridPic.getIconWidth(),Math.round(i/3)*gridPic.getIconHeight(),gridPic.getIconWidth(),gridPic.getIconHeight());
numbBackLabel[i] = new JLabel("");
numbBackLabel[i].setBounds(i*numbBackPic.getIconWidth()+1,gridPic.getIconHeight()*3,numbBackPic.getIconWidth(),numbBackPic.getIconHeight());
numbLabel[i] = new JLabel("");
numbLabel[i].setBounds(i*numbBackPic.getIconWidth(),gridPic.getIconHeight()*3,numbBackPic.getIconWidth(),numbBackPic.getIconHeight());
for (int j=0; j<9; j++) {
numbDisp[i][j] = new JLabel("");
numbDisp[i][j].setBounds((j * (selection.selected.getIconWidth() + 4) + (j / 3) * 4) + 4, (i * (selection.selected.getIconWidth() + 4) + (i / 3) * 4) + 4, selection.selected.getIconWidth(), selection.selected.getIconHeight());
boxArea[j][i] = new Rectangle((j*(selection.selected.getIconWidth()+4)+(j/3)*4)+4,(i*(selection.selected.getIconWidth()+4)+(i/3)*4)+4,selection.selected.getIconWidth(),selection.selected.getIconHeight());
add(numbDisp[i][j]);
}
}
for (int i=0; i<9; i++) {
numbPic = new ImageIcon(getClass().getResource("/numb_" + (i+1) + ".png"));
numbLabel[i].setIcon(numbPic);
gridLabel[i].setIcon(gridPic);
numbBackLabel[i].setIcon(numbBackPic);
add(selection.boxSelected);
add(gridLabel[i]);
add(numbLabel[i]);
add(numbBackLabel[i]);
}
setBoxNumb(random.nextInt(9)+1,random.nextInt(9)+1,random.nextInt(9)+1);
selection.setNewSelection(1,2);
}
public void setBoxNumb(int x, int y, int numb){
numbPic = new ImageIcon(getClass().getResource("/numb_" + numb + ".png"));
numbDisp[x - 1][y - 1].setIcon(numbPic);
}
}
So what I am trying to ask is why the image I want to be displayed if a field is selected does not appear ? Does anyone know how to fix this ?

Try to simplify your program down to the simplest one that reproduces the problem. You may discover the problem in the process, but if not, you'll have a clear example of it that's easy to understand.
Single step through your program to see if it's behaving as you expect.
Add logging to your program to see if it's behaving as you expect.
If you encounter any specific issues, feel free to ask a specific question. But right now, you're basically asking "how do I debug a program?"

What I found is that the layout layers are backwards to what i would expect. The Label you add first will always stay on top. That label won't be drawn over by JComponents add after the original is on. So basically, the earlier in the code you add a component to a JFrame, the Higher the priority that Component has.

Related

Sobel edge detection with BufferedImage.TYPE_BYTE_BINARY as output

I´m doing a school assignment where we are supposed to do a sobel edge detection on an image. We should do a convolution with the sobel cores och then calculate the gradientmagnitude for each pixel. After that, we should use the threshold method to give a pixel the value 255 (white) or 0 (black), depending on the threshold value. The output image from the edge detection must be of the type BufferedImage.TYPE_BYTE_BINARY. I use a grayscale image as input but the endresult ends up looking very weird.. it definitely does not detect the edges.
I googled around and managed to find working code (here, see the marked correct answer), however, the output image here is of the type BufferedImage.TYPE_INT_RGB, which is not allowed... In this question, the also use a BufferedImage.TYPE.INT.RGB as input to the edge detection.
Help on resolving this matter is much appreciated!
Result when I execute the program. The edge detection result is on the far right.
What the edge detection result should look like.
My code:
/**
* turns an image to a grayscale version of the image
*/
public void alterImageGrayScale() throws IOException {
imageGrayScale = new BufferedImage(imageOriginal.getWidth(), imageOriginal.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
for(int i = 0; i < imageOriginal.getWidth(); i++) {
for(int j = 0; j < imageOriginal.getHeight(); j++) {
Color c = new Color(imageOriginal.getRGB(i, j));
int red = c.getRed();
int green = c.getGreen();
int blue = c.getBlue();
int gray = (int) (0.2126*red + 0.7152*green + 0.0722*blue);
imageGrayScale.setRGB(i, j, new Color(gray, gray, gray).getRGB());
}
}
}
/**
* edge detection
* #throws IOException
*/
public void alterEdgeDetection() throws IOException {
imageBlackAndWhite = new BufferedImage(imageGrayScale.getWidth(), imageGrayScale.getHeight(), BufferedImage.TYPE_INT_RGB);
int x = imageGrayScale.getWidth();
int y = imageGrayScale.getHeight();
int threshold = 250;
for (int i = 1; i < x - 1; i++) {
for (int j = 1; j < y - 1; j++) {
int val00 = imageGrayScale.getRGB(i - 1, j - 1);
int val01 = imageGrayScale.getRGB(i - 1, j);
int val02 = imageGrayScale.getRGB(i - 1, j + 1);
int val10 = imageGrayScale.getRGB(i, j - 1);
int val11 = imageGrayScale.getRGB(i, j);
int val12 = imageGrayScale.getRGB(i, j + 1);
int val20 = imageGrayScale.getRGB(i + 1, j - 1);
int val21 = imageGrayScale.getRGB(i + 1, j);
int val22 = imageGrayScale.getRGB(i + 1, j + 1);
int gradientX = ((-1 * val00) + (0 * val01) + (1 * val02)) + ((-2 * val10) + (0 * val11) + (2 * val12))
+ ((-1 * val20) + (0 * val21) + (1 * val22));
int gradientY = ((-1 * val00) + (-2 * val01) + (-1 * val02)) + ((0 * val10) + (0 * val11) + (0 * val12))
+ ((1 * val20) + (2 * val21) + (1 * val22));
int gradientValue = (int) Math.sqrt(Math.pow(gradientX, 2) + Math.pow(gradientY, 2));
//???? feel like something should be done here, but dont know what
if(threshold > gradientValue) {
imageBlackAndWhite.setRGB(i, j, new Color(0, 0, 0).getRGB());
} else {
imageBlackAndWhite.setRGB(i, j, new Color(255, 255, 255).getRGB());
}
}
}
}
According to the response in the comment, it should be sufficient to convert the grayscale image that is computed by the edge detection into an image of type TYPE_BYTE_BINARY.
The following is a MCVE that loads the grayscale image that was linked to in the question (containing the edge detection result), and converts it into a binary image.
For the conversion to the binary image, there is a threshold that can be modified with the slider at the bottom of the screen: It determines which grayscale value will be converted into a BLACK or WHITE pixel, respectively.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
public class ImageToBinary
{
public static void main(String[] args) throws Exception
{
BufferedImage input =
ImageIO.read(new URL("https://i.stack.imgur.com/jvOan.png"));
BufferedImage output = convertToBinary(input, 10);
SwingUtilities.invokeLater(() -> createAndShowGui(input, output));
}
private static void createAndShowGui(
BufferedImage input, BufferedImage output)
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel(new GridLayout(1,2));
JLabel outputLabel = new JLabel(new ImageIcon(output));
p.add(new JLabel(new ImageIcon(input)));
p.add(outputLabel);
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(p, BorderLayout.NORTH);
JSlider slider = new JSlider(0, 256, 10);
slider.addChangeListener(e ->
{
int threshold = slider.getValue();
BufferedImage newOutput = convertToBinary(input, threshold);
outputLabel.setIcon(new ImageIcon(newOutput));
});
f.getContentPane().add(slider, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static BufferedImage convertToBinary(
BufferedImage input, int threshold)
{
int w = input.getWidth();
int h = input.getHeight();
BufferedImage output = new BufferedImage(
w, h, BufferedImage.TYPE_BYTE_BINARY);
int blackRgb = Color.BLACK.getRGB();
int whiteRgb = Color.WHITE.getRGB();
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
int rgb = input.getRGB(x, y);
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = (rgb) & 0xFF;
int gray = (int) (0.2126 * r + 0.7152 * g + 0.0722 * b);
if (gray >= threshold)
{
output.setRGB(x, y, whiteRgb);
}
else
{
output.setRGB(x, y, blackRgb);
}
}
}
return output;
}
}

Java: Starting loop increment for drawing a multiplication table

I am having trouble figuring out how to remove the 0's in this table. I've attempted looking it up online and have had little success figuring it out that way (probably not searching it correctly). I am attempting to get Figure #1 to appear like Figure #2 besides a few stylistic changes.
I'd appreciate any help.
Code: (http://www.buildingjavaprograms.com/DrawingPanel.java) Drawing Panel Used
import java.awt.*;
public class IfGridFor {
public static void main(String[] args) {
DrawingPanel panel = new DrawingPanel(400, 520);
panel.setBackground(Color.blue);
Graphics g = panel.getGraphics();
int sizeX = 40;
int sizeY = 40;
for (int x = 0; x < 10; x++) {
for (int y = 0; y <= 12; y++) {
int cornerX = x*sizeX;
int cornerY = y*sizeY;
if ((x + y) % 2 == 0)
g.setColor(Color.green);
else
g.setColor(Color.yellow);
g.fillRect(cornerX+1, cornerY+1, sizeX-2, sizeY-2);
g.setColor(Color.black);
g.drawString(x + " * " + y, cornerX + 5, cornerY + 15); // text is
g.drawString("= " + x * y, cornerX + 5, cornerY + 33); // offsets
}
}
}
}
Figure #1:
Figure #2:
You are almost done - all you need is changing what gets shown from x, y, x*y to (x+1), (y+1), (x+1)*(y+1), and reducing the height of the panel by one row:
DrawingPanel panel = new DrawingPanel(400, 480); // 12 rows, not 13
...
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 12; y++) { // < instead of <=
...
g.drawString((x+1) + " * " + (y+1), cornerX + 5, cornerY + 15); // text is
g.drawString("" + (x+1) * (y+1), cornerX + 5, cornerY + 33); // offsets
}
}
The rest of your code (i.e. the ... parts) remain the same.
If I'm understanding your question correctly, you want to remove the top row and the left column? If so, start your for loops at one instead of zero. Also your outer loop should have the condition x <= 10 if you want the figure to include the square labelled '10'.
Then change the lines:
int cornerX = x*sizeX;
int cornerY = y*sizeY;
to:
int cornerX = (x-1)*sizeX;
int cornerY = (y-1)*sizeY;

Computing area of a polygon in Java

I have a class called SimplePolygon that creates a polygon with coordinates provided by the user. I am trying to define a method to compute the area of the polygon. It's an assignment and course instructor wants us to use the following formula to compute the area.
I can use either formula. I chose the right one.
My code gives me the wrong area. I don't know what's wrong.
public class SimplePolygon implements Polygon {
protected int n; // number of vertices of the polygon
protected Point2D.Double[] vertices; // vertices[0..n-1] around the polygon
public double area() throws NonSimplePolygonException {
try
{
if(isSimple()==false)
throw new NonSimplePolygonException();
else
{
double sum = 0;
for(int i = 0; i < vertices.length - 1; i++)
if(i == 0)
sum += vertices[i].x * (vertices[i+1].y - vertices[vertices.length - 1].y);
else
sum += vertices[i].x * (vertices[i+1].y - vertices[i-1].y);
double area = 0.5 * Math.abs(sum);
return area;
}
}
catch(NonSimplePolygonException e)
{
System.out.println("The Polygon is not simple.");
}
return 0.0;
}
The following is a tester code. The polygon is a rectangle with area 2, but the output is 2.5
Point2D.Double a = new Point2D.Double(1,1);
Point2D.Double b = new Point2D.Double(3,1);
Point2D.Double c = new Point2D.Double(3,2);
Point2D.Double d = new Point2D.Double(1,2);
SimplePolygon poly = new SimplePolygon(4);
poly.vertices[0] = a;
poly.vertices[1] = b;
poly.vertices[2] = c;
poly.vertices[3] = d;
System.out.println(poly.area());
Now that you've fixed the trivial boundary case, you're missing another boundary and your loop is wrong. Corrected code with debug:
public double area()
{
double sum = 0;
for (int i = 0; i < vertices.length ; i++)
{
if (i == 0)
{
System.out.println(vertices[i].x + "x" + (vertices[i + 1].y + "-" + vertices[vertices.length - 1].y));
sum += vertices[i].x * (vertices[i + 1].y - vertices[vertices.length - 1].y);
}
else if (i == vertices.length - 1)
{
System.out.println(vertices[i].x + "x" + (vertices[0].y + "-" + vertices[i - 1].y));
sum += vertices[i].x * (vertices[0].y - vertices[i - 1].y);
}
else
{
System.out.println(vertices[i].x + "x" + (vertices[i + 1].y + "-" + vertices[i - 1].y));
sum += vertices[i].x * (vertices[i + 1].y - vertices[i - 1].y);
}
}
double area = 0.5 * Math.abs(sum);
return area;
}
There is one missing term from the sum: vertices[n-1].x * (vertices[0].y - vertices[n-2].y).
Before the edit of the question there was also a problem with the first term:
Furthermore, if i==0 the term should be vertices[i].x * (vertices[i+1].y - vertices[n-1].y).
Assuming that n is equal to vertices.length.
The simplest way to code the loop is probably:
n = vertices.length;
sum =0;
for (int i = 0; i < n; i++) {
sum += vertices[i].x * (vertices[(i + 1) % n].y - vertices[(i + n - 1) % n].y);
}
I found another way,
Add first element again into polygon array
So that we can avoid "Out of bound" case as well as many If conditions.
Here is my solution:
public class PolygonArea {
public static void main(String[] args) {
PolygonArea p = new PolygonArea();
System.out.println(p.calculateArea());
}
Point[] points = new Point[5];
public double calculateArea() {
points[0] = new Point("A", 4, 10);
points[1] = new Point("B", 9, 7);
points[2] = new Point("C", 11, 2);
points[3] = new Point("D", 2, 2);
/** Add first entry again to polygon */
points[4] = new Point("A", 4, 10);
double sum = 0.0;
for (int i = 0; i < points.length - 1; ++i) {
sum += (points[i].X * points[i + 1].Y) - (points[i + 1].X * points[i].Y);
}
return Math.abs(sum / 2);
}
class Point {
final String _ID;
final int X;
final int Y;
public Point(String id, int x, int y) {
_ID = id;
X = x;
Y = y;
}
}
}

How to measure time for maze generation?

How can I insert a timer to my code? My goal is to know how long it would take for my maze to generate because I am comparing it to the previous program for my thesis.
Thanks for the big help. :)
Here is the code that I used:
public class Maze extends JPanel {
private Room[][] rooms;// m x n matrix of rooms
private ArrayList<Wall> walls; // List of walls
private Random rand;// for random wall
private int height;// height of matrix
private int width;// width of matrix
private int num;// incrementor
private JoinRoom ds;// union paths
// paint methods //
private int x_cord; // x-axis rep
private int y_cord;// y-axis rep
private int roomSize;
private int randomWall;
public Maze(int height, int width) {
this.height = height;
this.width = width;
rooms = new Room[height][width];
walls = new ArrayList<Wall>((height - 1) * (width - 1));
generateRandomMaze();
setPreferredSize(new Dimension(800, 700));
}
private void generateRandomMaze() {
generateInitialRooms();// see next method
ds = new JoinRoom(width * height);
rand = new Random(); // here is the random room generator
num = width * height;
while (num > 1) {
// when we pick a random wall we want to avoid the borders getting eliminated
randomWall = rand.nextInt(walls.size());
Wall temp = walls.get(randomWall);
// we will pick two rooms randomly
int roomA = temp.currentRoom.y + temp.currentRoom.x * width;
int roomB = temp.nextRoom.y + temp.nextRoom.x * width;
// check roomA and roomB to see if they are already members
if (ds.find(roomA) != ds.find(roomB)) {
walls.remove(randomWall);
ds.unionRooms(ds.find(roomA), ds.find(roomB));
temp.isGone = true;
temp.currentRoom.adj.add(temp.nextRoom);
temp.nextRoom.adj.add(temp.currentRoom);
num--;
}// end of if
}// end of while
}
// name the room to display
private int roomNumber = 0;
/**
* Sets the grid of rooms to be initially boxes
* This is self explanitory, we are only creating an reverse L for all
* The rooms and there is an L for the border
*/
private void generateInitialRooms() {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
// create north walls
rooms[i][j] = new Room(i, j);
if (i == 0) {
rooms[i][j].north = new Wall(rooms[i][j]);
} else {
rooms[i][j].north = new Wall(rooms[i - 1][j], rooms[i][j]);
walls.add(rooms[i][j].north);
}
if (i == height - 1) {
rooms[i][j].south = new Wall(rooms[i][j]);
}
if (j == 0) {
rooms[i][j].west = new Wall(rooms[i][j]);
} else {
rooms[i][j].west = new Wall(rooms[i][j - 1], rooms[i][j]);
walls.add(rooms[i][j].west);
}
if (j == width - 1) {
rooms[i][j].east = new Wall(rooms[i][j]);
}
rooms[i][j].roomName = roomNumber++;// we will name the rooms
}
}
// initalize entrance and exit
rooms[0][0].west.isGone = true;// you can replace .west.isGone with .north.isGone
// this is just saying the roomName for top left is 0
rooms[0][0].roomName = 0;
// we will remove the south wall of the last room
rooms[height - 1][width - 1].south.isGone = true;
// this is just saying the roomName for bottom right is the last element in the mxn room matrix
rooms[height - 1][width - 1].roomName = (height * width);
}
public void paintComponent(Graphics g) {
x_cord = 40;
y_cord = 40;
// could have taken height as well as width
// just need something to base the roomsize
roomSize = (width - x_cord) / width + 7;
// temp variables used for painting
int x = x_cord;
int y = y_cord;
for (int i = 0; i <= height - 1; i++) {
for (int j = 0; j <= width - 1; j++) {
if (!(rooms[i][j].north.isGone)) {
g.drawLine(x, y, x + roomSize, y);
}//end of north if
// west wall not there draw the line
if (rooms[i][j].west.isGone == false) {
g.drawLine(x, y, x, y + roomSize);
}// end of west if
if ((i == height - 1) && rooms[i][j].south.isGone == false) {
g.drawLine(x, y + roomSize, x + roomSize,
y + roomSize);
}// end of south if
if ((j == width - 1) && rooms[i][j].east.isGone == false) {
g.drawLine(x + roomSize, y, x + roomSize,
y + roomSize);
}// end of east if
x += roomSize;// change the horizontal
}// end of inner for loop
x = x_cord;
y += roomSize;
}// end of outer for loop
}
public static void main(String[] args) {
// we will use the scanner for userInput
Scanner userInput = new Scanner(System.in);
int m, n;// these are variables for the size of maze (m x n)
System.out.print("Enter the size of your maze: ");
// store the input
m = userInput.nextInt();
n = userInput.nextInt();
// use JFrame to put the created panel on
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 800);
frame.getContentPane().add(new Maze(m, n));
frame.pack();
frame.setVisible(true);
}// end of main
}// END OF CLASS
I once wrote a Timer class to do this, you can find it here: https://github.com/twothe/newdawn/blob/master/two/newdawn/util/TimeCounter.java
It is very simple and sufficient for most tasks.
The general difficulty with Java is that code is not executed at a constant time. Somewhere in between the Garbage Collector might interrupt your timing, or the JIT considers a piece of code to slow and suddenly optimizes it. All these things will mess up any measurements done with System.nanoTime(), so don't take the numbers as facts, but more as a tendency.
If you want to have exact numbers, you need to use more sophisticated tools and especially run the code in question a thousand or billion times to rule out background noise, but even then those numbers are only valid for your local machine, and could be entirely different on a different hardware.
It depends how you want the information. The easiest way is to use System.currentTimeInMillis() before you start generation, then again afterwards, and compare the results. That'll give you the number of ms taken to generate.
e.g.
walls = new ArrayList<Wall>((height - 1) * (width - 1));
long startTime = System.currentTimeMillis();
generateRandomMaze();
long endTime = System.currentTimeMillis();
System.out.println("Time Taken: " + (endTime-startTime) + "ms");
setPreferredSize(new Dimension(800, 700));

plotting a graph [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Hi there I am quite new to java, however I need to plot a graph in JApplet. I have managed to declare all variables and classes, the equation is working (when compiled on it's own). but all I get is a strait line! can anyone tell me what am I doing wrong please?!
in this applet the user will be asked to insert the values for abcd and the min and max values for the x axes
here is my code.......any help will be gratefully appreciated :)
package CubicEquationSolver;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.*;
public class graphApplet extends JApplet implements ActionListener {
private static class g {
public g() {
}
}
int a;
int b;
int c;
int d;
int minimumX;
int maximumX;
int minimumY;
int maximumY;
int xCoOrdinates[];
int yCoOrdinates[];
int y;
// Setting labels
JLabel labelA = new JLabel("Enter value of A");
JLabel labelB = new JLabel("Enter value of B");
JLabel labelC = new JLabel("Enter value of C");
JLabel labelD = new JLabel("Enter value of D");
JLabel labelMinX = new JLabel("Minimum X value");
JLabel labelMaxX = new JLabel("Maximum X value");
JLabel message = new JLabel("Please insert your values");
// Values will be entered here using JTextField
JTextField textA = new JTextField();
JTextField textB = new JTextField();
JTextField textC = new JTextField();
JTextField textD = new JTextField();
JTextField minX = new JTextField();
JTextField maxX = new JTextField();
JTextField ref = new JTextField("Enter value 0-1");
// declaring the layout for layout manager
JPanel north = new JPanel();
JPanel south = new JPanel();
JPanel west = new JPanel();
JPanel east = new JPanel();
JPanel center = new JPanel();
// declaring buttons using JButtons
JButton calculate = new JButton("Calculate");
JButton delete = new JButton("Delete");
JButton refine = new JButton("Refine");
// Calling from equation class
// equation eq = new equation();
private JPanel panel;
private int width = center.getWidth();
private int height = center.getHeight();
#Override
public void init() {
// setDefaultCloseOperation(EXIT_ON_CLOSE);
Container c = this.getContentPane();
this.setSize(900, 480);
this.setVisible(true);
// listener to buttons
calculate.addActionListener(this);
delete.addActionListener(this);
refine.addActionListener(this);
// listeer to user's input
textA.addActionListener(this);
textB.addActionListener(this);
textC.addActionListener(this);
textD.addActionListener(this);
minX.addActionListener(this);
maxX.addActionListener(this);
ref.addActionListener(this);
// assigning colours to panels to be distinguished
north.setBackground(Color.LIGHT_GRAY);
south.setBackground(Color.LIGHT_GRAY);
west.setBackground(Color.YELLOW);
east.setBackground(Color.GREEN);
center.setBackground(Color.GRAY);
// Declaring border
BorderLayout layoutBorder = new BorderLayout();
// setting up the grid (x rows, y clumns, space, space)
GridLayout layoutGrid = new GridLayout(2, 8, 4, 4);
// layout grid
north.setLayout(layoutGrid);
// set labels
north.add(labelA);
north.add(labelB);
north.add(labelC);
north.add(labelD);
north.add(labelMinX);
north.add(labelMaxX);
north.add(ref);
// calculate button
north.add(calculate);
// text boxes
north.add(textA);
north.add(textB);
north.add(textC);
north.add(textD);
north.add(minX);
north.add(maxX);
north.add(refine);
// delete button
north.add(delete);
south.add(message);
// border layout
c.add(north, BorderLayout.NORTH);
c.add(south, BorderLayout.SOUTH);
c.add(center, BorderLayout.CENTER);
// c .add(west, BorderLayout.WEST);
// c .add(east, BorderLayout.EAST);
// panel = new JPanel();
// panel.setPreferredSize(new Dimension(width, height));
// panel.setBackground(Color.GRAY);
// center.add(panel);
}
#Override
public void actionPerformed(ActionEvent e) // throws NumberFormatException
{
// dafault message will be <message> -- "Please insert values"
message.setText(e.getActionCommand());
// when button "Delete" is pressed all values in text firlds will turn
// null
if (e.getActionCommand().equals("Delete")) {
message.setForeground(Color.DARK_GRAY);
textA.setText(null);
textB.setText(null);
textC.setText(null);
textD.setText(null);
minX.setText(null);
maxX.setText(null);
repaint();
} else if (e.getActionCommand().equals("Calculate"))
// when "Calculate" button is pressed, values will be attached to
// equation
try {
message.setForeground(Color.DARK_GRAY);
// -------------------------------------------------
a = Integer.parseInt(textA.getText());
b = Integer.parseInt(textB.getText());
c = Integer.parseInt(textC.getText());
d = Integer.parseInt(textD.getText());
minimumX = Integer.parseInt(minX.getText());
maximumX = Integer.parseInt(maxX.getText());
System.out.println("center.getWidth() " + center.getWidth());
System.out.println("center.getHeight() " + center.getHeight());
System.out.println("minimum " + minX.getText());
System.out.println("maximum " + maxX.getText());
System.out.println("a " + textA.getText());
System.out.println("b " + textB.getText());
System.out.println("c " + textC.getText());
System.out.println("d " + textD.getText());
// ------------------------------------------------------
message.setText("This is the result for " + "A "
+ textA.getText() + ", B " + textB.getText() + ", C "
+ textC.getText() + ", D " + textD.getText());
draw();
}
catch (NumberFormatException ex)
// if user inputs other than numbers, a warning message in the south
// panel will show
{
message.setText("Please insert numerical value in "
+ ex.getMessage());
message.setForeground(Color.red);
message.setFont(new Font("Tahoma", Font.BOLD, 12));
}
else if (e.getActionCommand().equals("Refine")) {
// for refine
}
}
// ===================================================================================
private void calculation() {
xCoOrdinates = new int[(maximumX - minimumX) + 1];
yCoOrdinates = new int[(maximumX - minimumX) + 1];
for (int i = 0; i < xCoOrdinates.length; i++)
// for(int j = 0; j < yCoOrdinates.length; j++)
{
// generating the x co-ordinates and storing them in arrays
xCoOrdinates[i] = minimumX + i;
// generating the y co-ordinates using the formula given
y = ((a * (int) Math.pow(i, 3)) + (b * (int) Math.pow(i, 2))
+ (c * i) + (d));
// storing y co-ordinates
yCoOrdinates[i] = y;
// displaying results
// System.out.println("X = " + i + " Y = " + getY());
System.out.println("These are the values of X = " + i);
}
// printing the y axes values
for (int i = 0; i < yCoOrdinates.length; i++) {
System.out.println("this is the extracted Y " + yCoOrdinates[i]);
}
maximumX = xCoOrdinates[0];
maximumX = xCoOrdinates[0];
for (int i = 1; i < yCoOrdinates.length; i++) {
if (yCoOrdinates[i] > maximumX)
maximumX = xCoOrdinates[i];
else if (yCoOrdinates[i] < minimumX)
minimumX = xCoOrdinates[i];
}
System.out.println("MAXX is " + maximumX);
System.out.println("MINX is " + minimumX);
maximumY = yCoOrdinates[0];
minimumY = yCoOrdinates[0];
for (int i = 1; i < yCoOrdinates.length; i++) {
if (yCoOrdinates[i] > maximumY)
maximumY = yCoOrdinates[i];
else if (yCoOrdinates[i] < minimumY)
minimumY = yCoOrdinates[i];
}
System.out.println("MAXY is " + maximumY);
System.out.println("MINY is " + minimumY);
}
// =================================================================================================
public void draw() {
Graphics g = center.getGraphics();
g.setColor(Color.GRAY);
g.fillRect(0, 0, center.getWidth(), center.getHeight());
// g.fillRect(25,25, center.getWidth()-50, center.getHeight()-50);
double x, y, nextX, nextY;
int xPoint; // = 0;
int yPoint; // = 0;
int nextXpoint; // = 0;
int nextYpoint; // = 0;
g.setColor(Color.BLUE);
for (xPoint = 0; xPoint <= (double) center.getWidth(); xPoint++) {
x = scaleX(xPoint);
y = equation(x);
yPoint = scaleY(y);
nextXpoint = xPoint + 1;
nextX = scaleX(nextXpoint);
nextY = equation(nextX);
nextYpoint = scaleY(nextY);
g.drawLine(xPoint, yPoint, nextXpoint, nextYpoint);
// System.out.println("equation --->" + eq.getY());
}
}
private double equation(double x) {
return y;
// return a*x*x*x + b*x*x + c*x + d;
}
private double scaleX(int xPoint) {
int minXstart = minimumX;
int maxXend = maximumX;
double xScale = (double) center.getWidth() / (maxXend - minXstart);
return (xPoint - (center.getWidth() / 2)) / xScale;
}
private int scaleY(double y) {
int minYstart = minimumY;
int maxYend = maximumY;
int yCoord;
double yScale = (double) center.getHeight() / (maxYend - minYstart);
yCoord = (int) (-y * yScale) + (int) (center.getHeight() / 2);
return yCoord;
}
}
There are 3rd party libraries out there to do this type of work for you. Check out:
JFreeChart
Charts4J
Short term help: Check your output, do the values of x and y vary as expected? are they actually used during plotting? Use a debugger to step through your code. Then come back with a more focused questions.
Mid term (within the next two days): Please buy and read the following two books:
http://www.amazon.com/Pragmatic-Programmer-Andrew-Hunt/dp/020161622X
http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?s=books&ie=UTF8&qid=1342369060&sr=1-1&keywords=clean+code
Classes as long as the one you posted are not acceptable, and make it next to impossible to understand the revlevant part. This is the reason why you received the down votes I'd guess.
I'm a JFreeChart fan, but you can also plot graphs using Cartesian coordinates in Java 2D, as suggested here.

Categories