Number and loop issue - java

I am new to programming and am having difficulty with this problem. I am trying to build a wall based on the number entered in the JTextField but the number cannot exceed 20. I cannot get my error message to display nor can I get my brick wall to build. Could someone please help me figure out what I am doing wrong?
public class Wall extends JApplet implements ActionListener {
JTextField enter;
Boolean submit;
JLabel bricks;
JButton build;
JPanel top;
Image zombie;
int value;
public void init() {
setLayout(new BorderLayout());
top = new JPanel();
build = new JButton("AHHHHHH...ZOMBIES!"); //button for building wall
bricks = new JLabel("Enter between 1 & 20 rows to contruct:");
enter = new JTextField(2);
top.add(build); //add zombie button
top.add(bricks); //add intructions
top.add(enter); //add text field
add(top, BorderLayout.NORTH);
build.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == build) {
int value = Integer.parseInt(build.getText());
if (value > 0 && value < 21) {
submit = true;
repaint();
} else {
submit = false;
repaint();
}
}
}
public void paint(Graphics g) {
super.paint(g);
//add zombie image
Image zombie = getImage(getCodeBase(), "Zombie.jpg");
g.drawImage(zombie, 0, 45, this);
if (submit = false) //add error message
{
g.setColor(Color.WHITE);
g.setFont(new Font("TimesRoman", Font.BOLD, 40));
g.drawString("You must enter a number between 1 & 20!", 400, 100); //add message
}
int brick_width = 50;
int brick_height = 20;
int spacing = 1;
int x = 0;
while (x < 21) {
drawBrick(g, nextInt(brick_width + spacing), nextInt(brick_height + spacing));
x = x + getWidth() + 50;
x = x - 25 + getWidth() + 50;
x++;
}
}
public void drawBrick(Graphics g, int x, int y) {
g.setColor(new Color(150, 0, 0));
g.fillRect(0, 635, 50, 20);
}
}

Instead of painting on top-level containers such as JApplet directly, you have to use JPanel and paint on it. Just override paintComponent() method of JPanel(). Never forget to call super.paintComponent(g) in overridden method.
sample code:
top = new JPanel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
...
// your custom painting code goes here
}
};
Note:
submit == false and !submit are the correct way to check it but it still will result in NullPointerException because you have never initialized instance variable submit.
Use primitive boolean instead of Boolean to avoid such exception or initialize it properly.
Boolean submit = false;

Change your if statement to:
if (submit == false)
That'll get your error message to pop up

Should be if (submit == false) rather than if (submit = false).

Two issues:
1) Your submit variable is not initialized, you should initialize it to true/false.
If you dont want to initialize it, you can simple try with
if(submit!=null && !submit)
2)
Secondly, "=" is used for assigning a value where as "==" is used for comparing
Change
if (submit = false) //add error message
{
g.setColor(Color.WHITE);
g.setFont(new Font("TimesRoman", Font.BOLD, 40));
g.drawString("You must enter a number between 1 & 20!", 400, 100); //add message
}
to
if (submit == false) //add error message
{
g.setColor(Color.WHITE);
g.setFont(new Font("TimesRoman", Font.BOLD, 40));
g.drawString("You must enter a number between 1 & 20!", 400, 100); //add message
}

To solve your error display issue,
submit = false should be submit == false
= is for assignment
== is for comparison
Also, initialize your variable to avoid null pointer exception:
boolean submit = false;

Related

How to prevent my KeyEvent from repainting both objects?

I am working on a simple game which requires 1 player (the square) and some enemies that spawn randomly inside the play-area. I am running into an issue currently, because when I run my program, pressing any arrow key will repaint not only the player's new location, but it will also re-spawn all the enemies into the new locations.
I have gone through my code a few times and I am still stumped as to why this is happening. Any help would be greatly appreciated.
P.S. I am not a very experienced programmer, so some of this code may not be as efficient as possible and some things may be incorrect; feel free to point out any errors besides the issue at hand. Thanks!
Main Class
public class Eat {
public static void main(String[] args) {
// Creating the main frame
JFrame main = new JFrame("Eat 'Em All - Version 1.0.2");
main.setSize(497, 599);
main.setLocationRelativeTo(null);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setResizable(false);
// Colours and borders
Border areaBorder = new LineBorder(Color.LIGHT_GRAY, 3);
// Creating main JPanel
JPanel area = new JPanel();
area.setLayout(new BoxLayout(area, BoxLayout.PAGE_AXIS));
area.setBackground(Color.WHITE);
main.setContentPane(area);
// Creating the drawing/image/player
DrawPlayer player = new DrawPlayer();
player.setPreferredSize(new Dimension(497, 539));
player.setOpaque(false);
// Enemies
DrawEnemy enemy = new DrawEnemy();
enemy.setPreferredSize(new Dimension(497, 539));
enemy.setBackground(Color.WHITE);
// Creating the control panel for buttons, etc
JPanel control = new JPanel();
control.setPreferredSize(new Dimension(497, 60));
control.setLayout(new GridLayout(1, 2, 0, 0));
control.setBorder(areaBorder);
JLabel welcome = new JLabel(" Welcome to Eat 'Em All |--| Press 'Start'");
JButton start = new JButton("Start");
// Adding it all to the frame
main.add(enemy);
enemy.add(player);
control.add(welcome);
control.add(start);
area.add(control);
// Adding keylistener and making button false
player.addKeyListener(player);
player.setFocusable(true);
start.setFocusable(false);
enemy.setFocusable(false);
// Bring frame to front and visible
main.toFront();
main.setVisible(true);
System.out.println(player.getWidth() / 2);
System.out.println(player.getHeight() / 2);
}
}
Drawing Player Class
public class DrawPlayer extends JPanel implements KeyListener {
long xPosition = 0;
long yPosition = 0;
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Making loop to get points and move it
// Center of area is x: 245 y: 255
int xPoints[] = {235, 255, 255, 235, 235, 255};
int yPoints[] = {265, 265, 245, 245, 265, 245};
for (int i = 0; i < xPoints.length; i++) {
xPoints[i] += xPosition;
yPoints[i] += yPosition;
}
g.setColor(Color.BLUE);
g.drawPolygon(xPoints, yPoints, xPoints.length);
}
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_DOWN:
if (yPosition == 245) {
yPosition -= 5;
} else {
yPosition += 5;
}
break;
case KeyEvent.VK_UP:
if (yPosition == -245) {
yPosition += 5;
} else {
yPosition -= 5;
}
break;
case KeyEvent.VK_LEFT:
if (xPosition == -235) {
xPosition += 5;
} else {
xPosition -= 5;
}
break;
case KeyEvent.VK_RIGHT:
if (xPosition == 235) {
xPosition -= 5;
} else {
xPosition += 5;
}
break;
}
repaint();
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
Drawing Enemies Class
public class DrawEnemy extends JPanel {
public void paintComponent(Graphics f) {
super.paintComponent(f);
for (int i = 0; i < 10; i++ ){
f.setColor(Color.RED);
f.drawOval((int)(Math.random() * ((440 - 0) + 0) + 0), (int)(Math.random() * ((500 - 0) + 0) + 0), 50, 50);
}
}
}
Your have a problem here:
public void paintComponent(Graphics f) {
super.paintComponent(f);
for (int i = 0; i < 10; i++ ){
f.setColor(Color.RED);
f.drawOval((int)(Math.random() * ((440 - 0) + 0) + 0), (int)(Math.random() * ((500 - 0) + 0) + 0), 50, 50);
}
}
You've got program logic inside of a painting method, something you should never do, since you never have full control over when or even if a painting method will be called. The solution, get the randomization out of the paintComponent method and into its own separate method, one that you call if and only if you want to randomize the enemies, and not every time you repaint.
Other issues:
Separate your program logic from your GUI.
For instance you should have a non-GUI Enemy class, one that has fields for its own position, its size, its movement, perhaps a move() method, perhaps a collision(Player p) method.
You should have only one JPanel that does drawing and this should be its only job.
Again, you don't tie movement of anything to the painting method.
You would want a game loop of some sort, perhaps a Swing Timer. This will generate regularly spaced ticks that will prod Enemies and Players to move.
Get rid of KeyListener code and favor Key Bindings. The latter is much less kludgy when it comes to component focus. Do check the tutorial for this.

How to call this file in my main file?

package harjutamine;
public class algandmed{
Button[] whitebutton= new Button[2];
Button[] blackbutton= new Button[2];
public algandmed(){
whitebutton[0] = new Button(5, 1);
whitebutton[1] = new Button(5, 3);
blackbutton[0] = new Button(0, 0);
blackbutton[1] = new Button(0, 2);
}
}
This is basic information for my main file.
I have tried algandmed(); and algandmed a = new algandmed(); to call the code in my main file which don't work and I don't know why, I'd be thankful if someone explained why those wouldn't work and what would work.
Main
package harjutamine;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Checkerboard extends JPanel implements ActionListener {
public void drawFrame(Graphics g, int frameNumber, int width, int height) {
int row; // Row number, from 0 to 7
int col; // Column number, from 0 to 7
int x, y; // Top-left corner of square
for (row = 0; row < 8; row++) {
//Kabelaud
for (col = 0; col < 8; col++) {
x = col * 50;
y = row * 50;
if ((row % 2) == (col % 2)) {
g.setColor(Color.BLACK);
} else {
g.setColor(Color.WHITE);
}
g.fillRect(x, y, 50, 50);
}
}
//This is where I try to call the function, but it doesn't work
algandmed aa = new algandmed();
for (Button n: (whitebutton)) {
x = n.col * 50 + 4;
y = n.row * 50 + 4;
g.setColor(Color.RED);
g.drawOval(x, y, 40, 40);
g.fillOval(x, y, 40, 40);
}
for (Button n: (blackbutton)) {
x = n.col * 50 + 4;
y = n.row * 50 + 4;
g.setColor(Color.BLUE);
g.drawOval(x, y, 40, 40);
g.fillOval(x, y, 40, 40);
}
}
//------ Implementation details: DO NOT EXPECT TO UNDERSTAND THIS ------
public static void main(String[] args) {
JFrame window = new JFrame("Checkerboard");
Checkerboard drawingArea = new Checkerboard();
drawingArea.setBackground(Color.WHITE);
window.setContentPane(drawingArea);
drawingArea.setPreferredSize(new Dimension(390, 390));
window.pack();
window.setLocation(100, 50);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false); // The user can't change the size.
Timer frameTimer = new Timer(20, drawingArea);
window.setVisible(true);
//frameTimer.start(); // commented out so we don't get an animation
} // end main
private int frameNum;
public void actionPerformed(ActionEvent evt) {
frameNum++;
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawFrame(g, frameNum, getWidth(), getHeight());
}
}
Button
package harjutamine;
public class Button{
int row;
int col;
public Button(int r, int c){
row = r;
col = c;
}
}
I guess what you are trying to say is that your code does not compile. There is no declaration for a Variable whitebutton in your drawFrame method. Therefor the compiler won't compile your code. If you simply paste the code algandmed then you have a declaration of whitebutton. However this is probably not what you wanted. Think about which class should hold/own the Button Arrays. If you decide to put them in the alganmed class you need to provide a correct variable declaration.aa.whitebutton should work because you created an instance of alganmed named aa. Since you are in the same package and whitebutton is default visibility you can access it directly from your main method. Note however that this is not good practice. You should not access another classes internal data directly. Try to think of methods that encapsulate the data of alganmed instead.

Java Key Events and Timer control

Im almost finished with this car project im working on but cant seem to get the key events to work. I think it has to do with my action listener with my timer but im not sure. When I press the up arrow key the timer delay is supposed to decrease and vice versa for the down arrow key. I have the commands written but they are not registering input. If anyone could give me some pointers I'd appreciate it
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RaceCar extends JFrame{
public RaceCar(){
add(new CarPic());
}
public static void main(String[] args){
JFrame frame = new RaceCar();
frame.setTitle("Brady Kedge: Race Car");
frame.setSize(300, 150);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public class CarPic extends JPanel implements KeyListener
{
private int x = 0;
private int y = 150;
private int z = 300;
Timer mytimer = new Timer(50, new ActionListener());
public CarPic()
{
mytimer.start();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
y = getHeight();
z = getWidth();
g.setColor(Color.WHITE);
g.fillRect(0, 0, z, y);
Polygon polygon = new Polygon();
polygon.addPoint(x + 10, y - 20);
polygon.addPoint(x + 20, y - 30);
polygon.addPoint(x + 30, y - 30);
polygon.addPoint(x + 40, y - 20);
if(x < z - 40)
{
g.setColor(Color.BLACK);
g.fillOval(x + 10, y - 10, 10, 10);
g.fillOval(x + 30, y - 10, 10, 10);
g.setColor(Color.BLUE);
g.fillRect(x, y - 20, 50, 10);
g.setColor(Color.BLUE);
g.fillPolygon(polygon);
}
else
x = 0;
}
public void actionPerformed(ActionEvent e){
x+=10;
repaint();
}
#Override
public void keyTyped(KeyEvent k) {
//Fill
}
#Override
public void keyPressed(KeyEvent k) {
int delay = mytimer.getDelay();
if(k.getKeyCode() == KeyEvent.VK_UP)
mytimer.setDelay(delay > 10 ? delay - 10 : 0);
else if(k.getKeyCode() == KeyEvent.VK_DOWN)
mytimer.setDelay(delay < 5000 ? delay + 10 : 5000);
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
}
First of all, you never register a KeyListener with your component (implementing KeyListener isn't enough).
Second of all, KeyListener will only raise KeyEvents if the component it is registered to has focus and is focusable.
A better solution would be to use the key bindings API, which provides you with the means to configure the focus level at which a component will trigger key events.
Also, personally, instead of modifying the Timer delay, I would have use a speed modifier (of type double) which would be percentage of the speed you want. In this way 1 would normal speed, 0.5 half speed and 2 double speed, for example.

Advanced GUIs and Graphics

Good day, OK here's my problem: I have to create an applet by adding three different types
of GUI components so the user can select from the following:
Number of figures: 1, 2, 4, 8, 16, or various combinations of these
numbers
Type of figures: circle, oval, rectangle, or square
Color: red, blue, green, yellow, pink, black, cyan, or magenta
I've done that design but the problem is drawing the image the user selects
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Ovals extends JApplet implements ItemListener
{
private JCheckBox circleCB,ovalCB,rectangleCB,squareCB;
private Color currentColor = Color.black;
private JRadioButton redRB, greenRB, blueRB, yellowRB, pinkRB, cyanRB, magentaRB, blackRB;
private ButtonGroup ColorSelectBGroup;
private JComboBox numFig;
int Figure;
int num;
public String[] figNum = {"1", "2", "4", "8", "16", "32", "64", "128"};
public void init()
{
Container c = getContentPane();
c.setLayout(null);
circleCB = new JCheckBox("Circle");
ovalCB = new JCheckBox("Oval");
rectangleCB = new JCheckBox("Rectangle");
squareCB = new JCheckBox("Square");
redRB = new JRadioButton("Red");
greenRB = new JRadioButton("Green");
blueRB = new JRadioButton("Blue");
yellowRB = new JRadioButton("Yellow");
pinkRB = new JRadioButton("Pink");
cyanRB = new JRadioButton("Cyan");
magentaRB = new JRadioButton("Magenta");
blackRB = new JRadioButton("Black");
numFig = new JComboBox(figNum);
numFig.setMaximumRowCount(8);
circleCB.setSize(80, 30);
ovalCB.setSize(80, 30);
rectangleCB.setSize(80, 30);
squareCB.setSize(80, 30);
redRB.setSize(80, 30);
greenRB.setSize(80, 30);
blueRB.setSize(80, 30);
yellowRB.setSize(80, 30);
pinkRB.setSize(80, 30);
cyanRB.setSize(80, 30);
magentaRB.setSize(80, 30);
blackRB.setSize(80, 30);
numFig.setSize(80, 30);
circleCB.setLocation(100, 70);
ovalCB.setLocation(100, 110);
rectangleCB.setLocation(100, 150);
squareCB.setLocation(100, 190);
redRB.setLocation(300, 70);
greenRB.setLocation(300, 110);
blueRB.setLocation(300, 150);
yellowRB.setLocation(300, 190);
pinkRB.setLocation(300, 230);
cyanRB.setLocation(300, 270);
magentaRB.setLocation(300, 310);
blackRB.setLocation(300, 350);
numFig.setLocation(200, 70);
circleCB.addItemListener(this);
ovalCB.addItemListener(this);
rectangleCB.addItemListener(this);
squareCB.addItemListener((ItemListener) this);
redRB.addItemListener(this);
greenRB.addItemListener(this);
blueRB.addItemListener(this);
yellowRB.addItemListener(this);
pinkRB.addItemListener(this);
cyanRB.addItemListener(this);
magentaRB.addItemListener(this);
blackRB.addItemListener(this);
numFig.addItemListener(this);
c.add(circleCB);
c.add(ovalCB);
c.add(rectangleCB);
c.add(squareCB);
c.add(redRB);
c.add(greenRB);
c.add(blueRB);
c.add(yellowRB);
c.add(pinkRB);
c.add(cyanRB);
c.add(magentaRB);
c.add(blackRB);
c.add(numFig);
ColorSelectBGroup = new ButtonGroup();
ColorSelectBGroup.add(redRB);
ColorSelectBGroup.add(greenRB);
ColorSelectBGroup.add(blueRB);
ColorSelectBGroup.add(yellowRB);
ColorSelectBGroup.add(pinkRB);
ColorSelectBGroup.add(cyanRB);
ColorSelectBGroup.add(magentaRB);
ColorSelectBGroup.add(blackRB);
}
public void paint (Graphics g)
{
super.paint(g);
g.setColor(Color.orange);
g.drawLine(183, 50, 183, 350);
g.drawLine(291, 50, 291, 350);
}
public void itemStateChanged(ItemEvent e)
{
for ( int i = 0; i < 10; i++ )
{
switch( Figure )
{
case e.getSource() == circleCB:
(e.getStateChange() == ItemEvent.SELECTED)
e.drawLine( 10, 10, 250, 10 + i * 10 );
break;
case e.getSource() == rectangleCB:
(e.getStateChange() == ItemEvent.SELECTED)
e.drawRect( 10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10 );
break;
case e.getSource() == ovalCB:
(e.getStateChange() == ItemEvent.SELECTED)
e.drawOval( 10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10 );
break;
case e.getSource() == squareCB:
(e.getStateChange() == ItemEvent.SELECTED)
e.drawRect( 10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10 );
break;
default:
}
if (e.getSource() == redRB)
currentColor = Color.red;
else if (e.getSource() == greenRB)
currentColor = Color.green;
else if (e.getSource() == blueRB)
currentColor = Color.blue;
else if (e.getSource() == yellowRB)
currentColor = Color.yellow;
else if (e.getSource() == pinkRB)
currentColor = Color.pink;
else if (e.getSource() == cyanRB)
currentColor = Color.cyan;
else if (e.getSource() == magentaRB)
currentColor = Color.magenta;
else if (e.getSource() == blackRB)
currentColor = Color.black;
repaint();
}
}
}
whats my next step i have i have to adjust my itemStateChanged and paint method but im not sure how to go about it please help
Suggestions:
Have a class that extends JPanel and do all your drawing in its paintComponent override method.
Don't forget to call the super method in your override, usually first thing.
Then load this JPanel into your JApplet's contentPane in the BorderLayout.CENTER position.
In the paintComponent method have if blocks that check the state of variables in your class, such as a Color variable, perhaps a number variable, perhaps booleans for the shapes, and based on the state of these variables draw the appropriate shape.
In your listener, change the state of the above variables and then call repaint() to repaint the JPanel and display the new shapes.
Check out Custom Painting Approaches. I would suggest you would want to use the DrawOnComponent example as it allows you to add Objects that you want to paint to an ArrayList. The current code uses a "ColoredRectangle" class so you would need to change that to use a "ColoredShape" class so you can paint objects of different Shapes.
Then you might want to check out Playing With Shapes which will show you how to paint using the Shape class instead of using the specific Graphics draw methods. This makes your code far more flexible.
Put the two suggestions together and you have a possible solution.

Transferring JFrame to JPanel

I created a simple "elevator" program (it's still in the beginning stages) that goes up 1 floor when I click UP and vice versa.
I messed up pretty badly when I drew all my components into JFrame, and as expected, it flickers every time I click the button (repaints). I know the solution to be draw in the JPanel and put the said panel in the JFrame, but I have a problem translating my JFrame components into JPanel. I've tried extending JPanel, creating a JFrame object and then overriding the paintComponent() method and doing my drawing there, but when I compile it does not draw it at all. It only creates the frame.
Can anyone help me or give me tips on how to proceed "transferring" my programming from JFrame based to JPanel based? Thank you in advance!
My code is below:
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.Timer;
import java.math.*;
public class MyCanvas extends JFrame {
private int up = 0;
private int down = 0;
private int movefloorup = 0;
private int buildingType;//type of building (1 = Residential, 2 = Commercial)
private int totnumoffloors; //for the total number of floors
private int numofelevators; //for the number of elevators to be generated
private int floorlimit = 0; //to determine up until where the elevator will be moving
private int currenttime; //determine the time of the day the elevator is operating (1 = Morning, 2 = Lunch, 3 = Afternooon)
//For elevator resetting to bottom
private int rectX = 190;
private int switchmarker = 0;
//Lines and stuff
private int horizborder = 0;
private int bordercount = 0;
private class UpAction implements ActionListener //move the elevator up
{
public void actionPerformed(ActionEvent e)
{
if(movefloorup<780){
repaint();
up++;
movefloorup = movefloorup + 130;
//repaint();
}
else
{
switchmarker = 1;
movefloorup = 0;
repaint();
}
}
}
private class DownAction implements ActionListener //move the elevator down
{
public void actionPerformed(ActionEvent e)
{
if(movefloorup>0){
repaint();
down++;
movefloorup = movefloorup - 130;
//repaint();
}
else
{
switchmarker = 0;
movefloorup = 780;
repaint();
}
}
}
public MyCanvas(int buildingType, int totnumoffloors, int numofelevators, int currenttime){
this.buildingType = buildingType;
this.totnumoffloors = totnumoffloors;
this.numofelevators = numofelevators;
this.currenttime = currenttime;
String title;
if(this.buildingType == 1)
{
title = "Residential Building";
}
else
{
title = "Commercial Building";
}
setLayout(null);
horizborder = 500*((int)Math.ceil((double)totnumoffloors/7)); //calculating how wide the window should be
bordercount = ((int)Math.ceil((double)totnumoffloors/7)); //counts how many borders there will be
//NOTES
//A floor is 130 units in the Y-Direction
//Drawing the bulding layout
if(totnumoffloors>7)
{
setSize(horizborder, 1000);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(title);
setLayout(new BorderLayout());
getContentPane().setBackground(Color.WHITE);
}
else{
setSize(500, 1000); //suitable for 7 floors
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(title);
setLayout(new BorderLayout());
getContentPane().setBackground(Color.WHITE);
}
JButton upButton = new JButton("UP");
upButton.addActionListener(new UpAction());
add(upButton, BorderLayout.NORTH);
JButton downButton = new JButton("DOWN");
//downButton.setBounds(0, 0, 220, 30);
//downButton.setLocation(100, 100);
downButton.addActionListener(new DownAction());
add(downButton, BorderLayout.SOUTH);
}
public void paint(Graphics graphics){ //this is where you draw shit
super.paint(graphics);
//Floors
graphics.setColor(Color.RED);
int numoffloorsY = 830;
int numoffloorsX = 830;
int floorbeginning = 0;
int floorcounter = 1;
int floorflag = 0;
int rightedge = 500;
if(this.totnumoffloors>7) //drawing the floors
{
//Default number of floors -> 7
for(int i = 0;i<totnumoffloors;i++)
{
graphics.setColor(Color.RED);
graphics.drawLine(floorbeginning,numoffloorsX,rightedge,numoffloorsY); //FLOORS
graphics.setColor(Color.DARK_GRAY);
graphics.setFont(new Font("TimesRoman", Font.PLAIN, 15));
graphics.drawString(" "+floorcounter, floorbeginning+10, numoffloorsY+20); //SAVE THIS FOR DRAWING FLOORS
numoffloorsY = numoffloorsY - 130;
numoffloorsX = numoffloorsX - 130;
floorcounter++;
floorflag++;
if(floorflag==7)
{
floorbeginning = floorbeginning + 500;
rightedge = rightedge+500;
numoffloorsY = 830;
numoffloorsX = 830;
floorflag = 0;
}
}
//Every other floor past 7 will be added here.
/*for(int i = 0;i<totnumoffloors-7;i++)
{
//System.out.println("LOLOOLO");
graphics.setColor(Color.RED);
graphics.drawLine(floorbeginning,numoffloorsX,horizborder,numoffloorsY);
graphics.setColor(Color.DARK_GRAY);
graphics.setFont(new Font("TimesRoman", Font.PLAIN, 15));
graphics.drawString(" "+floorcounter, floorbeginning, numoffloorsY+20);
//graphics.setColor(Color.DARK_GRAY);
//graphics.drawLine(500,0,500,1000);
floorcounter++;
numoffloorsY = numoffloorsY - 130;
numoffloorsX = numoffloorsX - 130;
}*/
//DIVIDING LINE -> to determine the first 7 floors from the ones higher up.
for(int i=0;i<bordercount;i++)
{
graphics.setColor(Color.DARK_GRAY);
graphics.drawLine(500*i,0,500*i,1000);
}
}
else{
for(int i = 0;i<this.totnumoffloors;i++)
{
graphics.setColor(Color.RED);
graphics.drawLine(0,numoffloorsX,500,numoffloorsY);
graphics.setColor(Color.DARK_GRAY);
graphics.setFont(new Font("TimesRoman", Font.PLAIN, 15));
graphics.drawString(" "+floorcounter, floorbeginning+10, numoffloorsY+20); //SAVE THIS FOR DRAWING FLOOR
numoffloorsY = numoffloorsY - 130;
numoffloorsX = numoffloorsX - 130;
floorcounter++;
}
}
//Drawing the elevators
if(up>0 && movefloorup<1000){
graphics.setColor(Color.GRAY);
if(switchmarker==1)
{
System.out.println("ELSA");
rectX = 690;
//rectX = rectX + 190;
}
else
{
rectX = 190;
}
System.out.println(rectX);
graphics.fillRect(rectX, 850-movefloorup, 100, 100); //this needs to match the stats of the rectangle to fill it properly
graphics.drawRect(rectX, 850-movefloorup, 100, 100);
//Line for the door
graphics.setColor(Color.BLACK);
graphics.drawLine(rectX+50, 850-movefloorup, rectX+50, 950-movefloorup); //match the y-coordinate for the rectangle, add 100 for the y-coordinate of the other end
System.out.println(movefloorup);
System.out.println(switchmarker);
//drawLine(x1, y1, x2, y2); --From (x1,y1) to (x2,y2)
}
else if(down>0 && movefloorup>0)
{
graphics.setColor(Color.GRAY);
if(switchmarker==1) //This determines when the elevator should move to the next column of higher floors.
{
System.out.println("ELSA");
rectX = 500;
}
System.out.println(rectX);
graphics.fillRect(rectX, 850-movefloorup, 100, 100); //this needs to match the stats of the rectangle to fill it properly
//graphics.drawRect(190, 850 + movefloorup, 100, 100); //FIRST FLOOR
graphics.drawRect(rectX, 850-movefloorup, 100, 100); //SECOND FLOOR (135 units difference in Y-axis between floors)
//x-coordinate, y-coordinate, width, height
//Line for the door
graphics.setColor(Color.BLACK);
graphics.drawLine(rectX+50, 850-movefloorup, rectX+50, 950-movefloorup); //match the y-coordinate for the rectangle, add 100 for the y-coordinate of the other end
System.out.println(movefloorup);
System.out.println(switchmarker);
}
else
{
graphics.setColor(Color.GRAY);
graphics.fillRect(190, 850, 100, 100); //this needs to match the stats of the rectangle to fill it properly
graphics.drawRect(190, 850, 100, 100); //FIRST FLOOR
graphics.drawRect(190, 850, 100, 100); //SECOND FLOOR (135 units difference in Y-axis between floors)
//x-coordinate, y-coordinate, width, height
//Line for the door
graphics.setColor(Color.BLACK);
graphics.drawLine(240, 850, 240, 950); //match the y-coordinate for the rectangle, add 100 for the y-coordinate of the other end
//System.out.println("In else!");
}
}
}
The main class just gets input from the user, such as the number of floors, time of day, etc.
This is going to be a little messy.
Start by creating a custom component that extends from JPanel (I'll call it ElevatorPane).
Take the contents of the current paint method and place them within this components paintComponent method. This will involve moving the instance variables that the paintComponent method will need including, totnumoffloors, bordercount, up, down, movefloorup, switchmarker, rectX
This is where it gets a little messy...
You need to take the contents of your ActionListeners and translate these into methods within the ElevatorPane, this way you expose the functionality without exposing the details...
Create a constructor within ElevatorPane that takes the number of floors.
Override the getPrefferedSize method of ElevatorPane and return the size that the component needs to be to satisfy your needs...
Create an instance field of ElevatorPane in MyCanvas, instantiate it and add it to the frame.
Clean, build, run...

Categories

Resources