I have looked through Google searches and a few online tutorials and I am still stuck. It seems unfortunately I am stuck using AWT to do this assignment, seeing as Swing would be better. My assignment is to draw a die.
Currently I am stuck just trying to draw a line from corner of the the square to the edge of the die I am trying to draw. I have read that writing on top frames is ill-advised, but I am waiting on my instructor to let me know if I can just implement Swing components instead.
Currently, I can get the square to show, but I can't get the line to show after its supposedly drawn. I have read it is drawn, but hidden under another frame/object/component/something. However, how can I get the line show?
Once I can get the line to show, I can (hopefully) start drawing the die and the put the dots on it. I am only looking to get the lines to show, and not on how to do the assignment!
Any help is appreciated!
CSC 211
Example #3
P r e t t y a s a p i c t u r e
=====================================
Purpose: To demonstrate the graphic capability of Java.
*/
public class Example03
{
//
// The main method is quite simple.
// We instantiate a (graphical) object, and we play with it.
//
public static void main(String[] args)
{
System.out.println("Hi!"); //say hola
Die myPicture = new Die(); //instantiate object Die
myPicture.action(); //call type Die object myPicture's action method
System.out.println("Bye!"); //say goodbye
}
} // end Example03 class
Here is my Die class, it displays the die:
/*
File: Die.java
Defines and implements the class for our "graphical" object.
*/
// To define a keyboard
import java.awt.*; // AWT = "Abstract Window Toolkit"
public class Die extends Frame
{
public final int WIDTH = 70; // Dimension of the rectangle
public final int HEIGHT = 70; // to be drawn on the window
private int xA = 200; // Coordinates of A (top left corner)
private int yA = xA; // trying to make the frame square
private int faceSide = 0; // the die's face side
public Die() //public constructor Die to set initial stuff
{
setTitle("Let's play some dice!"); // We set the characteristics of our
setLocation(200, 200); // drawing window: the location,
setSize(400, 400); // the size, and
setBackground(Color.lightGray); // the color of the background
setVisible(true); // And we make it appear
}
//
// The action method reads the position of the picture from the keyboard and validates the face side
//
public void action()
{
BrainsOfTheOperation brains = new BrainsOfTheOperation(); //instantiate a new object of BrainsOfTheOperation
brains.action(); //call object brain's, type of BrainsOfTheOperation, method's action
xA = brains.returnXCoordinate(); //return object brain's x coordinate
yA = brains.returnYCoordinate(); //return object brain's y coordinate
faceSide = brains.returnFaceSide(); //return object brain's dice face side position
repaint();
}
//
// The only "graphical" method of the class is the paint method.
//
public void paint(Graphics pane)
{
pane.setColor(Color.cyan); // We use black paint to label
pane.drawString("A", xA - 15, yA + 5); // the 2 opposite corners
pane.drawString("B", 175 + 5, 175 + 5); // of our rectangle
pane.setColor(Color.blue); // Gray is darker than light gray
pane.drawRect(175, 175, WIDTH , HEIGHT); // This is for the rectangle
// drawBlank(pane);
}
private void drawBlank (Graphics pane)
{
pane.setColor(Color.cyan); // We use black paint to label
pane.drawString("A", xA - 15, yA + 5); // the 2 opposite corners
// pane.drawString("B", 175 + 5, 175 + 5); // of our rectangle
pane.setColor(Color.blue); // Gray is darker than light gray
pane.drawRect(175, 175, WIDTH , HEIGHT); // This is for the rectangle
}
private void drawDot (Graphics pane)
{
}
private void drawOne (Graphics pane)
{
}
private void drawTwo (Graphics pane)
{
}
private void drawThree (Graphics pane)
{
}
private void drawFour (Graphics pane)
{
}
private void drawFive (Graphics pane)
{
}
private void drawSix (Graphics pane)
{
}
} // end class Die
And finally, my BrainsOfTheOperation class that validates an user's input and then asks for coordinates:
import java.util.Scanner;
public class BrainsOfTheOperation
{
public int xA, yA; //coordinates of where the dice will play
private int faceSide = 0; //what side the dice is showing
private boolean faceSideNotValid = true; //used in a while loop to ensure a correct side is chosen
public BrainsOfTheOperation() //public constructor
{
//left blank
}
public void action() //action method to ask for a face side, valid it, and then ask for the dice's coordinates on a frame
{
Scanner keyboard = new Scanner(System.in); // Instantiating a keyboard scanner
while ( faceSideNotValid )
{
System.out.print("Enter the number on the face of the die: ");
faceSide = keyboard.nextInt(); //take the next integer
testIfValid(); //make sure its valid: if faceSide >= to 1 and faceSide <= 6, return false, to break out of while loop
}
System.out.print("Enter the location of the die: ");
xA = keyboard.nextInt(); // Determines the upper left corner of
yA = keyboard.nextInt(); // the square AKA die
}
private void testIfValid() //declare method testIfValid to test if faceSide integer is a valid number for a die
{
if ( faceSide >= 1 && faceSide <= 6 )
{
faceSideNotValid = false; //set the faceSideNotValid to false to end the while loop
}
else //otherwise, leave the boolean faceSideNotValid true as they haven't entered a correct number
{
System.out.println("Number entered invalid please try again!");
faceSideNotValid = true;
}
}
public int returnXCoordinate() //returns the die's x Coordinate
{
return xA;
}
public int returnYCoordinate()//returns the die's y Coordinate
{
return yA;
}
public int returnFaceSide()//returns the die's face side (location)
{
return faceSide;
}
}//end class BrainsOfTheOperation
Related
I need to change the cursor while it moves over an array-list of rectangles by the contain(p) method.The problem is
My first algorithm to use an iterator to iterate through the rectangles doesn't work as expected.The cursor only changes when hovering over the first rectangle,in the other rectangles neither does it respond by showing the cursor changing nor indicate through the console that the cursor is hovering above them?!!
My second solution also refuses to work properly.I use a for loop to iterate over the rectangles, although the rectangles indicate through the console that the mouse is hovering above them, the cursor refuses to change with the exception of the last rectangle.
I use a JPanel in this SSCCE ,only because it reproduces the problem am encountering using a JTextPane...assuming my coding approach is what is in question.
I am thinking may be I may need to a thread to improve response and performance but not sure about the approach.Thanks in advance people.
public class UnstableCursor extends JPanel{
Rectangle2D rec;
ArrayList<Rectangle2D> recList = new ArrayList<>();
public UnstableCursor(){
}
public static void main(String[] args) {
UnstableCursor uc = new UnstableCursor();
JFrame frame = new JFrame();
Mover mv = new Mover(uc);
uc.addMouseListener(mv);
uc.addMouseMotionListener(mv);
JScrollPane jx = new JScrollPane(uc);
frame.getContentPane().add(jx);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2d = (Graphics2D)g;
int x = 5;
for(int i = 0;i < 4;i++){
g2d.setColor(Color.red);
rec = new Rectangle2D.Double(20,x,100,5);
g2d.draw(rec);
recList.add(rec);
x += 50;
}
System.out.println("RecList is: " +recList.size());
}
}
class Mover extends MouseInputAdapter{
UnstableCursor uc;
Rectangle2D rec;
ArrayList<Rectangle2D> reList;
public Mover(UnstableCursor ucc){
uc = ucc;
}
#Override
public void mouseDragged(MouseEvent e) {
super.mouseDragged(e);
Point p = e.getPoint();
System.out.println("xxxx");
}
#Override
public void mouseMoved(MouseEvent e) {
Point p = e.getPoint();
reList = uc.recList;
//System.out.println("List is: "+reList.size());
Iterator <Rectangle2D> recs = reList.iterator();
//--------------------- First Algorithm ----------------------//
if(recs.hasNext()){
rec = recs.next();
if(rec.contains(p)){
System.out.println("inside the rectangle....");
uc.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
else{
uc.setCursor(Cursor.getDefaultCursor());
}
}
//--------------------- Second Algorithm ---------------------//
int r = 0;
for(int i = 0;i<(reList.size());i++){
rec = reList.get(r);
//System.out.println("Rect No: "+r+"X: "+rec.getX()+"Y: "+rec.getY());
r++;
if(rec.contains(p)){
System.out.println("inside the rectangle....");
uc.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
else{
uc.setCursor(Cursor.getDefaultCursor());
}
}
}
}
the cursor refuses to change with the exception of the last rectangle.
Your basic search algorithm is wrong. Once you find a rectangle that contains the point you should set the cursor and break out of the loop, otherwise the next rectangle you check will not be a match and the cursor will be reset again.
Also...
for(int i = 0;i < 4;i++){
g2d.setColor(Color.red);
rec = new Rectangle2D.Double(20,x,100,5);
g2d.draw(rec);
recList.add(rec);
x += 50;
}
... A painting method is for painting only.
You should NOT be creating rectangles and adding them to the array, since the paintComponent() method is continually called when Swing determines the panel needs to be repainted.
The rectangles should be added to the List in the constructor of your class so each rectangle is only added once.
I am writing a program where I have to make my finch robot follow an object. I have written it so that the finch will begin by sensing objects around it once it has been tapped on the top. As soon as I tap the top and cover the sensors, a red light is supposed to turn on and it will follow the object in the direction of the covered sensor. While it is moving, it should be making a buzzing sound and have the light change from red to green. When I stop moving the object, the finch is supposed to turn it's nose back to red and wait until it is either tapped twice to end the program or until the object is moved for it to continue following. However, when I tap it, nothing happens.
Here is my code:
import edu.cmu.ri.createlab.terk.robot.finch.Finch;
public class FollowingAnObject
{
static Finch myF = new Finch();
public static void main(String[] args)
{
myF = new Finch();
}
public FollowingAnObject()
{
while (true)
{
//This begins the movement of the finch
if (myF.isTapped() == true && myF.isObstacleLeftSide() == true && myF.isObstacleRightSide() == true && myF.isObstacle() == true)
{
//LED colours are red, green and blue
myF.setLED(R,0,0);
myF.setWheelVelocities(velocityLeft, velocityRight);
//Triggers the RunAgain function to true so that the program does not stop in one run so that the Finch will continue to move
boolean RunAgain = true;
while(RunAgain)
{
//Calling the Move method for the Finch movements
Move();
//Inside the while, RunAgain loop , there is a conditional statement that makes the program terminate if the Finch has been tapped twice
if (myF.isTapped()==true && myF.isTapped()==true)
{
break;
}
}
}
}
}
// Method for all of the Finch movements
public static void Move()
{
if (myF.isObstacleRightSide() == false && myF.isObstacleLeftSide() == false && myF.isObstacle() == true)
{
MoveStraight();
}
else if (myF.isObstacleRightSide() == false && myF.isObstacleLeftSide() == true)
{
MoveLeft();
}
else if ( myF.isObstacleRightSide() == true && myF.isObstacleLeftSide() == false)
{
MoveRight();
}
else if (myF.isObstacleRightSide()==true && myF.isObstacleLeftSide()==true)
{
StopMoving();
}
}
//All of the variables have been declared
static int Buzz = 300;
static int BuzzDuration = 12;
static int R = 250;
static int G = 250;
static int velocityLeft = 150;
static int velocityRight = 150;
static int turnLeft = -50;
static int turnRight = -50;;
//If the finch is moving straight, the light will be green and both of the wheels will move at 150
public static void MoveStraight()
{
myF.setLED(0, G, 0);
myF.setWheelVelocities(velocityLeft, velocityRight);
myF.buzz(Buzz, BuzzDuration);
}
public static void MoveLeft()
{
//If the finch is moving left, the light will be green, the left wheel will move at -50 and the right wheel will move at 150
myF.setLED(0, G, 0);
myF.setWheelVelocities(turnLeft, velocityRight);
myF.buzz(Buzz, BuzzDuration);
}
public static void MoveRight()
//If the finch is moving right, the light will be green the left wheel will move at 150 and the right wheel will move at -50
{
myF.setLED(0, G, 0);
myF.setWheelVelocities(velocityLeft, turnRight);
myF.buzz(Buzz, BuzzDuration);
}
public static void StopMoving()
//if the Finch is not moving, the colour of the light will be red and the buzzing will stop
{
myF.setLED(R, 0 , 0);
myF.stopWheels();
myF.buzz(Buzz, BuzzDuration);
}
}
Your main method is empty. Java starts at main, so you need to start your new Finch in main.
I'm fairly new to Java, and using NetBeans IDE 7.0.1.
Problem:
I'm trying to finish up a Java applet I've been working on that requires a pie chart. I've implemented the pie chart, but I've not been able to get the text labels to appear next to the data in the legend. Does anyone have any pointers?
package piechartapplet;
import javax.swing.*;
import java.awt.*;
public class PieChartApplet extends JApplet {
int TotalPieChartSlices = 7;
SliceValues[] pieSlice = new SliceValues[TotalPieChartSlices];
private int pieChartValueY;
public PieChartApplet()
{
//Source for input statisctics:
//Global Issues. (2012). World Military Spending. Retrieved from http://www.globalissues.org/article/75/world-military-spending
// Link: http://www.globalissues.org/article/75/world-military-spending
pieSlice[0] = new SliceValues(41.0, Color.RED,"United States");
pieSlice[1] = new SliceValues(8.2, Color.CYAN,"China");
pieSlice[2] = new SliceValues(4.1, Color.GREEN,"Russia");
pieSlice[3] = new SliceValues(3.6, Color.BLUE,"UK");
pieSlice[4] = new SliceValues(3.6, Color.PINK,"France");
pieSlice[5] = new SliceValues(21.3, Color.ORANGE,"Next 10 Countries Combined");
pieSlice[6] = new SliceValues(18.2, Color.LIGHT_GRAY,"Rest of the World");
}
// drawing the pir chart using the values in the array
public int drawPieChartValues(Graphics2D graphics, Rectangle pieChartArea, SliceValues[] pieSlice)
{
// setting font size/style
Font font = new Font("Arial", Font.BOLD, 24);
graphics.setFont(font);
// Title of Pie Chart
graphics.drawString("World Military Spending (% by Country)", 20, 20);
graphics.setFont(font);
// establishing inital area positioning
pieChartArea.x=10;
pieChartArea.y = 30;
// using the array values, rectangles, and color to draw the slices
for(int i=0; i<pieSlice.length;i++)
{
graphics. setColor(pieSlice[i].getSliceColor());
graphics.fillRect(pieChartArea.x, pieChartArea.y, 15, 10);
graphics.setColor(Color.BLACK);
pieChartArea.y+=20;
graphics.drawString(""+pieSlice[i].getSliceValue(), pieChartArea.x+25, pieChartArea.y-10);
}
return pieChartArea.y+=10;
}
//The code below was adapted from an example I found that enables me to pull from
// the array and use the values as the slice sizes, putting them into a 360* pie
// Walker, K. (2012). How to Draw a Pie Chart in Java. Retrieved from http://www.ehow.com/how_6647263_draw-pie-chart-java.html
public void drawPieChart(Graphics2D graphics, Rectangle pieChartArea, SliceValues[] pieSlice) {
// pulling array data for the individual slices
double total = 0.0;
for (int i=0; i<pieSlice.length; i++)
{
total += pieSlice[i].getSliceValue(); //pulling value
}
// drawing the slice and positioning it accordingly
double slice = 0.0D;
int StartAngle = 0;
pieChartArea.x = 20;
for (int i=0; i<pieSlice.length; i++) {
// finding initial and final angels
StartAngle = (int)(slice * 360 / total);
int finalAngle = (int)(pieSlice[i].getSliceValue() * 360 / total);
//loop for last slice
if (i == pieSlice.length-1)
{
finalAngle = 360 - StartAngle;
}
// Pulling color from array and setting accordingly
graphics.setColor(pieSlice[i].getSliceColor()); //pulling color
// drawing pie piece
graphics.fillArc(pieChartArea.x, pieChartValueY, pieChartArea.width/2, pieChartArea.height/2, StartAngle, finalAngle);
slice += pieSlice[i].getSliceValue();
}
}
public void paint(Graphics g)
{
super.paint(g);
pieChartValueY = drawPieChartValues((Graphics2D)g, getBounds(), pieSlice);
drawPieChart((Graphics2D)g, getBounds(), pieSlice);
}
public void init() {
// Sizing my applet
setSize(600,600);
// adding applet to pane
getContentPane().add(new PieChartApplet());
}
}
Here is the 'values' code
package piechartapplet;
import javax.swing.*;
import java.awt.*;
public class SliceValues
{
// Establishing values for the pir chart
private double Slicevalue;
private Color Slicecolor;
private String Slicestring;
// Construction begins...
public SliceValues(double value, Color color, String string) {
this.Slicevalue = value; //values from array
this.Slicecolor = color; //color from array
this.Slicestring = string; //string values
}
// calling slice values, colors, strings, and setting values, colors, strings for each slice
public double getSliceValue() {
return Slicevalue;
}
public void setSliceValue(double value) {
this.Slicevalue = value;
}
public Color getSliceColor() {
return Slicecolor;
}
public void setSliceColor(Color color) {
this.Slicecolor = color;
}
public String getSliceString() {
return Slicestring;
}
public void setSliceString(String string) {
this.Slicestring = string;
}
}
The source code for PieChartDemo1, illustrated here with labels, is included in the distribution.
Does anyone know how to make this applet into an application? After I remove "extends applet", It doesn't work. I'm not sure how to change it into an application and what to write after "extends."
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BlackjackGUI extends JApplet {
public void init() {
The init() method creates components and lays out the applet.
A BlackjackCanvas occupies the CENTER position of the layout.
On the bottom is a panel that holds three buttons. The
BlackjackCanvas object listens for events from the buttons
and does all the real work of the program.
setBackground( new Color(130,50,40) );
BlackjackCanvas board = new BlackjackCanvas();
getContentPane().add(board, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground( new Color(220,200,180) );
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
JButton hit = new JButton( "Hit!" );
hit.addActionListener(board);
buttonPanel.add(hit);
JButton stand = new JButton( "Stand!" );
stand.addActionListener(board);
buttonPanel.add(stand);
JButton newGame = new JButton( "New Game" );
newGame.addActionListener(board);
buttonPanel.add(newGame);
} // end init()
public Insets getInsets() {
// Specify how much space to leave between the edges of
// the applet and the components it contains. The background
// color shows through in this border.
return new Insets(3,3,3,3);
}
// --- The remainder of this class consists of a nested class ---
class BlackjackCanvas extends JPanel implements ActionListener {
// A nested class that displays the card game and does all the work
// of keeping track of the state and responding to user events.
Deck deck; // A deck of cards to be used in the game.
BlackjackHand dealerHand; // Hand containing the dealer's cards.
BlackjackHand playerHand; // Hand containing the user's cards.
String message; // A message drawn on the canvas, which changes
// to reflect the state of the game.
boolean gameInProgress; // Set to true when a game begins and to false
// when the game ends.
Font bigFont; // Font that will be used to display the message.
Font smallFont; // Font that will be used to draw the cards.
BlackjackCanvas() {
// Constructor. Creates fonts and starts the first game.
setBackground( new Color(0,120,0) );
smallFont = new Font("SansSerif", Font.PLAIN, 12);
bigFont = new Font("Serif", Font.BOLD, 14);
doNewGame();
}
public void actionPerformed(ActionEvent evt) {
// Respond when the user clicks on a button by calling
// the appropriate procedure. Note that the canvas is
// registered as a listener in the BlackjackGUI class.
String command = evt.getActionCommand();
if (command.equals("Hit!"))
doHit();
else if (command.equals("Stand!"))
doStand();
else if (command.equals("New Game"))
doNewGame();
}
void doHit() {
// This method is called when the user clicks the "Hit!" button.
// First check that a game is actually in progress. If not, give
// an error message and exit. Otherwise, give the user a card.
// The game can end at this point if the user goes over 21 or
// if the user has taken 5 cards without going over 21.
if (gameInProgress == false) {
message = "Click \"New Game\" to start a new game.";
repaint();
return;
}
playerHand.addCard( deck.dealCard() );
if ( playerHand.getBlackjackValue() > 21 ) {
message = "You've busted! Sorry, you lose.";
gameInProgress = false;
}
else if (playerHand.getCardCount() == 5) {
message = "You win by taking 5 cards without going over 21.";
gameInProgress = false;
}
else {
message = "You have " + playerHand.getBlackjackValue() + ". Hit or Stand?";
}
repaint();
}
void doStand() {
// This method is called when the user clicks the "Stand!" button.
// Check whether a game is actually in progress. If it is,
// the game ends. The dealer takes cards until either the
// dealer has 5 cards or more than 16 points. Then the
// winner of the game is determined.
if (gameInProgress == false) {
message = "Click \"New Game\" to start a new game.";
repaint();
return;
}
gameInProgress = false;
while (dealerHand.getBlackjackValue() <= 16 && dealerHand.getCardCount() < 5)
dealerHand.addCard( deck.dealCard() );
if (dealerHand.getBlackjackValue() > 21)
message = "You win! Dealer has busted with " + dealerHand.getBlackjackValue() + ".";
else if (dealerHand.getCardCount() == 5)
message = "Sorry, you lose. Dealer took 5 cards without going over 21.";
else if (dealerHand.getBlackjackValue() > playerHand.getBlackjackValue())
message = "Sorry, you lose, " + dealerHand.getBlackjackValue()
+ " to " + playerHand.getBlackjackValue() + ".";
else if (dealerHand.getBlackjackValue() == playerHand.getBlackjackValue())
message = "Sorry, you lose. Dealer wins on a tie.";
else
message = "You win, " + playerHand.getBlackjackValue()
+ " to " + dealerHand.getBlackjackValue() + "!";
repaint();
}
void doNewGame() {
// Called by the constructor, and called by actionPerformed() if
// the use clicks the "New Game" button. Start a new game.
// Deal two cards to each player. The game might end right then
// if one of the players had blackjack. Otherwise, gameInProgress
// is set to true and the game begins.
if (gameInProgress) {
// If the current game is not over, it is an error to try
// to start a new game.
message = "You still have to finish this game!";
repaint();
return;
}
deck = new Deck(); // Create the deck and hands to use for this game.
dealerHand = new BlackjackHand();
playerHand = new BlackjackHand();
deck.shuffle();
dealerHand.addCard( deck.dealCard() ); // Deal two cards to each player.
dealerHand.addCard( deck.dealCard() );
playerHand.addCard( deck.dealCard() );
playerHand.addCard( deck.dealCard() );
if (dealerHand.getBlackjackValue() == 21) {
message = "Sorry, you lose. Dealer has Blackjack.";
gameInProgress = false;
}
else if (playerHand.getBlackjackValue() == 21) {
message = "You win! You have Blackjack.";
gameInProgress = false;
}
else {
message = "You have " + playerHand.getBlackjackValue() + ". Hit or stand?";
gameInProgress = true;
}
repaint();
} // end newGame();
public void paintComponent(Graphics g) {
// The paint method shows the message at the bottom of the
// canvas, and it draws all of the dealt cards spread out
// across the canvas.
super.paintComponent(g); // fill with background color.
g.setFont(bigFont);
g.setColor(Color.green);
g.drawString(message, 10, getSize().height - 10);
// Draw labels for the two sets of cards.
g.drawString("Dealer's Cards:", 10, 23);
g.drawString("Your Cards:", 10, 153);
// Draw dealer's cards. Draw first card face down if
// the game is still in progress, It will be revealed
// when the game ends.
g.setFont(smallFont);
if (gameInProgress)
drawCard(g, null, 10, 30);
else
drawCard(g, dealerHand.getCard(0), 10, 30);
for (int i = 1; i < dealerHand.getCardCount(); i++)
drawCard(g, dealerHand.getCard(i), 10 + i * 90, 30);
// Draw the user's cards.
for (int i = 0; i < playerHand.getCardCount(); i++)
drawCard(g, playerHand.getCard(i), 10 + i * 90, 160);
} // end paint();
void drawCard(Graphics g, Card card, int x, int y) {
// Draws a card as a 80 by 100 rectangle with
// upper left corner at (x,y). The card is drawn
// in the graphics context g. If card is null, then
// a face-down card is drawn. (The cards are
// rather primitive.)
if (card == null) {
// Draw a face-down card
g.setColor(Color.blue);
g.fillRect(x,y,80,100);
g.setColor(Color.white);
g.drawRect(x+3,y+3,73,93);
g.drawRect(x+4,y+4,71,91);
}
else {
g.setColor(Color.white);
g.fillRect(x,y,80,100);
g.setColor(Color.gray);
g.drawRect(x,y,79,99);
g.drawRect(x+1,y+1,77,97);
if (card.getSuit() == Card.DIAMONDS || card.getSuit() == Card.HEARTS)
g.setColor(Color.red);
else
g.setColor(Color.black);
g.drawString(card.getValueAsString(), x + 10, y + 30);
g.drawString("of", x+ 10, y + 50);
g.drawString(card.getSuitAsString(), x + 10, y + 70);
}
} // end drawCard()
} // end nested class BlackjackCanvas
} // end class BlackjackGUI
If you're using an Applet-based approach for your game, you may just want to keep it that way. You can create a wrapper window which will hold your applet, which can then operate as normal. All you'll need to do is add a main method to your applet class, like so:
public static void main(String[] args) {
JFrame mainWindow = new JFrame("Blackjack"); // You can change "Blackjack" to anything, it will display that as the window title
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setResizeable(false); // If your applet can handle resizing, you can remove this line
BackjackGUI applet = new BlackjackGUI();
applet.init();
mainWindow.add(applet);
mainWindow.setSize(applet.getSize());
mainWindow.setVisible(true);
}
This will allow your app to run as both an applet and a stand-alone application.
Similar approach like Jake Kings way:
Move everything which isn't purely applet related from the init-method to a method, which produces the main panel. Most often you have such a main panel. Else you can define one.
In the applets init-method, call this new makeMainPanel ().
In parallel, create a main method, to start the application as a Swing JFrame. Create a mainframe, and add the same Panel with that method to your mainframe, and do purely application typical stuff in main.
Now you can call it either way.
I am passing some coordinates from one class to another using the following code
**edited to show more detail
At start of class1:
public class BattleGui implements ActionListener {
private int xCoordinate;
private int yCoordinate;
public void coordinateHandler(int xCoord, int yCoord) {
xCoordinate=xCoord;
yCoordinate=yCoord;
System.out.println("Coordinates Received "+xCoord + " " +yCoord);
System.out.println("Test "+xCoordinate + " " +yCoordinate);
}
public void actionPerformed(ActionEvent e) {
String classname = getClassName(e.getSource());
JComponent component = (JComponent)(e.getSource());
cellState cs = new cellState();
if (classname.equals("JMenuItem")) {
JMenuItem menusource = (JMenuItem)(e.getSource());
String menutext = menusource.getText();
// Determine which menu option was chosen
if (menutext.equals("Load Game")) {
/* BATTLEGUI Add your code here to handle Load Game **********/
System.out.println(cs.turnFeedback());
LoadGame();
}
else if (menutext.equals("Save Game")) {
/* BATTLEGUI Add your code here to handle Save Game **********/
SaveGame();
}
else if (menutext.equals("New Game")) {
/* BATTLEGUI Add your code here to handle Save Game **********/
NewGame();
}
}
// Handle the event from the user clicking on a command button
else if (classname.equals("JButton")) {
JButton button = (JButton)(e.getSource());
int bnum = Integer.parseInt(button.getActionCommand());
int row = bnum / GRID_SIZE;
int col = bnum % GRID_SIZE;
//col=yCoord;
//row=xCoord;
//System.out.println(e.getSource());
//System.out.println(bnum / GRID_SIZE);
fireShot(row, col);
if (row==xCoordinate){
if (col==yCoordinate){
button.setBackground(cellColour[cs.turnFeedback()]);
}
else {
//Remember to change the 1 to whatever is reported back from cell class cell state
//button.setBackground(cellColour[cs.turnFeedback()]);
button.setBackground(Color.BLUE);
}
}
else {
button.setBackground(Color.BLUE);
}
}
}
From class2:
public void shipDeploy() {
int gridLength;
int lengthDraw;
int winningNumbers = 0;
int xCoord;
int yCoord;
xCoord=99;
yCoord=100;
System.out.println(xCoord + "\n" + yCoord);
BattleGui bGui = new BattleGui();
//Passing the coordinates back to the battlegui coordinate handler class
bGui.coordinateHandler(xCoord, yCoord);
}
This passes these two values to a coordinate handler method within the first class.
within this class I have an xCoordinate variable used throughout a variety of methods, the problem is that I dont seem to be able to set this, 0 is always being returned outside of this method for xCoordinate and yCoordinate and I dont understand why, as they seem to be ok in the line System.out.println("Test "+xCoordinate + " " +yCoordinate); above.
just figured it out on my own, quite simple really, actionlistener was basically re-instantiating the variable on every "event" explaining the zero values, as soon as i took this process outside of the listener it worked and set the values as intended. thanks for the input guys and hope this helps someone along the way!