Why doesn't my GUI show squares after repaint()? [duplicate] - java

I posted this question a bit earlier and was told to make it SSCCE so here goes (if I can make any improvements feel free to let me know):
I'm wondering why when my button "confirm" is clicked the old squares disappear and the redrawn squares do not appear on my GUI (made with swing). The Squares class draws 200 spaced out squares with an ID (0, 1, 2, or 3 as String) inside obtained from a different class (for the purpose of this question, let's assume it is always 0 and not include that class). For clarification: Squares draws everything perfectly the first time (also retrieves the correct IDs), but I want it to redraw everything once the button is clicked with new IDs.
Code for Squares:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.util.ArrayList;
public class Squares extends JPanel{
private ArrayList<Rectangle> squares = new ArrayList<Rectangle>();
private String stringID = "0";
public void addSquare(int x, int y, int width, int height, int ID) {
Rectangle rect = new Rectangle(x, y, width, height);
squares.add(rect);
stringID = Integer.toString(ID);
if(ID == 0){
stringID = "";
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
FontMetrics fm = g2.getFontMetrics();
int fontAscent = fm.getAscent();
g2.setClip(new Rectangle(0,0,Integer.MAX_VALUE,Integer.MAX_VALUE));
for (Rectangle rect : squares) {
g2.drawString(stringID, rect.x + 7, rect.y + 2 + fontAscent);
g2.draw(rect);
}
}
}
Code for GUI:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUIReserver extends JFrame implements Runnable{
private int myID;
private JButton confirm = new JButton("Check Availability and Confirm Reservation");
private JFrame GUI = new JFrame();
private Squares square;
public GUIReserver(int i) {
this.myID = i;
}
#Override
public void run() {
int rows = 50;
int seatsInRow = 4;
confirm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
GUI.getContentPane().remove(square);
square = new Squares();
int spaceNum = 0;
int rowNum = 0;
int offsetX = 200;
int offsetY = 0;
for(int i = 0; i < rows * seatsInRow; i++){
square.addSquare(rowNum * 31 + offsetX,spaceNum * 21 + 50 + offsetY,20,20, 0); //normally the 4th parameter here would retrieve the ID from the main class
rowNum++;
if(rowNum == 10){
rowNum = 0;
spaceNum++;
}
if(spaceNum == 2){
spaceNum = 3;
rowNum = 0;
}
if(spaceNum == 5){
spaceNum = 0;
offsetY += 140;
}
}
GUI.getContentPane().add(square); //this does not show up at all (could be that it wasn't drawn, could be that it is out of view etc...)
GUI.repaint(); //the line in question
}
});
GUI.setLayout(new FlowLayout());
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setLocation(0,0);
GUI.setExtendedState(JFrame.MAXIMIZED_BOTH);
square = new Squares();
int spaceNum = 0;
int rowNum = 0;
int offsetX = 200;
int offsetY = 0;
for(int i = 0; i < rows * seatsInRow; i++){
square.addSquare(rowNum * 31 + offsetX,spaceNum * 21 + 50 + offsetY,20,20, 0); //normally the 4th parameter here would retrieve the ID from the main class
rowNum++;
if(rowNum == 10){
rowNum = 0;
spaceNum++;
}
if(spaceNum == 2){
spaceNum = 3;
rowNum = 0;
}
if(spaceNum == 5){
spaceNum = 0;
offsetY += 140;
}
}
GUI.getContentPane().add(square); //this shows up the way I wish
GUI.add(confirm);
GUI.pack();
GUI.setVisible(true);
}
}
Code for main:
public class AircraftSeatReservation {
static AircraftSeatReservation me = new AircraftSeatReservation();
private final int rows = 50;
private final int seatsInRow = 4;
private int seatsAvailable = rows * seatsInRow;
private Thread t3;
public static void main(String[] args) {
GUIReserver GR1 = new GUIReserver(3);
me.t3 = new Thread(GR1);
me.t3.start();
}
}

One major problem: Your Squares JPanels preferred size is only 20 by 20, and will likely actually be that size since it seems to be added to a FlowLayout-using container. Next you seem to be drawing at locations that are well beyond the bounds of this component, and so the drawings likely will never be seen. Consider allowing your Squares objects to be larger, and make sure to only draw within the bounds of this component.
Note also there is code that doesn't make sense, including:
private int myID;
private JTextField row, column, instru draft saved // ???
package question2;ction1, instruction2, seatLabel, rowLabel; // ???
I'm guessing that it's
private int myID;
private JTextField row, column, instruction1, instruction2, seatLabel, rowLabel;
And this won't compile for us:
int rows = AircraftSeatReservation.getRows();
int seatsInRow = AircraftSeatReservation.getSeatsInRow(); // and shouldn't this take an int row parameter?
since we don't have your AircraftSeatReservation class (hopefully you don't really have static methods in that class).
And we can't compile or run your current code. We don't want to see your whole program, but rather you should condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem. So as Andrew Thompson recommends, for better help, please create and post your Minimal, Complete, and Verifiable example or Short, Self Contained, Correct Example.
I would try to OOP-ify your problem as much as possible, to allow you to divide and conquer. This could involve:
Creating a SeatClass enum, one with possibly two elements, FIRST and COACH.
Creating a non-GUI Seat class, one with several fields including possibly: int row, char seat ( such as A, B, C, D, E, F), a SeatClass field to see if it is a first class seat or coach, and a boolean reserved field that is only true if the seat is reserved.
This class would also have a getId() method that returns a String concatenation of the row number and the seat char.
Creating a non-GUI Airplane class, one that holds two arrays of Seats, one for SeatClass.FIRST or first-class seats, and one for SeatClass.COACH.
It would also have a row count field and a seat count (column count) field.
After creating all these, then work on your GUI classes.
I'd create a GUI class for Seats, perhaps GuiSeat, have it contain a Seat object, perhaps have it extend JPanel, allow it to display its own id String that it gets from its contained Seat object, have it override getBackground(...) so that it's color will depend on whether the seat is reserved or not.
etc.....

Related

Finding solution to maze in java

I have a project to have a red dot inside the first box of a maze i randomly generated and the dot is supposed to follow its way through the boxes and find the end of the maze. Now if it hits a dead end, its supposed to go back to where its path started and not go back down that path, that leads to a dead end. i made it so each box represents the #1, this way when the red dot travels over the box, it increments by 1, so it can realize where its been. its always supposed to go to the lowest number possible so it can never go back to the dead ends its already been to. i am able to reach the end of the maze but i come into 2 problems.
the method i wrote that does all this work is the solve() function. I cant understand why 2 things happen...
1st thing is that when the red dot comes to a branch of dead ends, sometimes itll just go to one dead end, to a different dead end , back to the same dead end.. traveling to the same 'numbers' when im trying to have it only go towards the boxes that have 1's or just the lower numbers.
2nd thing is that once it inevitably reaches the end of the maze.. the red dot goes into the green area, where i specifically say in the while loop, it can not be in a green box.
if M[y][x] = 0, its a green box and if its = 1 its a black box. anything higher than 1 will also be inside the box.
your help is highly appreciated as ive been stuck on this problem for hours and cant seem to find out the problem.
the problem persists in the solve() method
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
import javax.swing.*;
public class mazedfs extends JFrame implements KeyListener
{
/* default values: */
private static int bh = 16; // height of a graphical block
private static int bw = 16; // width of a graphical block
private int mh = 41; // height and width of maze
private int mw = 51;
private int ah, aw; // height and width of graphical maze
private int yoff = 40; // init y-cord of maze
private Graphics g;
private int dtime = 40; // 40 ms delay time
byte[][] M; // the array for the maze
public static final int SOUTH = 0;
public static final int EAST = 1;
public static final int NORTH = 2;
public static final int WEST = 3;
public static boolean showvalue = true; // affects drawblock
// args determine block size, maze height, and maze width
public mazedfs(int bh0, int mh0, int mw0)
{
bh = bw = bh0; mh = mh0; mw = mw0;
ah = bh*mh;
aw = bw*mw;
M = new byte[mh][mw]; // initialize maze (all 0's - walls).
this.setBounds(0,0,aw+10,10+ah+yoff);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try{Thread.sleep(500);} catch(Exception e) {} // Synch with system
this.addKeyListener(this);
g = getGraphics(); //g.setColor(Color.red);
setup();
}
public void paint(Graphics g) {} // override automatic repaint
public void setup()
{
g.setColor(Color.green);
g.fill3DRect(0,yoff,aw,ah,true); // fill raised rectangle
g.setColor(Color.black);
// showStatus("Generating maze...");
digout(mh-2,mw-2); // start digging!
// digout exit
M[mh-1][mw-2] = M[mh-2][mw-1] = 1;
drawblock(mh-2,mw-1);
solve(); // this is the function you will write for parts 1 and 2
play(); // for part 3
}
public static void main(String[] args)
{
int blocksize = bh, mheight = 41, mwidth = 41; // need to be odd
if (args.length==3)
{
mheight=Integer.parseInt(args[0]);
mwidth=Integer.parseInt(args[1]);
blocksize=Integer.parseInt(args[2]);
}
mazedfs W = new mazedfs(blocksize,mheight,mwidth);
}
public void drawblock(int y, int x)
{
g.setColor(Color.black);
g.fillRect(x*bw,yoff+(y*bh),bw,bh);
g.setColor(Color.yellow);
// following line displays value of M[y][x] in the graphical maze:
if (showvalue)
g.drawString(""+M[y][x],(x*bw)+(bw/2-4),yoff+(y*bh)+(bh/2+6));
}
void drawdot(int y, int x)
{
g.setColor(Color.red);
g.fillOval(x*bw,yoff+(y*bh),bw,bh);
try{Thread.sleep(dtime);} catch(Exception e) {}
}
/////////////////////////////////////////////////////////////////////
/* function to generate random maze */
public void digout(int y, int x)
{
M[y][x] = 1; // digout maze at coordinate y,x
drawblock(y,x); // change graphical display to reflect space dug out
int dir = (int)(Math.random()*4);
for (int i=0;i<4;i++){
int [] DX = {0,0,2,-2};
int [] DY = {-2,2,0,0};
int newx = x + DX[dir];
int newy = y + DY[dir];
if(newx>=0 && newx<mw && newy>=0 && newy<mh && M[newy][newx]==0)
{
M[y+DY[dir]/2][x+DX[dir]/2] = 1;
drawblock(y+DY[dir]/2,x+DX[dir]/2);
digout(newy,newx);
}
dir = (dir + 1)%4;}
} // digout
public void solve() // This is the method i need help with.
{
int x=1, y=1;
drawdot(y,x);
while(y!=mh-1 || x!=mw-1 && M[y][x]!=0){
int min = 0x7fffffff;
int DX = 0;
int DY = 0;
if (y-1>0 && min>M[y-1][x] && M[y-1][x]!=0){
min = M[y-1][x];
DX = 0;
DY = -1;
}//ifNORTH
if (y+1>0 && min>M[y+1][x] && M[y+1][x]!=0){
min = M[y+1][x];
DY = 1;
DX = 0;
}//ifSOUTH
if (x-1>0 && min>M[y][x-1] && M[y][x-1]!=0){
min = M[y][x-1];
DX = -1;
DY = 0;
}//ifWEST
if (x+1>0 && min>M[y][x+1] && M[y][x+1]!=0){
min = M[y][x+1];
DX = 1;
DY = 0;
}//ifEAST
M[y][x]++;
drawblock(y,x);
x = x+DX;
y = y+DY;
drawdot(y,x);
}//while
// modify this function to move the dot to the end of the maze. That
// is, when the dot reaches y==mh-2, x==mw-2
} // solve
///////////////////////////////////////////////////////////////
/// For part three (save a copy of part 2 version first!), you
// need to implement the KeyListener interface.
public void play() // for part 3
{
// code to setup game
}
// for part 3 you may also define some other instance vars outside of
// the play function.
// for KeyListener interface
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) // change this one
{
int key = e.getKeyCode(); // code for key pressed
System.out.println("YOU JUST PRESSED KEY "+key);
}
} // mazedfs
////////////
// define additional classes (stack) you may need here.
The issue causing the second problem you are facing (dot moving to green box) lies in the while loop conditiony!=mh-1 || x!=mw-1 && M[y][x]!=0 . The condition evaluates to y!=mh-1 ||(x!=mw-1 && M[y][x]!=0) since && has higher precedence over the || and || just needs one of its operand to be true. In your case, y!=mh-1 is still ture at the end of maze. Hence the loop continues and the dot moves into green area. To fix the issue modify the condition as (y!=mh-1 || x!=mw-1) && M[y][x]!=0. Hope this helps.

Java GUI program to convert 2D array value into graphic [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am a beginner in Java & i have to make a java program that takes the input from a 2d array with dimensions 347*697 (array's value range from 2200 to 4200 ). I have to do such that for every 100 increase in range there is a set of specific color(for e.g 2200-2300 color(214,217,223) & so on). I have never done anything .. & this is the program i found little bit similar ... Can anyone give me idea how to convert it
I know its too much to ask for , but tomorrow i have to give a ppt. & when every option is closed i came here. Please guys, I need help badly
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class Map extends JPanel {
public static final Color CITY = new Color(214,217,223);
public static final Color DESERT = new Color(255,204,102);
public static final Color DIRT_ROAD = new Color(153,102,0);
public static final Color FOREST = new Color(0,102,0);
public static final Color HILLS = new Color(51,153,0);
public static final Color LAKE = new Color(0,153,153);
public static final Color MOUNTAINS = new Color(102,102,255);
public static final Color OCEAN = new Color(0,0,153);
public static final Color PAVED_ROAD = new Color(51,51,0);
public static final Color PLAINS = new Color(102,153,0);
public static final Color[] TERRAIN = {
CITY,
DESERT,
DIRT_ROAD,
FOREST,
HILLS,
LAKE,
MOUNTAINS,
OCEAN,
PAVED_ROAD,
PLAINS
};
public static final int NUM_ROWS = 215;
public static final int NUM_COLS = 300;
public static final int PREFERRED_GRID_SIZE_PIXELS = 10;
// In reality you will probably want a class here to represent a map tile,
// which will include things like dimensions, color, properties in the
// game world. Keeping simple just to illustrate.
private final Color[][] terrainGrid;
public Map(){
this.terrainGrid = new Color[NUM_ROWS][NUM_COLS];
Random r = new Random();
// Randomize the terrain
for (int i = 0; i < NUM_ROWS; i++) {
for (int j = 0; j < NUM_COLS; j++) {
int randomTerrainIndex = r.nextInt(TERRAIN.length);
Color randomColor = TERRAIN[randomTerrainIndex];
this.terrainGrid[i][j] = randomColor;
}
}
int preferredWidth = NUM_COLS * PREFERRED_GRID_SIZE_PIXELS;
int preferredHeight = NUM_ROWS * PREFERRED_GRID_SIZE_PIXELS;
setPreferredSize(new Dimension(preferredWidth, preferredHeight));
}
#Override
public void paintComponent(Graphics g) {
// Important to call super class method
super.paintComponent(g);
// Clear the board
g.clearRect(0, 0, getWidth(), getHeight());
// Draw the grid
int rectWidth = getWidth() / NUM_COLS;
int rectHeight = getHeight() / NUM_ROWS;
for (int i = 0; i < NUM_ROWS; i++) {
for (int j = 0; j < NUM_COLS; j++) {
// Upper left corner of this terrain rect
int x = i * rectWidth;
int y = j * rectHeight;
Color terrainColor = terrainGrid[i][j];
g.setColor(terrainColor);
g.fillRect(x, y, rectWidth, rectHeight);
}
}
}
public static void main(String[] args) {
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Game");
Map map = new Map();
frame.add(map);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
Create a byte[] with the rgb values for each pixel of the image you want. The byte[] length will be width * height * 3 (3 values for each pixel). Look at this for an example of how create a BufferedImage from the byte[].
Another alternative is to create a BufferedImage and set the rgb value for each pixel directly. In this case, you have to bit twiddle all 3 rgb values into a single int value.

Getting values of Grid's individual nodes (JAVA)

I want to create a program that can simulate the influence of a social structure of a matrix / grid. It's like an Erdos Renyi structure, but an nxn matrix where each node initially has a random value of +1 or -1. Each node has 4 neighbors (top, bottom, left, right) which also has values of +1 or -1. Thus, I can find the neighborhood of each node, which should be just a list / vector of the 4 values of those neighbors. The value of each node is then influenced by the neighbors' values, and the grid's values keep simulating and changing until an equilibrium is reached.
So far, I have a code which can create a grid with random -1 or +1 variables. Now, I am not sure how to get the values of each node (and its neighbors) inside the main method. I am a little confused as to how to go about this project so far, as in how to get the values.
In the main method, I cannot do like... int x = grid[0][1] etc. Sorry that I'm rusty in Java, but what topics can I look up in finding out the procedure to do this? I can't remember what it's called.
Also, is there a way that I can edit what each button (or node) on the grid says in the main method? Like, I can change it while it's looping, and I can also write what the values of its neighbors are? Thanks!
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.GridLayout;
public class Grid {
JFrame frame = new JFrame(); // create frame
static JButton[][] grid;
// constructor
public Grid (int w, int l) {
frame.setLayout(new GridLayout(w, l));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
// create grid
grid = new JButton[w][l];
for (int y = 0; y < l; y++) {
int value = 0;
for (int x = 0; x < w; x++) {
// probability p
double p = 0.5;
// randomly allocate opinion
double random = Math.random();
if (random <= p)
value = -1;
else if (random > p)
value = 1;
grid[x][y] = new JButton("" + value);
frame.add(grid[x][y]);
}
}
}
public static void main (String[] args) {
// DIMENSION
// int d = 2;
// LENGTH
int l = 2;
// WIDTH
int w = 2;
new Grid(l,w); // create new Grid with parameters
}
}
I changed your approach a little bit, so it is more object-oriented. I hope this example makes clear, what you have to do. To get an basic understanding, google keywords like "encapsulation" or "object-orientation". There are many tutorials out there.
public class Grid {
private JFrame frame = new JFrame();
private JButton[][] grid; // Has to be a field of the object. static would make it to an field of the class
public Grid (int w, int l) {
frame.setLayout(new GridLayout(w, l));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
createGrid (w, l);
}
private void createGrid (int w, int l) {
// Your above implementation
}
public void stepInSimulation () {
// Your algorithm, you want to implement
}
public JButton[][] getGrid () {
return grid;
}
public static void main (String[] args) {
Grid grid = new Grid(2,2);
grid.getGrid ()[0][1]; // Access a value
grid.stepInSimulation (); // Do a step, call it in while loop, to do multiple steps
}
}
I hope this helps.

Attempting to create progress bars

This is just an exercise in mechanics. I am attempting to create three custom panels that control their own progress bar. It’s part of a time management program I am writing for myself to learn more about Java. The larger program uses dates input by the user to create the framework for the min/max of the progress bar. Both this program and the larger one exhibit the same behavior with multiple bars racing the clock.
The issue I am having is that if I have just one bar everything seems to work just fine, but when I have more than one everything seems to go bust. So I wrote this little program to test some things out. It’s very simple, takes three custom panels, gives them a label and uses a timer event to change the label and the position of the progress bar. My question is If the math lines up (System output shows the calculation) and I’m counting events every second (1000 milliseconds) why is everything beating the count down.
Please forgive my lack of form with my code. I’m more concerned with the logic than the form.
(Most of the below is cut from my larger program, so if you see extraneous bits they really do have a home)
Thank you in advance.
import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
public class plaything extends JFrame implements ActionListener
{
myPanel[] mp = new myPanel[3];
JLabel[] jl = new JLabel[3];
short[] tim = new short[3];
short x = 0;
short t = 0; //used to stagger the clocks
short dateSaver; //holds temp dates
public plaything()
{
setSize(400, 350);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 1) );
for(short x = 0; x < 3; x++)
{
mp[x] = new myPanel();
//sets all three bars to different 'times'
dateSaver = (short)(10 + t) ;
tim[x] = dateSaver;
mp[x].setMax( dateSaver );
jl[x] = new JLabel("Expires: " + dateSaver);
this.add(mp[x]);
mp[x].add( jl[x] );
t += 15; // 15 seconds
}
Timer time = new Timer(1000, this);
time.start();
}
public void actionPerformed(ActionEvent e)
{
if ( x < 60 )
{
x++;
}
else
{
x = 1;
}
for(myPanel m : mp)
{
m.tock();
}
for(short x = 0; x < 3; x++ )
{
mp[x].tock();
jl[x].setText( "" + --tim[x] );
}
}
private class myPanel extends JPanel
{
//Fields
private boolean finished = false;
//(x,y) Coords
private short x = 15;
private short y = 50;
//Size and shape
private short width = 200;
private short height = 10;
private short arcSize = 10;
//Bar essentials
private double max; //highest range of bar
private double fill = width; //sets filled in portion
private double tick; //calculates movement per event
private Color urgent = Color.BLUE; // Changes the color depending on the Urgency
//Constructors
public myPanel()
{
this.setBackground( Color.WHITE );
repaint();
}
//Mutators ( tick manipulation )
public void setMax( double maxIn )
{
this.max = maxIn;
System.out.println("Max: " + this.max );
this.tick = (double)width / this.max;
System.out.println("tick: " + this.tick );
}
//Methods
//Tick Manipulation
public void tock()
{
//Ends when zero
if( fill < 1 )
{
fill = width;
finished = true;
tick = 0;
urgent = Color.BLUE;
repaint();
}
else
{
fill -= tick ;
System.out.println("fill is " + fill );
repaint();
}
}
//Paint method
public void paint( Graphics g)
{
super.paint(g);
Graphics2D g2 = (Graphics2D)g;
g2.setColor( urgent );
g2.draw(new RoundRectangle2D.Double(x,y + 40, width, height, arcSize, arcSize) );
g2.fill(new RoundRectangle2D.Double(x,y + 40, fill , height, arcSize, arcSize) );
}
}
public static void main(String[] args)
{
plaything pt = new plaything();
pt.setVisible(true);
}
}
My real only concern is where is my logic flawed concerning the progression of the bars and the labels. I hope to find how to make both reach zero together. (two days of research and work on just the bars alone)
Again thank you for your time.
You're calling tock() twice every iteration of your Timer:
for(myPanel m : mp)
{
m.tock(); // ONCE
}
for(short x = 0; x < 3; x++ )
{
mp[x].tock(); // TWICE
jl[x].setText( "" + --tim[x] );
}
You should remove one call, or the other.

Java Lines Confusion

I am having a problem with my java code. I'm trying to make it so the top left quadrant produces a set number of lines input by a user through JOption Pane which are in random colors and in random positions. The programs builds successfully but it does not produce the number of lines the user input, nor does it set a random color (This it at the very bottom of my code). Can someone please explain how to fix this problem? Thanks very much.
Edit: fixed the curve braces but still will not work.
Edit: Everything works now except the random colors
import javax.swing.*; //for JFrame
import java.awt.*; //for Graphics and Container
import java.util.Random;
import javax.swing.JOptionPane;
// other import statements here
public class RandomGraphics
{
// constants are used to draw the grid, and for you to put shapes in the grid
public static final int MIDX = 400;
public static final int MIDY = 300;
public static final int MAXX = 799;
public static final int MAXY = 599;
public static final int COLOR = (int) (Math.random() * 256);
// make another constant for the color value that will
// be used to generate a random color
public static void main( String[] args )throws InterruptedException
{
//*** This next section sets up the graphics window.
//*** You are not required to understand it
Container contentPane;
Graphics g;
JFrame win = new JFrame("Random Graphics");
win.setSize(825,650);
win.setLocation(0,0);
win.setVisible(true);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = win.getContentPane();
contentPane.setBackground(Color.white);
g = contentPane.getGraphics();
Thread.sleep(50);
//*** done setting up graphics window
// Draws Grid - DO NOT CHANGE
// After you use JOptionPane to get the number of lines, you can move this
// section of code to just after that, so the lines will not disappear
g.drawRect(0,0,MAXX+1,MAXY+1);
g.drawLine(0,MIDY,MAXX,MIDY); // horizontal line
g.drawLine(MIDX,0,MIDX,MAXY); // vertical line
// Create Random object
Random r = new Random();
// Top left quadrant:
// Use a JOptionPane to ask the user to enter the number of lines 1 to 100.
int count = 0;
do
{
String morelines = JOptionPane.showInputDialog("Enter a number of lines between 1 to 100");
count = Integer.parseInt(morelines);
}
while(count > 100 || count < 1);
for(int i = 1; i >= count; i++)
{
g.setColor(new Color (r.nextInt(COLOR), r.nextInt(COLOR), r.nextInt(COLOR)));
g.drawLine(r.nextInt(MIDX), r.nextInt(MIDY), r.nextInt(MIDX), r.nextInt(MIDY));
}
g = contentPane.getGraphics();
Graphics objects are not persistent, the programmer needs to draw the GUI to them when asked to do so. For tips, see the Performing Custom Painting Lesson of the tutorial.
Beside the 'always include curly braces around loops advice', note..
for(int i = 1; i >= count; i++)
Should be..
for(int i = 1; i <= count; i++)
But don't ignore the advice about custom painting. The app. will not render reliably until that is fixed.
for(int i = 1; i >= count; i++)
g.setColor(new Color (r.nextInt(COLOR), r.nextInt(COLOR), r.nextInt(COLOR)));
g.drawLine(r.nextInt(MIDX), r.nextInt(MIDY), r.nextInt(MIDX), r.nextInt(MIDY));
Looking at your indenting, it looks like you want g.setColor(...) and g.drawLine(...) to be inside your for loop. You need to enclose them in curly braces {}, otherwise only the statement immediately following your for loop will be inside the loop.

Categories