Repeating drawLine() to draw vertical bars Java - java

I was given an assignment and have been able to complete it, but I feel there must be a easier way to complete it.
I was tasked to draw 60 vertical bars with a width of 5 and random heights.
public void paintComponent( Graphics g )
{
super.paintComponent( g );
g.setColor( color );
int width = getWidth();
int height = getHeight();
int x, h;
// bar with a width of 5 and random heights
h = rd.nextInt(height); //random height
x = 50;
g.drawLine( x, height, x, height-h ); //Bar 1
g.drawLine( x+1, height, x+1, height-h );
g.drawLine( x+2, height, x+2, height-h );
g.drawLine( x+3, height, x+3, height-h );
g.drawLine( x+4, height, x+4, height-h );
g.drawLine( x+6, height, x+6, height-h -12 ); // Bar 2
g.drawLine( x+7, height, x+7, height-h -12 );
g.drawLine( x+8, height, x+8, height-h -12 );
g.drawLine( x+9, height, x+9, height-h -12 );
g.drawLine( x+10, height, x+10, height-h -12);
What I have done is just repeat this for all 60 bars and just change the offset at the end of height-h +/- * and left a space of 1 between bars
This seems like a very long way to do this. Any suggestions on how to implement this without repeating it 60 times.
Edit: Added an image of the final project.
Here is the finished look ![1]
[1]: http://i.stack.imgur.com/3ivpM.png

Looking at the other answers, no one states the obvious:
To draw 60 bars, you don't need to draw more than 60 items (certainly not 60x5=300 lines).
Your options:
draw the bars as filled rectangles
draw the bars as lines with a width of 5
Also the bar values should not be calculated while painting, they're supposed to be the data model.
public class Bars extends JPanel {
private double[] barValues;
private final static int BAR_WIDTH = 5;
private final static int BAR_GAP = 3;
public Bars () {
barValues = new double[60];
for (int i = 0; i < barValues.length; i++) {
barValues[i] = Math.random();
}
}
...
}
Painting using rectangles:
#Override
protected void paintComponent (Graphics g) {
Dimension size = getSize();
g.setColor(Color.white);
g.fillRect(0, 0, size.width, size.height);
g.setColor(new Color(0x445566));
for (int i = 0; i < barValues.length; i++) {
int h = (int) Math.round(barValues[i] * size.height);
int x = (i * (BAR_WIDTH + BAR_GAP));
int y = size.height - 1 - h;
int w = BAR_WIDTH;
g.fillRect(x, y, w, h);
}
}
Painting using lines of width 5:
#Override
protected void paintComponent (Graphics g) {
Dimension size = getSize();
g.setColor(Color.white);
g.fillRect(0, 0, size.width, size.height);
g.setColor(new Color(0x445566));
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(5, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER));
for (int i = 0; i < barValues.length; i++) {
int h = (int) Math.round(barValues[i] * size.height);
int x = (i * (BAR_WIDTH + BAR_GAP)) + BAR_WIDTH / 2;
int y = size.height - 1 - h;
g.drawLine(x, y, x, y + h);
}
}

You could use a for loop with %
for(int i = 0, int j = 0 ; i < 360 ; i++ ) {
if(i % 5 != 0 ) {
g.drawLine( x+i, height, x+i, height-h - j);
}
if(i % 6 = 0)
j = j - 12;
}
I think that's right for what you want. I have made some assumptions:
You skip every 6th line to leave a space
You increase j by negative 12 every second line

why you don't use for loop and bunch of if statements!
for(int i = 0; i < 60; i++) {
if( i < 5) {
}
if( i > 5 && i < 10) {
}
// etc..
}

This is the second try :P
public void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
System.out.println("getWidth = " + getWidth());
System.out.println("getHeight = " + getHeight());
Random rd = new Random();
int x = 50;
for (int i = 0; i <= 60; i++) {
int fisrt = (i / 12) * 12;
for (int j = 0; j < 12; j++) {
int h = rd.nextInt(height); // random height
g.drawLine(x + j, height, x + j, height - h - fisrt);
}
}
}

This is a great example of when to use a loop. To draw the first five lines you need something like this.
public void drawLines(int x, int height, int h, int j){
for(int i = 0; i < 5; i++){
g.drawLine(x + i, height, x + i, height - h - j);
}
}
However, this is not complete because you have to do this multiple times. just use another for loop.
for(int i = 0; i < 12, i++){
drawLines(x + i * 5, height, h, i * 12);
}

What you saw but didn't know it
You saw a pattern of repeating code. In time and probably after an algorithm class you should be able to pre-predict patterns, some are obvious some are not. This is where reasoning, deductive and math skills come in. Which goes in the order of:
I am repeating myself...
Why am I repeating this
Is this is a basic pattern?
If I am not seeing a basic pattern...can this code be broken down further?
What is changing increase/decreasing on each same line of code
What coding idiom (loop, do-while,collection etc) do I know that best deals with this
This is also why keeping code methods short and to the point allows you to see the above more clearly.
But more important before you code: design your objects beforehand. This will allow you to solve 99 problems before you even have to deal with the coding aspect.
A good design can work in any code of that type (in this case OO/object orientated).
(Some might argue to keep the second loop in the code below to its separate method to keep it clean, readable and allow you to reuse it again.)
Your Solution
Create a method to get your barWidth and this should be your whole paintComponent method. Everything is commented and all variables are clearly defined in what they do, but if you require any help understanding any part do say.
I am not sure why you have rd as a global field.
public void paintComponent( Graphics g ) {
// Carry out super first
super.paintComponent( g );
// Set all field types at start
int totalWidth, totalHeight, barHeight, barWidth, totalBarsRequired;
// Set all constant fields
barWidth = 5; // THE BAR WIDTH IS SET HERE (Create a method)
// Set all method fields
totalWidth = getWidth();
totalHeight = getHeight();
// No need to set the bars as we can calculate them from the bar width
totalBarsRequired = (int) totalWidth / barWidth;
// Look over all the bars required
for( int barNumber = 0 ; barNumber < totalBarsRequired ; barNumber++ ) {
// Set a new random height each bar
barHeight = rd.nextInt( totalHeight );
// Create the lines and loop until the barWidth has been met
for (int barLineNumber = 0 ; barLineNumber < barWidth ; barLineNumber++ ) {
g.drawLine( (barNumber * barWidth) + barLineNumber, barHeight, (barNumber * barWidth) + barLineNumber, barHeight );
}
}
}

Related

Processing Java - Problem with draw an eclipse or load pic

i'm testing a code in Processing with Java for my school.
I try to create a game and i have a problem to draw an eclipse or to load a picture.
I think the picture or the eclipse is drawing under my game board .. I don't know how to solved it.
I have a txt file for the game board ( by level).
An example :
110000000
000000031
000000000
100000000
000000000
000000000
200000001
Please, can you help me
thank you
int cols, rows, w, x, y,level;
String lines[];
PImage flag;
void setup() {
size(460,360);
cols = 9;
rows = 7;
w = 50 ;
x= 0;
y = 0;
level = 1;
lines = loadStrings("../../data/niveau"+level+".iwk");
flag = loadImage("../../data/flag.png");
ellipseMode(CORNER);
}
void draw() {
String lines[]= loadStrings("../../data/niveau"+level+".iwk");
loadCard(cols,rows,w,x,y,lines,flag);
}
void loadCard(int cols, int rows, int w, int x,int y,String lines[],PImage flag) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if(lines[i].charAt(j) == '1'){
fill(156, 158, 162);
}
else if(lines[i].charAt(j) == '2'){
fill(225, 169, 26) ;
ellipse(x,y,w/2,w/2);
}
else if(lines[i].charAt(j) == '3'){
image(flag,x,y,w/2,w/2);
}else {
fill(23, 159, 215);
}
rect(x, y, w, w);
x = x + w ;
}
y = y + w ;
x = 0 ;
}
}
It is indeed drawn under the game board.
Check the loadCard function. First the ellipse / image is draw, then a rect is draw with the same x / y, ergo on top of it.
A modified your code a little, it should show the ellipses / image
void loadCard(int cols, int rows, int w, int x,int y,String lines[],PImage flag) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
//draw default so ellipse / img has a background
fill(23, 159, 215);
rect(x, y, w, w);
//draw other cases on top of default
if(lines[i].charAt(j) == '1'){
fill(156, 158, 162);
rect(x, y, w, w);
}
else if(lines[i].charAt(j) == '2'){
fill(225, 169, 26) ;
ellipse(x,y,w/2,w/2);
}
else if(lines[i].charAt(j) == '3'){
image(flag,x,y,w/2,w/2);
}
x = x + w ;
}
y = y + w ;
x = 0 ;
}
}
Since you're learning, allow me to give you 2 tips:
loadStrings() needs to happen only once per level. You should not put it in draw(), because draw() is called every frame. It is already called in setup, that is fine for now. Eventually you can put it in a separate function, and call this function at the beginning of a new level.
If you use a double for loop to draw a game board, you can use the iterators (int i and int j) as x/y variables. Instead of rect(x, y, w, w); you can use rect(i*w, j*w, w, w);. This way you'll have fewer variables to manage.

Recursive changing variables - Sierpinski carpet

I'm having some problems whit drawing a sierpinski carpet, and would apreciate any help.
I was able to define the stoping condition, draw the central rectangle, and recursively, draw the next level of the image, all while keeping count.
It just so happens that I can only draw on the top left side. I'd say I'm confusing variables, but I can't seem to figure it out. Would apreciate any help
This is the part of the code where i'm having problems.
int smallerWidth = newWidth / 3;
int smallerHeight = newHeight / 3;
int sX = 0;
int sY = 0;
if (currentDeep > 1) {
for (int i = 0; i < 3; i++) {
sX = width / 9 + (i * 3 * (width / 9));
sY = height / 9;
g.fillRect(sX, sY, smallerWidth, smallerHeight);
for (int j = 0; j < 3; j++) {
sY = height / 9 + (j * 3 * (height / 9));
g.fillRect(sX, sY, smallerWidth, smallerHeight);
}
}
return 1 + printSquares(g, sX, sY, newWidth, newHeight, currentDeep
- 1);
} else
return 1;
}
This is the full code
https://pastebin.com/WPJ5tG8w
In sum my question is. What should I change/create in order for my program to draw the remaining 7 squares?
The issue with your code is, that you are trying to perform actions for multiple layers of the recursion at once. Normally, in the recursion, you would only paint the Quadrado central, calculate the sizes and coordinates of the smaller rectangles, and call the method recursively. That way you ensure that the recursive calls do not influence the stuff that is already there.
private int printSquares(Graphics g, int xi, int yi, int width, int height, int currentDeep) {
//Quadrado central
int newWidth = width / 3;
int newHeight = height / 3;
int x = (width / 3) + xi;
int y = (height / 3) + yi;
g.fillRect(x, y, newWidth, newHeight);
int sX = 0;
int sY = 0;
if (currentDeep > 1) {
int sum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
//This is the position of each of the small rectangles
sX = i * (width / 3) + xi;
sY = j * (height / 3) + yi;
// Call the method recursively in order to draw the smaller rectangles
sum += printSquares(g, sX, sY, newWidth, newHeight, currentDeep - 1);
}
}
return 1 + sum;
} else
return 1;
}
I hope, this resolves you issue.
I hope this is ok. This is amazing code. I took the liberty to complete this with the original code provided in the question and added the code that fixed it that Illedhar recommended as a added method. Here it is. Thank you for sharing this.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class sierpinskicarpet {
public static Color BACKGROUNDCOLOR = new Color(0, 0, 150);
public static Color FOREGROUNDCOLOR = new Color(255, 180, 0);
// Padrao = 5, alterado
public static int DEEP = 10;
/**
* Build the frame and shows it
*/
public sierpinskicarpet(int deep) {
// the frame and title
JFrame frame = new JFrame();
frame.setTitle("...: Recursive Squares with deep " + deep + " :...");
// Dispose frame on click on close button
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
// set size and center frame on screen
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
// add print area occupying all the frame content area
frame.add(new PrintArea(deep));
// put frame visible
frame.setVisible(true);
}
/**
* Main method
*/
public static void main(String[] args)
{
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
// launch for 1 to DEEP squares frames
for (int i = DEEP; i >= 1; --i) {
// build a new object each time: objects will run
// independently
new sierpinskicarpet(i);
}
}
});
}
}
/**
* Our print area is, in fact, a label extended with the paint squares behavior
*/
class PrintArea extends JLabel {
private static final long serialVersionUID = 1L;
// local deep variable, will keep the registered deep for this the print
// area
int deep;
/**
* constructor
*/
public PrintArea(int deep) {
// call super, that is JLabel, constructor
super();
// set background color and set as well opaque to allow the background
// to be visible
setBackground(sierpinskicarpet.BACKGROUNDCOLOR);
setOpaque(true);
// save the deep
this.deep = deep;
}
/**
* paint method, called by JVM, when it is needed to update the PrintArea
*/
public void paint(Graphics g) {
// call paint from the JLABEL, draws the background of the PrintArea
super.paint(g);
// set drawing color
g.setColor(sierpinskicarpet.FOREGROUNDCOLOR);
// call the amazing print square method
int n = printSquares(g, 0, 0, getWidth(), getHeight(), this.deep);
// put to the world how much squares we printed
System.out.println("Deep = " + deep + ", squares painted: " + n);
}
/**
* Auxiliary method that will to the work. It must print a square with 1/3
* of the length of the frame and at the center and if not the bottom level
* ask to do the same for each of the other 8 square with 1/3 of length but
* called with the new deep
*/
private int printSquares(Graphics g, int xi, int yi, int width, int height, int currentDeep) {
//Quadrado central
int newWidth = width / 3;
int newHeight = height / 3;
int x = (width / 3) + xi;
int y = (height / 3) + yi;
g.fillRect(x, y, newWidth, newHeight);
int sX = 0;
int sY = 0;
if (currentDeep > 1) {
int sum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
//This is the position of each of the small rectangles
sX = i * (width / 3) + xi;
sY = j * (height / 3) + yi;
// Call the method recursively in order to draw the smaller rectangles
sum += printSquares(g, sX, sY, newWidth, newHeight, currentDeep - 1);
}
}
return 1 + sum;
} else
return 1;
}
}
/*
Works Cited:
Recursive changing variables - sierpinski carpet. Stack Overflow. Retrieved May 4, 2022,
from https://stackoverflow.com/questions/49945862/recursive-changing-variables-sierpinski-carpet
*/

convert Random text to image with random noise in java

I am implementing captcha feature in our project. Its basically Tapestry framework application. I am generating random alfa-numeric string and convert it to image and display it in web page.
Now what i need is, i want to add random noise like dots lines etc to make image with text unclear. How to proceed please help.
keeping the code for reference .
-- This method gives text captcha.
`
public String generateCaptcha() {
Random random = new Random();
int min = 4; // Inclusive
int max = 9; // Exclusive
int length = random.nextInt(max-min) + min;
StringBuilder captchaStringBuffer = new StringBuilder();
for (int i = 0; i < length; i++) {
int captchaNumber = Math.abs(random.nextInt()) % 60;
int charNumber = 0;
if (captchaNumber < 26) {
charNumber = 65 + captchaNumber;
}
else if (captchaNumber < 52){
charNumber = 97 + (captchaNumber - 26);
}
else {
charNumber = 48 + (captchaNumber - 52);
}
captchaStringBuffer.append((char)charNumber);
}
return captchaStringBuffer.toString();
}
`
-- This method converts generated captcha to Image with out any noise.
`
public void textToImage(String displayCode){
String text = displayCode;
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
Font font = new Font("Arial", Font.PLAIN, 48);
g2d.setFont(font);
FontMetrics fm = g2d.getFontMetrics();
int width = fm.stringWidth(text);
int height = fm.getHeight();
g2d.dispose();
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
g2d = img.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,
RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING,
RenderingHints.VALUE_DITHER_DISABLE);
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_DEFAULT);
g2d.setFont(font);
fm = g2d.getFontMetrics();
g2d.setColor(Color.BLACK);
g2d.drawString(text, 0, fm.getAscent());
g2d.dispose();
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "png", baos);
byte[] res=baos.toByteArray();
setBinaryImage("data:image/png;base64,"+Base64.encode(res));
} catch (IOException e) {
}
}
`
I am newbie so please tell in clear what ever you say.
Thanks in Advance :-)
When trying to obstruct the text that is being displayed, you can use:
Dots/Circles, spread randomly over the image with varying size and color
Lines, coming from a random point on the edge of the image to another point on the edge of the image. These can also vary in color and thickness.
As far as i know, you can use g2d.drawLine(x1, y1, x2, y2) to draw a line. Since you want it to go from the edge to another point on the edge, you have to limit your random-point-generation. You can use this approach:
public Point pointOnEdge(int width, int height) {
int side = (int) (Math.random() * 3); //0=top, 1=bot, 2=left, 3=right
int x = 0;
int y = 0;
switch(side) {
case 0:
//when on top, y is at the top of the image (0) and x is something in [0, width]
y = 0;
x = (int) (Math.random() * width);
break;
case 1:
//when on bottom, y is at the bottom of the image (image height) and x is something in [0, width]
y = height;
x = (int) (Math.random() * width);
case 2:
//when on left, x is at the left side (0) of the image and y is something in [0, height]
y = (int) (Math.random() * height);
x = 0;
break;
case 3:
//when on left, x is at the left side (0) of the image and y is something in [0, height]
y = (int) (Math.random() * height);
x = width;
break;
}
return new Point(x, y);
}
If you create two Points like that, and connect them with a line, then you have a pretty simple way of obstructing your Image Partially, thus distorting it.
Now to the Circles:
public void drawCircles(Graphics2D g2d, int width, int height) {
//draw 10 of them
for(int i = 0; i < 10; i++) {
//select a random size
int x = 10 + (int) (Math.random() * 10);
//draw circle at random position with the created size
g2d.fillOval((int) (Math.random() * width), (int) (Math.random() * height), x, x);
}
}
And like that you are now able to distort your image to make it hard to read.
I hope you have enough common code understanding to know where to put these function calls. If not, I can add it if nescessary.
EDIT 1
If you want a dotted Background for your Captcha, you can use this code before rendering the String or anything else:
boolean r = false;
boolean g = false;
for(int y = 0; y < height; y++) {
r = !r;
g = r;
for(int x = 0; x < width; x++) {
g = !g;
if(g) {
g2d.setColor(Color.GRAY);
}else {
g2d.setColor(Color.WHITE);
}
g2d.drawLine(x, y, x, y);
}
}
EDIT 2
I would recommend, that you use a different font. Then you dont have to do any streching. Good fonts for that are e.g. Gigi. You could also select a font randomly by using GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames() which returns all Fonts that Java has.

Input an image from some saved location on computer

I have a draw function
public void drawBoard(Graphics g) {
int height = this.getHeight();
int width = this.getWidth();
int dx = width / 7;
int dy = height / 6;
for (int x = 0, row = 0; x <= width && row < gameboard.length; row++, x += dx) {
for (int col = 0, y = 0; y <= height&& col < gameboard[0].length; y += dy, col++) {
if (gameboard[row][col] == 0) {
g.setColor(Color.GRAY);
g.fillOval(y, x, dy, dx);
} else if (gameboard[row][col] == 1) {
g.setColor(Color.RED);
g.fillOval(y, x, dy, dx);
} else if(gameboard[row][col] == 1){
g.setColor(Color.BLACK);
g.fillOval(y, x, dy, dx);
} else if(gameboard[row][col]==3){
}else if(gameboard[row][col]==4){
}else if(gameboard[row][col]==5){
}else if(gameboard[row][col]==6){
}else if(gameboard[row][col]==7){
}else if(gameboard[row][col]==8){
}else if(gameboard[row][col]==9){
}
}
}
}
However for when gameboard[row][col]=3,4,...9 I want it to change that slot into a picture downloaded from the web. How do I do that?
I would prefer to do it without a URL definition and simply a get Document like thing in html where I have the photos saved in a file
First, you need to get your image as a BufferedImage. I suggest using the ImageIO class:
String imageFileName = "myTestFile.jpg"
BufferedImage img = ImageIO.read(((new File(imageFileName)).toURI()).toURL());
Next, you want to draw your image using the Graphics.drawImage() API. Your comment indicates that you think you'll need to scale the image, so use the appropriate drawImage method to do that. Using your Graphics object g from your code above, this might look like::
int oldWidth = img.getWidth();
int oldHeight = img.getHeight();
int newWidth = 10; //You decide this...
int newHeight = 10; //You decide this too...
g.drawImage(img, 0, 0, oldWidth, newWidth, 0, 0, newWidth, newHeight, null);
Oracle themselves have an applet which demonstrates the code for this approach, along with a number of other common operations you might want to do on images in their ImageDrawingApplet.java code

Drawing lines in Java

Alright, so I am having a problem writing this program. I have the first part done but I don't know how to finish it. I've tried different solutions and everything, but yet I still have no clue. Here is what I have so far. What I need to do is make this where it will start in all four corners.
public void paintComponent( Graphics g )
{
super.paintComponent( g );
int width = getWidth();
int height = getHeight();
int number, x, y, dx, dy;
x = 0;
y = height;
number = 15;
dx = width / number;
dy = height / number;
for ( int i = 1; i < number; i++ )
{
x += dx;
y -= dy;
g.drawLine( 0, 0, x, y );
}
}
I gather that you want to draw a fan-out of 15 lines from each corner to the facing diagonal. I'd suggest writing a routine to draw a fan from a point to an arbitrary line segment and then use that:
drawFan(Graphics g,
int number, // number of fan lines
int x0, int y0, // coordinates of the point
int sx, int sy, // coordinates of the line segment start
int ex, int ey) // coordinates of the line segment end
{
int x = sx,
y = sy,
dx = (ex - sx) / number,
dy = (ey - sy) / number;
for (int i = 1; i < number; ++i) {
x += dx;
y += dy;
g.drawLine(x0, y0, x, y);
}
}
You can then call this with the appropriate values for each corner and diagonal.
public void paintComponent( Graphics g )
{
super.paintComponent( g );
int width = getWidth();
int height = getHeight();
drawFan(g, 15, 0, 0, 0, height, width, 0); // top left corner
drawFan(g, 15, 0, height, 0, 0, width, height); // bottom left corner
drawFan(g, 15, width, height, 0, height, width, 0); // bottom right corner
drawFan(g, 15, width, 0, 0, 0, width, height); // top right corner
}
Here is the solution, my suggestion is to understand how the coordinate system works in Java then It'll be easy.
public void paintComponent( Graphics g ){
super.paintComponent(g);
int widthX = getWidth();
int heightY = getHeight();
int num, i, j;
num = 15;
i = 0;
j = 15;
while( i != 16 && j != -1 ){
g.drawLine( 0, 0, widthX*i/num, heightY*j/num );
g.drawLine( widthX*i/num, heightY*j/num, widthX, heightY );
g.drawLine( widthX*i/num, heightY*i/num, widthX, 0);
g.drawLine( widthX*j/num, heightY*j/num, 0, heightY);
i++;
j--;
}//end while
}//end method paintComponent

Categories

Resources