Advanced GUIs and Graphics - java

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.

Related

I need help making JButtons disappear when a condition is met (and also adding buttons when a condition is met) [duplicate]

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

How to get a graphics-method, such as paint, to activate on a button-click

For a school-project, we've recieved a set amount of figures we're supposed to paint on a canvas with the normal Java-graphics method .paint(). This is supposed to be controlled with the help of a few buttons, each painting a different mix of colors. The paint-method is quite easy and works but when we try to connect the buttons, nothing happens but the buttons appearing on the screen. The code reads as following:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class MarcusErikaGrf2 extends Applet implements ActionListener {
Button knapp, knapp2, knapp3, knapp4, knapp5;
boolean svart=false, rod=false, gul=false, gron=false, rensa=false;
int tx[],ty[],pox[],poy[],pgx[],pgy[],pgxf[],pgyf[],bx[],by[],bxf[],byf[],hf[],hy[];
Polygon txy, po, pg, pgf, b, bf, hxy;
public void init (){
this.setSize(800,900);
this.setBackground(Color.white);
this.setLocation(200,1);
knapp= new Button ("Svart");
knapp2= new Button ("Röd & Rosa");
knapp3= new Button ("Gul & Orange");
knapp4 = new Button ("Grön & Blå");
knapp5 = new Button ("Rensa fönstret");
knapp.addActionListener(this);
knapp2.addActionListener(this);
knapp3.addActionListener(this);
knapp4.addActionListener(this);
knapp5.addActionListener(this);
add(knapp);
add(knapp2);
add(knapp3);
add(knapp4);
add(knapp5);
int tx[] = {375,475,425};
int ty[] = {110,110,250};
int pox[] = {65,120,120,65,50};
int poy[] = {350,350,450,450,400};
int pgx[] = {35,88,98,88,35,25};
int pgy[] = {210,210,270,330,330,270};
int pgxf[] = {36,87,97,87,36,26};
int pgyf[] = {211,211,270,329,329,270};
int bx[] = {372, 400, 395, 420, 415, 440/*TP*/, 415, 400, 405, 382, 387 };
int by[] = {60 , 67 , 70 , 77 , 80 , 87 /*TP*/, 95, 88 , 85 , 75 , 70};
int bxf[] = {373,399,394,419,414,439,416,401,406,383,388};
int byf[] = {61,67,70,77,80,86,94,88,85,75,70};
int hx[] = {150,185,225};
int hy[] = {176,120,176};
Polygon txy = new Polygon(tx,ty,tx.length);
Polygon po = new Polygon(pox,poy,pox.length);
Polygon pg = new Polygon(pgx,pgy,pgx.length);
Polygon pgf = new Polygon(pgxf,pgyf,pgxf.length);
Polygon b = new Polygon(bx,by,bx.length);
Polygon bf = new Polygon(bxf,byf,bxf.length);
Polygon hxy = new Polygon(hx,hy,hx.length);
}
#Override
public void paint(Graphics g){
if(svart == true){
g.setColor(Color.black);
g.drawRect(50, 50, 30, 150); //Rektangel 1
g.drawRect(90,50,30,150); //Rektangel 2
g.drawOval(140, 60, 40,30); //Öga 1
g.drawOval(200, 62, 40, 30); //Öga 2
g.fillOval(147,67,15,15); //Pupill 1
g.fillOval(218,69,15,15); //Pupill 2
g.fillOval(310,100,50,120); //Svart oval, Stor
g.fillOval(310, 50, 22, 30); //Svart oval, Medium
g.fillOval(270, 220, 20, 28); //Svart oval, Liten
g.drawOval(100,230,140,40); //Rosa oval, outline
g.fillOval(370,250,100,50); //Svart oval, horisontell
g.drawRect(200,300,180,150); //Grön rektangel, outline
g.drawRect(170,369,10,130);
g.drawRect(140,369,10,130);
g.fillOval(250,480,28,40);
g.fillOval(400,480,14,20);
g.drawOval(280,520,122,200);
g.drawOval(160, 570, 80, 100);
g.drawOval(50,680,140,40);
g.drawRect(65,500,65,150);
g.drawPolygon(pg);
g.drawPolygon(b);
g.setColor(Color.white);
g.fillOval(317, 65, 8, 8); //Vit prick i svart oval, Medium
g.fillOval(277, 235, 6, 6); //Vit prick i svart oval, Liten
}
else if(rod == true){
g.setColor(Color.red);
g.fillOval(161,571,79,99);
g.fillOval(255, 150, 50, 70);
g.setColor(Color.pink);
g.fillOval(101, 231, 138, 38); //Rosa oval
g.fillPolygon(bf);
g.setColor(Color.white);
g.fillOval(255, 170, 50, 50);
}
else if(gron == true){
g.setColor(Color.blue);
g.fillRect(51, 51, 29, 149); //Rektangel 1
g.fillRect(91, 51, 29, 149); //Rektangel 2
g.fillRect(66,501,64,149);
g.fillPolygon(txy);
g.setColor(Color.green);
g.fillRect(201, 301, 179, 149); //Grön rektangel
g.fillOval(51,681,139,38);
g.fillPolygon(pgf);
}
else if(gul == true){
g.setColor(Color.yellow);
g.fillRect(171,370,9,129);
g.fillRect(141,370,9,129);
g.fillOval(281,521,120,198);
g.setColor(Color.orange);
g.fillPolygon(po);
g.fillPolygon(hxy);
g.fillOval(150, 160, 45, 45);
g.fillOval(180, 160, 45, 45);
}
else if(rensa == true){
repaint();
}
}
public void actionPerformed (ActionEvent e){
if(e.getSource() == knapp){
svart = true;
}
else if(e.getSource() == knapp2){
rod = true;
}
else if(e.getSource() == knapp3){
gul = true;
}
else if(e.getSource() == knapp4){
gron = true;
}
else if(e.getSource() == knapp5){
rensa = true;
}
}
}
What are we missing?
In your actionPerformed(...) method you need to invoke:
repaint();
This tells the component to repaint itself.
else if(rensa == true){
repaint();
}
Never invoke repaint() from within a painting method. A painting method is for doing the painting, not scheduling the painting.

Number and loop issue

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;

Java Poker Game - Change diamonds and hearts to red

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;
}
}

How to create a dynamically updating GUI using MyCanvas in Java?

How does one go about dynamically updating a GUI created with MyCanvas in java? I'm trying to program a board game called Lotus.
This is a description of the game:
Players attempt to maneuver their playing pieces (10 in the two-player version, six in the three- or four-player game) from the start area along the game track to the finish area. Pieces move a number of spaces equal to the number of other pieces they are stacked on. Only the piece on the top of a stack may move. There are two entrances onto the game track, but only one route leading to the finish area. The track contains a "trampoline" space which allows a player to double the distance of a move when landing on this spot. The first player to remove all of his pieces wins.
Basically, I have two classes so far. A GameEngine class and a GUI class.
GameEngine.java
package GameEngine;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Stack;
import java.util.Timer;
import javax.swing.JFrame;
import GUI.MyCanvas;
/**
* Lotus Game Engine
*
* Functionality:
* 1) Generates a GUI and modifies it in real-time based on player input through the Finch.
* 2) Tracks whose current turn it is.
* 3) Manages all game pieces on the Lotus game board.
* 4) Determines when a player has won the game.
*
*
*/
public class GameEngine extends Canvas {
// Instantiate a few variables
boolean isRunning = true; // Game is currently active
private java.util.Timer timer;
/* Create 25 stacks that correspond to each position on the game board
ArrayList<Stack<Integer>>[] positions = new ArrayList<Stack<Integer>>[25];
public GameEngine() {
for (int i=0; i<positions.length; i++) {
positions[i] = new Stack<?>();
}
}
*/
//The following 8 Stacks are named using the following conventions:
//posS## - The 'S' indicated that this is one of the starting Stacks.
// - The first number indicates the player (1 or 0)
// - The second number indicates the size of the starting stack (1, 2, 3, or 4)
StackByCompositionWithArrayList<Integer> posS01 = new StackByCompositionWithArrayList<Integer>();
StackByCompositionWithArrayList<Integer> posS02 = new StackByCompositionWithArrayList<Integer>();
StackByCompositionWithArrayList<Integer> posS03 = new StackByCompositionWithArrayList<Integer>();
StackByCompositionWithArrayList<Integer> posS04 = new StackByCompositionWithArrayList<Integer>();
StackByCompositionWithArrayList<Integer> posS11 = new StackByCompositionWithArrayList<Integer>();
StackByCompositionWithArrayList<Integer> posS12 = new StackByCompositionWithArrayList<Integer>();
StackByCompositionWithArrayList<Integer> posS13 = new StackByCompositionWithArrayList<Integer>();
StackByCompositionWithArrayList<Integer> posS14 = new StackByCompositionWithArrayList<Integer>();
// Launch GUI
public static void main(String[] args){
MyCanvas c = new MyCanvas();
JFrame frame = new JFrame();
frame.setSize(420, 420);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.getContentPane().add(c);
frame.setVisible(true);
}
//Loads proper number of game pieces (0's and 1's) into starting stack positions.
public void setUpStacks(){
//Single Stacks
posS01.push(0);
posS11.push(1);
//Double Stacks
for (int x = 0; x < 2; x++){
posS02.push(0);
posS12.push(1);
}
//Triple Stacks
for (int x = 0; x < 3; x++){
posS03.push(0);
posS13.push(1);
}
//Quad Stacks
for (int x = 0; x < 4; x++){
posS04.push(0);
posS14.push(1);
}
}
//#author rshannon
public void gameLoop()
{
timer = new Timer();
timer.schedule(new GameLoop(), 0, 1000 / 60); //new timer at 60 fps, the timing mechanism
}
private class GameLoop extends java.util.TimerTask
{
public void run() { // this becomes the loop
/*
if(pos24counter==10 || pos25counter==10){
isRunning = false;
}
*/
if (!isRunning){
timer.cancel(); // Stop timer
//declareWinner(); // Declare winner
}
}
}
public void Updater (StackByCompositionWithArrayList<Integer> stack, int position, boolean player, Graphics g){
int distance = stack.size();
//PLAYER 1 == TRUE == BLUE == 1
//PLAYER 2 == FALSE == RED == 0
int finalPosition;
if (position == 15){
position = position - 3;
}
if ((position == 16) && (distance > 1)){
position = position - 3;
}
if ((position == 17) && (distance > 2)){
position = position - 3;
}
finalPosition = position + distance;
if (finalPosition == 1){
pos1.push(stack.pop());
}
if (finalPosition == 2){
pos2.push(stack.pop());
}
if (finalPosition == 3){
pos3.push(stack.pop());
}
if (finalPosition == 4){
pos4.push(stack.pop());
}
if (finalPosition == 5){
pos5.push(stack.pop());
}
if (finalPosition == 6){
pos6.push(stack.pop());
}
if (finalPosition == 7){
pos7.push(stack.pop());
}
if (finalPosition == 8){
pos8.push(stack.pop());
}
if (finalPosition == 9){
pos9.push(stack.pop());
}
if (finalPosition == 10){
pos10.push(stack.pop());
}
if (finalPosition == 11){
pos11.push(stack.pop());
}
if (finalPosition == 12){
pos12.push(stack.pop());
}
if (finalPosition == 13){
pos13.push(stack.pop());
}
if (finalPosition == 14){
pos14.push(stack.pop());
}
if (finalPosition == 15){
pos15.push(stack.pop());
}
if (finalPosition == 16){
pos16.push(stack.pop());
}
if (finalPosition == 17){
pos17.push(stack.pop());
}
//*************************************************************************************************************\\
//*************************************************************************************************************\\
//*************************************************************************************************************\\
//*************************************************************************************************************\\
//*************************************************************************************************************\\
//Could make it so the GUI Updater method continuously peeks at each stack, it it
//returns 1 then the circle should be blue, if it returns 0 then the circle should
//be red, and else, it sets the circle to black (empty.)
//OR
//Could make it so the Updater Class executes only when a Finch interaction is made
//In this case, the parameters would include the stack where the position is, (we will
//need to know the size of the stack, so I think we should implement a size method in
//the StackByCompositionWithArrayList Class definition.) Also, we will need to a boolean
//value to determine which player's turn it is. This method will need access to all of the
//position stacks (pos1-pos25.) I think that this class should be written in the GameEngine
//class.
if(distance > 1){
if (player == true){
}
else{
}
}
}
}
GUI.java
package GUI;
import java.awt.GridLayout;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.*;
import GameEngine.StackByCompositionWithArrayList;
public class MyCanvas extends Canvas{
public MyCanvas(){
}
public void paint(Graphics g){
g.setColor(Color.black);
g.drawLine(30, 100, 100, 30);
g.drawLine(300, 30, 100, 30);
g.drawLine(300, 30, 370, 100);
g.drawLine(370, 350, 370, 100);
g.drawLine(370, 350, 320, 350);
g.drawLine(320, 120, 320, 350);
g.drawLine(320, 120, 280, 80);
g.drawLine(120, 80, 280, 80);
g.drawLine(120, 80, 80, 120);
g.drawLine(80, 120, 80, 250);
g.drawLine(80, 250, 100, 270);
g.drawLine(170, 270, 100, 270);
//Breaking pattern, moving to Left most line.
g.drawLine(30, 100, 30, 270);
g.drawLine(30, 270, 80, 320);
g.drawLine(230, 320, 80, 320);
g.drawLine(230, 320, 230, 250);
g.drawLine(300, 250, 230, 250);
g.drawLine(300, 250, 300, 130);
g.drawLine(250, 130, 300, 130);
g.drawLine(250, 130, 250, 200);
g.drawLine(150, 200, 250, 200);
//Breaking pattern, moving to smallest vertical line.
g.drawLine(170, 270, 170, 250);
g.drawLine(100, 250, 170, 250);
g.drawLine(100, 250, 100, 130);
g.drawLine(150, 130, 100, 130);
g.drawLine(150, 130, 150, 200);
g.fillOval(110,140,30,30); //14
g.fillOval(110,180,30,30); //13
g.fillOval(140,210,30,30); //12
g.fillOval(185,210,30,30); //11
g.fillOval(260,140,30,30); //17
g.fillOval(260,180,30,30); //16
g.fillOval(230,210,30,30); //15
g.fillOval(185,280,30,30); //10
g.fillOval(80,280,30,30); //9
g.fillOval(40,210,30,30); //8
g.fillOval(40,130,30,30); //7
g.fillOval(80,55,30,30); //6
g.fillOval(185,40,30,30); //5
g.fillOval(290,55,30,30); //4
g.fillOval(330,130,30,30); //3
g.fillOval(330,210,30,30); //2
g.fillOval(330,290,30,30); //1
}
public void test(Graphics g){
g.setColor(Color.red);
g.fillOval(330,210,30,30); //2
g.fillOval(330,290,30,30); //1
}
}
When I call the test method in GUI.java, it doesn't update the GUI?
Any suggestions on this mess that I have here?
use Swing JPanel instead of AWT Canvas
override paintComponent for JPanel instead of paint for Canvas
put all painting in the array, prepare that before paintComponent / paint is executed, inside paintComponent / paint only loop inside this array
answer to your question is add code line super.paint(g);, then old painting is cleared and a new is dispalyed

Categories

Resources