I am working on a poker game in Java.
I would like to know how to make the diamond and heart symbol red instead of white filled, since I cannot find it in the unicode list.
Any help is appreciated.
EDIT: I would like to know how to paint the symbols to red.
This is my code so far:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class PokerHand extends Frame implements ActionListener {
Button b = new Button("Click for new hand");
boolean dealt[] = new boolean[52];
String[] playercard = new String[10];
String[] playersuit = new String[10];
Random r = new Random();
int drawn;
public static void main(String args[]) {
PokerHand ph = new PokerHand();
ph.doIt();
}
public void doIt() {
int ct;
for (ct = 0; ct <= 9; ++ct) { // first loop that you learned tonight
playercard[ct] = " ";
playersuit[ct] = " ";
} // ends for loop
b.addActionListener(this);
this.setLayout(new FlowLayout());
this.add(b);
this.setSize(500, 500);
this.setVisible(true);
}// ends doIt method
public void paint(Graphics g) {
g.setFont(new Font(null, 1, 30));
g.drawString("Me", 400, 100);
g.drawString(playercard[0], 30, 100);
g.drawString(playersuit[0], 60, 100);
g.drawString(playercard[1], 90, 100);
g.drawString(playersuit[1], 120, 100);
g.drawString(playercard[2], 150, 100);
g.drawString(playersuit[2], 180, 100);
g.drawString(playercard[3], 210, 100);
g.drawString(playersuit[3], 240, 100);
g.drawString(playercard[4], 270, 100);
g.drawString(playersuit[4], 300, 100);
g.drawString("You", 400, 200);
g.drawString(playercard[5], 30, 200);
g.drawString(playersuit[5], 60, 200);
g.drawString(playercard[6], 90, 200);
g.drawString(playersuit[6], 120, 200);
g.drawString(playercard[7], 150, 200);
g.drawString(playersuit[7], 180, 200);
g.drawString(playercard[8], 210, 200);
g.drawString(playersuit[8], 240, 200);
g.drawString(playercard[9], 270, 200);
g.drawString(playersuit[9], 300, 200);
}
public void actionPerformed(ActionEvent ae) {
int ct;
ct = 0;
int card;
int suit;
// we draw 10 cards here
while (ct < 10) { // a while loop in practice
drawn = r.nextInt(52);
if (dealt[drawn] != true) { // if in practice
card = drawn % 13 + 1;
suit = drawn / 13;
dealt[drawn] = true;
playercard[ct] = String.valueOf(card);
if (card == 1) {
playercard[ct] = "A";
}
if (card == 11) {
playercard[ct] = "J";
}
if (card == 12) {
playercard[ct] = "Q";
}
if (card == 13) {
playercard[ct] = "K";
}
if (suit == 0) {
playersuit[ct] = "\u2660";
}
if (suit == 1) {
playersuit[ct] = "\u2661"; //change to red heart
}
if (suit == 2) {
playersuit[ct] = "\u2662"; //change to red diamond
}
if (suit == 3) {
playersuit[ct] = "\u2663";
}
ct = ct + 1;
} // ends if
}// ends while
repaint();
for (int x = 0; x <= 51; ++x)
dealt[x] = false;
}// ends method
}// ends the class
If your Unicode font has the hearts, clubs, diamonds and spades symbols, then all you need to do to draw them in the color of your choice is the same as drawing any other character in the color of your choice: simply use setColor.
Now you should start from the "filled" version of spades, hearts, diamonds and clubs, they are:
- spade: \u2660
- heart: \u2665 (use 2665 instead of 2661)
- diamonds: \u2666 (use 2666 instead of 2662)
- clubs: \u2663b
Then you simply do:
g.setColor(Color.RED);
g.drawString("\u2665");
And then you change the color, say, back to black to draw text and back to red/black for suits (or red, black, blue and green if you want to use a "four-color deck").
This is (FINALLY) working for me! Ultimately the unicode doesn't change for the suits themselves, it's the \uFE0F that makes it "pop" and give it the color.
public enum Suit {
SPADES("\u2660\uFE0F"), HEARTS("\u2665\uFE0F"), DIAMONDS("\u2666\uFE0F"), CLUBS("\u2663\uFE0F");
private final String icon;
Suit(String icon) {
this.icon = icon;
}
public String getIcon() {
return icon;
}
}
Related
Nothing appears to be wrong with this from what I have seen
Code for Driver:
import javax.swing.JFrame;
import java.util.Scanner;
import java.util.Random;
public class rpsDriver{
public static void main(String[] args){
//jpanel stuff
JFrame frame = new JFrame("Rock Paper Scissors Game");
frame.setSize(1280,720);
frame.setLocation(250, 50);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new rpsPanel());
frame.setVisible(true);
}//end main
}//end class
The problem I have is that when I run the code and me or the computer gets to 3 wins the end screen that says you win/lose appears but the rock, paper, scissors button on the left is still there (and I would like for it to disappear). Also, I would like to add buttons below the thing that says you win/lose that will let you restart the game (making userScore, tieScore, and compScore = 0), and a button that ends the game (closes the panel and ends the run). I'd appreciate any help.
Code for the JPanel (the one I have problem with):
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon.*;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class rpsPanel extends JPanel{
Random rand = new Random();
//variables used in code
String compChoice = "";
int userNum; //number that corresponds to a choice
int compNum; //number that corresponds to a choice
int num;
int score; //score to decide who wins
String result = "";
String userChoice = "";
//win and tie count
int userScore = 0;
int compScore = 0;
int tieScore = 0;
//boolean variables for each choice
static JFrame frame;
boolean rock = false;
boolean paper = false;
boolean scissors = false;
public void paintComponent(Graphics g){
setLayout(null);
//background
// setLayout(new BoxLayout());
ImageIcon wooden = new ImageIcon("woodenBG.jpg");
g.drawImage(wooden.getImage(), 0, 0, 1280, 720, null);
g.setFont(new Font("Serif", Font.BOLD, 30));
g.setColor(Color.BLACK);
g.drawString("VS" , 630, 385);
//images for rock,paper, scissors
ImageIcon rockChoice = new ImageIcon("rock.png");
ImageIcon paperChoice = new ImageIcon("paper.jpg");
ImageIcon scissorsChoice = new ImageIcon("scissors.jpg");
/*displays the choice the user made*/
if (rock){
g.drawImage(rockChoice.getImage(), 350, 300, 200, 200, null);
}
else if (paper){
g.drawImage(paperChoice.getImage(), 350, 300, 200, 200, null);
}
else if (scissors){
g.drawImage(scissorsChoice.getImage(), 350, 300, 200, 200, null);
}
/**********************************/
/* computer makes choice after user */
if(rock || paper || scissors){
num = rand.nextInt(9);
if(num == 1 || num == 4 || num == 7){ //rock choice
compChoice = "rock";
compNum = 1;
g.drawImage(rockChoice.getImage(), 800, 300, 200, 200, null);
}
else if (num == 2 || num == 5 || num == 8){//paper choice
compChoice = "paper";
compNum = 2;
g.drawImage(paperChoice.getImage(), 800, 300, 200, 200, null);
}
else if(num == 3 || num == 6 || num == 0){//scissors choice
compChoice = "scissors";
compNum = 3;
g.drawImage(scissorsChoice.getImage(), 800, 300, 200, 200, null);
}
}
/**********************************/
/*the logic part to decide the winner*/
score = userNum - compNum;
if(score == -2 || score == 1){
result = "win";
userScore++;
}
if(score == 2 || score == -1){
result = "loss";
compScore++;
}
if ((score == 0) && (rock || paper || scissors)){
result = "tie";
tieScore++;
}
/***************************************/
//Displays the outcome
g.setFont(new Font("Serif", Font.BOLD, 40));
g.setColor(Color.BLACK);
g.drawString("The outcome: " + result, 425, 100);
//This shows the score of you and the computer
g.setFont(new Font("Serif", Font.BOLD, 30));
g.setColor(Color.BLACK);
g.drawString("Your score is " + userScore, 25, 50);
g.setFont(new Font("Serif", Font.BOLD, 30));
g.setColor(Color.BLACK);
g.drawString("The computer's score is " + compScore, 925, 50);
g.setFont(new Font("Serif", Font.BOLD, 30));
g.setColor(Color.BLACK);
g.drawString("The amount of ties that occured are " + tieScore, 400, 50);
//user wins the game after user wins 3 rounds
if(userScore >= 3){
g.setColor(new Color(0, 0, 0, 150));
g.fillRect(0,0,1280,720);
g.setFont(new Font("Serif", Font.BOLD, 75));
g.setColor(new Color(57, 255, 20));
g.drawString("You WIN!", 300, 330);
}
//computer wins the game after computer wins 3 rounds
if(compScore >= 3){
g.setColor(new Color(0, 0, 0, 150));
g.fillRect(0,0,1280,720);
g.setFont(new Font("Serif", Font.BOLD, 75));
g.setColor(Color.RED);
g.drawString("You LOSE! Try again", 400, 330);
}
}//ends the paintcomponent class
public rpsPanel(){
setLayout(null);
//images for rock, paper, scissors
Icon rPic = new ImageIcon(new ImageIcon("rock.png").getImage().getScaledInstance(70, 70, Image.SCALE_DEFAULT));
Icon pPic = new ImageIcon(new ImageIcon("paper.jpg").getImage().getScaledInstance(70, 70, Image.SCALE_DEFAULT));
Icon sPic = new ImageIcon(new ImageIcon("scissors.jpg").getImage().getScaledInstance(70, 70, Image.SCALE_DEFAULT));
/* buttons for rock paper scissors */
JButton rockBTN = new JButton(rPic); //rock button
rockBTN.addActionListener(new rockListener());
rockBTN.setBounds(20, 200, 70, 70);
add(rockBTN);
JButton paperBTN = new JButton(pPic); //paper button
paperBTN.addActionListener(new paperListener());
paperBTN.setBounds(20, 300, 70, 70);
add(paperBTN);
JButton scissorsBTN = new JButton(sPic); //scissors button
scissorsBTN.addActionListener(new scissorsListener());
scissorsBTN.setBounds(20, 400, 70, 70);
add(scissorsBTN);
/*************************************/
/* Creates the buttons to restart or end the game when one team has 3 wins */
JButton restartBTN = new JButton("RESTART");
restartBTN.addActionListener(new restartListener());
JButton endGameBTN = new JButton("END");
endGameBTN.addActionListener(new endGameListener());
endGameBTN.setBounds(300,500,50,50);
/*****************************************************/
if(userScore < 3 || compScore < 3){
rockBTN.setVisible(true);
paperBTN.setVisible(true);
scissorsBTN.setVisible(true);
restartBTN.setVisible(false);
endGameBTN.setVisible(false);
}
else if (userScore >= 3 || compScore >= 3){
rockBTN.setVisible(false);
paperBTN.setVisible(false);
scissorsBTN.setVisible(false);
restartBTN.setVisible(true);
endGameBTN.setVisible(true);
}
}
/* listeners for each button */
private class rockListener implements ActionListener{ //rock
public void actionPerformed(ActionEvent e){
//repaints game with the rock choice
rock = true;
repaint();
revalidate();
paper = false;
scissors = false;
userNum = 1;
}
}
private class paperListener implements ActionListener{ //paper
public void actionPerformed(ActionEvent e){
//repaints game with the paper choice
paper = true;
repaint();
revalidate();
rock = false;
scissors = false;
userNum = 2;
}
}
private class scissorsListener implements ActionListener{//scissors
public void actionPerformed(ActionEvent e){
//repaints game with the scissors choice
scissors = true;
repaint();
revalidate();
paper = false;
rock = false;
userNum = 3;
}
}
private class restartListener implements ActionListener{//restartBTN
public void actionPerformed(ActionEvent e){
//if button is clicked it will restart game with score at 0
}
}
private class endGameListener implements ActionListener{//restartBTN
public void actionPerformed(ActionEvent e){
//if button is clicked it will end the game, remove panel, and end the run
}
}
/**********************************************/
}//ends rpsPanel
I'm having problems with my java applet. I've made a Rock paper scissors game and i have 2 problems which I can't solve:
1. how to load the applet without the rock image on the left (players choice)
2. the score for player and computer does not reduce by 1 for every lost game
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class RockScissorsPaper extends Applet implements ActionListener
{
private Button rockButton;
private Button scissorsButton;
private Button paperButton;
private String buttonPressed = "";
private int computerValue = -1;
private int myValue;
private int playerScore = 10;
private int computerScore = 10;
private int drawScore = 0;
private Image imgRock;
private Image imgScissors;
private Image imgPaper;
public void init()
{
rockButton = new Button("Rock");
scissorsButton = new Button("Scissors");
paperButton = new Button("Paper");
add(rockButton);
add(scissorsButton);
add(paperButton);
rockButton.addActionListener(this);
scissorsButton.addActionListener(this);
paperButton.addActionListener(this);
imgRock = getImage(getCodeBase(), "rock.jpg");
imgScissors = getImage(getCodeBase(), "scissors.jpg");
imgPaper = getImage(getCodeBase(), "paper.jpg");
}
public void actionPerformed(ActionEvent event)
{
buttonPressed = ((Button)event.getSource()).getLabel();
computerValue = randomNumber012();
translator(buttonPressed);
repaint();
}
public void paint(Graphics g)
{
super.paint(g);
rockButton.setLocation(20,260);
rockButton.setSize(70,35);
paperButton.setLocation(210, 260);
paperButton.setSize(70, 35);
scissorsButton.setLocation(380, 260);
scissorsButton.setSize(90, 35);
choice(g);
g.drawString("Player's Wins: " + playerScore, 10, 20);
g.drawString("Computer's Wins: " + computerScore, 180, 20);
g.drawString("Draws: " + drawScore, 400, 20);
g.drawString("Your Choice: " + buttonPressed, 20, 60);
g.drawString("Computer's Pick: ", 350, 60);
winner(g, computerValue, myValue);
}
int randomNumber012()
{
return (int)(Math.random()*3);
}
public void translator(String s)
{
if(s.equals("Rock"))
{
myValue = 0;
}
else if(s.equals("Scissors"))
{
myValue = 1;
}
else if(s.equals("Paper"))
{
myValue = 2;
}
}
public void choice(Graphics g)
{
if(myValue == 0)
{
g.drawImage(imgRock, 20, 100, 100, 60, this);
}
else if(myValue == 1)
{
g.drawImage(imgScissors, 20, 100, 100, 60, this);
}
else if(myValue == 2)
{
g.drawImage(imgPaper, 20, 100, 100, 60, this);
}
if(computerValue == 0)
{
g.drawString("Computer's Pick: Rock", 350, 60);
g.drawImage(imgRock, 350, 100, 100, 60, this);
}
else if(computerValue == 1)
{
g.drawString("Computer's Pick: Scissors", 350, 60);
g.drawImage(imgScissors, 350, 100, 100, 60, this);
}
else if(computerValue == 2)
{
g.drawString("Computer's Pick: Paper", 350, 60);
g.drawImage(imgPaper, 350, 100, 100, 60, this);
}
}
public void winner(Graphics g, int cv, int mv)
{
if(cv == -1)
{
g.drawString("", 200, 100);
}
else if(cv == mv)
{
g.drawString("Draw", 200, 250);
drawScore = drawScore + 1;
}
else if(cv == 0 && mv == 1 || cv == 2 && mv == 0 || cv == 1 && mv == 2)
{
g.drawString("Computer Wins", 200, 250);
playerScore = playerScore - 1;
}
else
{
g.drawString("You Win!", 200, 250);
computerScore = computerScore - 1;
}
if (playerScore == 0)
{
System.out.println("You lost!");
playerScore = 10;
computerScore = 10;
drawScore = 0;
}
else if(computerScore == 0)
{
System.out.println("You won!");
playerScore = 10;
computerScore = 10;
drawScore = 0;
}
}
}
how to load the applet without the rock image on the left (players choice)
You need to have a fourth case for your myValue variable, when the player has not made a choice yet. Right now you only have three potential values, and the default is 0, which is why you see a rock image before you make a choice.
the score for player and computer does not reduce by 1 for every lost game
You're using ints where you should be using enums and booleans, which is making your code harder to understand. I'd highly recommend refactoring your code to use enums and booleans instead of ints.
Also, you're always calling every method from the paint() method. Don't do that. Instead, only call the functions that check for a winner when the player actually makes a choice, presumably from a button click.
Finally, you're also calling setLocation() inside your paint() method, which is a bad idea. You should only call setLocation() once, or better yet, use a layout manager.
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.
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...
I'm having trouble getting the graphics to show up with my hangman program.
This is the code for my engine class:
public static void main(String[] args)
{
//hangman viewer stuff
//////////////////////////////////////////////////////////////
JFrame frame = new JFrame();
frame.setSize(200,375); //invoked the method setSize on the implicit parameter frame
frame.setTitle("Hangman");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
HangmanComponent g = new HangmanComponent();
frame.add(g);
frame.setVisible(true);
///////////////////////////////////////////////////////////////
String wordd = JOptionPane.showInputDialog("Type in a word.");
int length = wordd.length();
String blank = "_ ";
String word2 = new String("");
int guesscount = 10;
ArrayList<String>answers=new ArrayList<String>(); //creates reference to empty structure that will contain references
char blanks[]=new char[wordd.length()]; //creates an array with the same number of terms as the length of the word
for (int i=0; i<length; i++)//fills the array with blanks corresponding to the length of the word
{
blanks[i] = '_';
}
HangmanComponent y = new HangmanComponent();
while (true)
{
String letter = JOptionPane.showInputDialog("Guess a letter! You have "+guesscount+" guesses."+"\n"+answers+"\n"+Arrays.toString(blanks).replace(",", " ").replace("[","").replace("]","")); //Prints a space
char letterchar = letter.charAt(0); //converts string letter to char letterchar
int idx = 0;
boolean found = false;
answers.add(letter); //adds the string to the arraylist answers
while (idx >= 0 && idx < length) //idx is greater than or equal to 0 but less than the length of the word
{
//System.out.println("idx = " + idx);
idx = wordd.indexOf(letter, idx); //idx is the index of "letter" in "wordd" and finds all instances of the letter
//System.out.println("idx = " + idx + ", guesscount = " + guesscount);
if (idx != -1) //if idx is not -1 (the letter exists in the word)
{
found = true;
blanks[idx] = letterchar; //sets the term in the array equal to the letter
idx += 1; //idx=idx+1
}
else
{
guesscount=guesscount-1;
y.nextStage();
y.printStage();
frame.add(y);
frame.setVisible(true);
break;
}
}
if (found)
{
JOptionPane.showMessageDialog(null, Arrays.toString(blanks).replace(",", " ").replace("[","").replace("]","")+"\n"+"You found a letter!"+"\n"+answers);
}
else
{
JOptionPane.showMessageDialog(null, Arrays.toString(blanks).replace(",", " ").replace("[","").replace("]","")+"\n"+"That letter is not in the word! Guess again!"+"\n"+answers);
if (guesscount == 0)
{
JOptionPane.showMessageDialog(null, "Sorry, you're all out of guesses. The answer was '"+wordd+".' Thanks for playing!");
break;
}
}
char [] lettersArray = wordd.toCharArray(); //converts word to array of chars
if (Arrays.equals(blanks, lettersArray))//compares array of blanks to array of letters
{
JOptionPane.showMessageDialog(null, "You guessed the word! Thanks for playing!");
break;
}
}
}
and this is the code for my HangmanComponent class (with the graphics)
int stage=0;
public void nextStage()
{
stage++;
}
public void printStage()
{
System.out.println("Your stage number is:"+stage);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(5,BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
g2.setColor(Color.BLACK);
g.drawLine(50, 30, 50, 10);
g.drawLine(50, 10, 130, 10);
g.drawLine(130, 10, 130, 300);
g.drawLine(20, 300, 150, 300);
if (stage==1)
{
//draws the head
g2.setStroke(new BasicStroke(3,BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
Ellipse2D.Double head = new Ellipse2D.Double(25, 30, 50, 50);
g2.draw(head);
}
else if (stage==2)
{
//draws the body
g.drawLine(50, 80, 50, 180);
}
else if (stage==3)
{
//draws the left arm
g.drawLine(10, 150, 50, 100);
}
else if (stage==4)
{
//draws the right arm
g.drawLine(50, 100, 90, 150);
}
else if (stage==5)
{
//draws the left leg
g.drawLine(30, 250, 50, 180);
}
else if (stage==6)
{
//draws the right leg
g.drawLine(50, 180, 70, 250);
}
else if (stage==7)
{
//draws the left eye
Ellipse2D.Double lefteye = new Ellipse2D.Double(40, 50, 1, 1);
g2.draw(lefteye);
g2.fill(lefteye);
}
else if (stage==8)
{
//draws the right eye
Ellipse2D.Double righteye = new Ellipse2D.Double(58, 50, 1, 1);
g2.draw(righteye);
g2.fill(righteye);
}
else if (stage==9)
{
//draws the mouth
Arc2D.Double mouth = new Arc2D.Double(40.00, 50.00, 20.00, 20.00, 180.00, 190.00, Arc2D.OPEN);
g2.draw(mouth);
}
}
Right now, the hangman program runs perfectly fine, but the graphic is only added the first time the user inputs a wrong letter. How do I get the graphics to be inputted for every time a wrong letter is inputted?