PokerFrame (called from a viewer class) worked perfectly, but once I tried to convert it to an applet, it won't load. I don't get any runtime exceptions, just a blank applet space. I won't be able to respond/pick an answer until hours from now, but I'd really appreciate any insights anyone might have....
<HTML><head></head>
<body>
<applet code="PokerApplet.class" width="600" height="350"> </applet>
</body>
</HTML>
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import javax.swing.JFrame;
public class PokerApplet extends JApplet {
public void init() {
final JApplet myApplet = this;
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JPanel frame = new PokerFrame();
frame.setVisible(true);
myApplet.getContentPane().add(frame);
}
});
}
catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
}
import java.awt.Color;
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.net.MalformedURLException;
/** A class that displays a poker game in a JFrame. */
public class PokerFrame extends JPanel {
public static final int HEIGHT = 350;
public static final int WIDTH = 600;
private static final int BUTTON_HEIGHT = 50;
private static final int BUTTON_WIDTH = 125;
// the following variables must be kept out as instance variables for scope reasons
private Deck deck;
private Hand hand;
private int[] handCount; // for keeping track of how many hands of each type player had
private int gamesPlayed;
private int playerScore;
private String message; // to Player
private boolean reviewMode; // determines state of game for conditional in doneBttn listener
private JLabel scoreLabel;
private JLabel gamesPlayedLabel;
private JLabel msgLabel;
private JLabel cardImg1;
private JLabel cardImg2;
private JLabel cardImg3;
private JLabel cardImg4;
private JLabel cardImg5;
/** Creates a new PokerFrame object. */
public PokerFrame() {
this.setSize(WIDTH, HEIGHT);
// this.setTitle("Poker");
gamesPlayed = 0;
playerScore = 0;
handCount = new int[10]; // 10 types of hands possible, including empty hand
message = "<HTML>Thanks for playing poker!"
+ "<br>You will be debited 1 point"
+ "<br>for every new game you start."
+ "<br>Click \"done\" to begin playing.</HTML>";
reviewMode = true;
this.add(createOuterPanel());
deck = new Deck();
hand = new Hand();
}
/** Creates the GUI. */
private JPanel createOuterPanel() {
JPanel outerPanel = new JPanel(new GridLayout(2, 1));
outerPanel.add(createControlPanel());
outerPanel.add(createHandPanel());
return outerPanel;
}
/** Creates the controlPanel */
private JPanel createControlPanel() {
JPanel controlPanel = new JPanel(new GridLayout(1, 2));
controlPanel.add(createMessagePanel());
controlPanel.add(createRightControlPanel());
return controlPanel;
}
/** Creates the message panel */
private JPanel createMessagePanel() {
JLabel msgHeaderLabel = new JLabel("<HTML>GAME STATUS:<br></HTML>");
msgLabel = new JLabel(message);
JPanel messagePanel = new JPanel();
messagePanel.add(msgHeaderLabel);
messagePanel.add(msgLabel);
return messagePanel;
}
/** Creates the right side of the control panel. */
private JPanel createRightControlPanel() {
scoreLabel = new JLabel("Score: 0");
gamesPlayedLabel = new JLabel("Games Played: 0");
JPanel labelPanel = new JPanel(new GridLayout(2, 1));
labelPanel.add(scoreLabel);
labelPanel.add(gamesPlayedLabel);
JButton doneBttn = new JButton("Done");
doneBttn.setPreferredSize(new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT));
class DoneListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (reviewMode) {
reviewMode = false;
startNewHand();
return;
}
else {
reviewMode = true;
while (!hand.isFull()) {
hand.add(deck.dealCard());
}
updateCardImgs();
score();
}
}
}
ActionListener doneListener = new DoneListener();
doneBttn.addActionListener(doneListener);
JPanel donePanel = new JPanel();
donePanel.add(doneBttn);
// stats button!
JButton statsBttn = new JButton("Statistics");
statsBttn.setPreferredSize(new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT));
final JPanel myFrame = this;
class StatsListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// add stats pop window functionality after changing score() method to keep track of that stuff
double numGames = gamesPlayed;
String popupText = "<HTML>You've played " + gamesPlayed + " games. This is how your luck has played out:<br>"
+ "<table>"
+ "<tr><td>HAND DESCRIPTION</td>PERCENTAGE</td></tr>"
+ "<tr><td>royal flush</td><td>" + getPercentage(0) + "</td></tr>"
+ "<tr><td>straight flush</td><td>" + getPercentage(1) + "</td></tr>"
+ "<tr><td>four of a kind</td><td>" + getPercentage(2) + "</td></tr>"
+ "<tr><td>full house</td><td>" + getPercentage(3) + "</td></tr>"
+ "<tr><td>straight</td><td>" + getPercentage(4) + "</td></tr>"
+ "<tr><td>four of a kind</td><td>" + getPercentage(5) + "</td></tr>"
+ "<tr><td>three of a kind</td><td>" + getPercentage(6) + "</td></tr>"
+ "<tr><td>two pair</td><td>" + getPercentage(7) + "</td></tr>"
+ "<tr><td>pair of jacks or better</td><td>" + getPercentage(8) + "</td></tr>"
+ "<tr><td>empty hand</td><td>" + getPercentage(9) + "</td></tr>"
+ "</table></HTML>";
JOptionPane.showMessageDialog(myFrame, popupText, "Statistics", 1);
}
private double getPercentage(int x) {
double numGames = gamesPlayed;
double percentage = handCount[x] / numGames * 100;
percentage = Math.round(percentage * 100) / 100;
return percentage;
}
}
ActionListener statsListener = new StatsListener();
statsBttn.addActionListener(statsListener);
JPanel statsPanel = new JPanel();
statsPanel.add(statsBttn);
JPanel bttnPanel = new JPanel(new GridLayout(1, 2));
bttnPanel.add(donePanel);
bttnPanel.add(statsPanel);
JPanel bottomRightControlPanel = new JPanel(new GridLayout(1,2));
bottomRightControlPanel.add(bttnPanel);
JPanel rightControlPanel = new JPanel(new GridLayout(2, 1));
rightControlPanel.add(labelPanel);
rightControlPanel.add(bottomRightControlPanel);
return rightControlPanel;
}
/** Creates the handPanel */
private JPanel createHandPanel() {
JPanel handPanel = new JPanel(new GridLayout(1, Hand.CARDS_IN_HAND));
JPanel[] cardPanels = createCardPanels();
for (JPanel each : cardPanels) {
handPanel.add(each);
}
return handPanel;
}
/** Creates the panel to view and modify the hand. */
private JPanel[] createCardPanels() {
JPanel[] panelArray = new JPanel[Hand.CARDS_IN_HAND];
class RejectListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (reviewMode) return;
// find out which # button triggered the listener
JButton thisBttn = (JButton) event.getSource();
String text = thisBttn.getText();
int cardIndex = Integer.parseInt(text.substring(text.length() - 1));
hand.reject(cardIndex-1);
switch (cardIndex) {
case 1:
cardImg1.setIcon(null);
cardImg1.repaint();
break;
case 2:
cardImg2.setIcon(null);
cardImg2.repaint();
break;
case 3:
cardImg3.setIcon(null);
cardImg3.repaint();
break;
case 4:
cardImg4.setIcon(null);
cardImg4.repaint();
break;
case 5:
cardImg5.setIcon(null);
cardImg5.repaint();
break;
}
}
}
ActionListener rejectListener = new RejectListener();
for (int i = 1; i <= Hand.CARDS_IN_HAND; i++) {
JLabel tempCardImg = new JLabel();
try {
tempCardImg.setIcon(new ImageIcon(new URL("http://erikaonearth.com/evergreen/cards/top.jpg")));
}
catch (MalformedURLException e) {
e.printStackTrace();
}
String bttnText = "Reject #" + i;
JButton rejectBttn = new JButton(bttnText);
rejectBttn.addActionListener(rejectListener);
switch (i) {
case 1:
cardImg1 = tempCardImg;
case 2:
cardImg2 = tempCardImg;
case 3:
cardImg3 = tempCardImg;
case 4:
cardImg4 = tempCardImg;
case 5:
cardImg5 = tempCardImg;
}
JPanel tempPanel = new JPanel(new BorderLayout());
tempPanel.add(tempCardImg, BorderLayout.CENTER);
tempPanel.add(rejectBttn, BorderLayout.SOUTH);
panelArray[i-1] = tempPanel;
}
return panelArray;
}
/** Clears the hand, debits the score 1 point (buy in),
* refills and shuffles the deck, and then deals until the hand is full. */
private void startNewHand() {
playerScore--;
gamesPlayed++;
message = "<HTML>You have been dealt a new hand.<br>Reject cards,\nthen click \"done\"<br>to get new ones and score your hand.";
hand.clear();
deck.shuffle();
while (!hand.isFull()) {
hand.add(deck.dealCard());
}
updateCardImgs();
updateLabels();
}
/** Updates the score and gamesPlayed labels. */
private void updateLabels() {
scoreLabel.setText("Score: " + playerScore);
gamesPlayedLabel.setText("Games played: " + gamesPlayed);
msgLabel.setText(message);
}
/** Updates the card images. */
private void updateCardImgs() {
try {
String host = "http://erikaonearth.com/evergreen/cards/";
String ext = ".jpg";
cardImg1.setIcon(new ImageIcon(new URL(host + hand.getCardAt(0).toString() + ext)));
cardImg2.setIcon(new ImageIcon(new URL(host + hand.getCardAt(1).toString() + ext)));
cardImg3.setIcon(new ImageIcon(new URL(host + hand.getCardAt(2).toString() + ext)));
cardImg4.setIcon(new ImageIcon(new URL(host + hand.getCardAt(3).toString() + ext)));
cardImg5.setIcon(new ImageIcon(new URL(host + hand.getCardAt(4).toString() + ext)));
}
catch (MalformedURLException e) {
e.printStackTrace();
}
}
/** Fills any open spots in the hand. */
private void fillHand() {
while (!hand.isFull()) {
hand.add(deck.dealCard());
updateCardImgs();
}
}
/** Scores the hand.
* #return a string with message to be displayed to player
* (Precondition: hand must be full) */
private void score() {
String handScore = hand.score();
int pointsEarned = 0;
String article = "a ";
if (handScore.equals("royal flush")) {
handCount[0]++;
pointsEarned = 250;
}
else if (handScore.equals("straight flush")) {
handCount[1]++;
pointsEarned = 50;
}
else if (handScore.equals("four of a kind")) {
handCount[2]++;
pointsEarned = 25;
article = "";
}
else if (handScore.equals("full house")) {
handCount[3]++;
pointsEarned = 6;
}
else if (handScore.equals("flush")) {
handCount[4]++;
pointsEarned = 5;
}
else if (handScore.equals("straight")) {
handCount[5]++;
pointsEarned = 4;
}
else if (handScore.equals("three of a kind")) {
handCount[6]++;
pointsEarned = 3; article = "";
}
else if (handScore.equals("two pair")) {
handCount[7]++;
pointsEarned = 2;
article = "";
}
else if (handScore.equals("pair of jacks or better")) {
handCount[8]++;
pointsEarned = 1;
}
else if (handScore.equals("empty hand")) {
handCount[9]++;
article = "an ";
}
playerScore = playerScore + pointsEarned;
message = "<HTML>You had " + article + handScore + ",<br>which earned you " + pointsEarned + " points.<br>Click \"done\" to start a new hand.";
updateLabels();
}
}
I can see two weak points in your code.
First.
If your applet consists of several classes, you should add codebase attribute to your applet tag, to let it know where to find them.
For example:
<applet code="PokerApplet.class"
codebase="http://localhost/classes" width="600" height="350">
</applet>
So, in this example, your PockerApplet.class, PokerFrame.class and other used classes
should be in classes folder.
If you don't use codebase attribute, then your classes should be in the same folder where your html page with applet tag resides.
Do you consider this?
Second.
Your applet init() method seems strange. Try to use the following variant:
public void init() {
// Bad idea: the applet is not initialized yet
// but you already use link to its instance.
//final JApplet myApplet = this;
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JPanel frame = new PokerFrame();
//frame.setVisible(true); // You don't need this.
// You don't need myApplet variable
// to call getContentPane() method.
//myApplet.getContentPane().add(frame);
getContentPane().add(frame);
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
You can get more help, after you add SSCCE code to your question.
first add the frame then set it to visible. THat usually works
Related
My project uses Java Swing as a GUI. I am making a Towers of Hanoi game. I've just about got the GUI all working, but my solve command wont work properly.
Without threading calls, it immediately solves the towers as expected. I added a couple Thread.waits expected it to solve it step by step so the user can see how it does but instead, it waits some time, then solves the entire puzzle at once. I'm thinking it might not be repainting, but I'm not sure why. Does anyone know what is going on?
Heres the code for the solve:
public class Solver {
public Solver() {
// nothing
}
public void solve(
int numberBlocks,
int startPin,
int auxiliaryPin,
int endPin) {
if (numberBlocks == 1) {
movePin(startPin, endPin);
try {
Thread.sleep(200);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
solve(numberBlocks - 1, startPin, endPin, auxiliaryPin);
movePin(startPin, endPin);
try {
Thread.sleep(200);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
solve(numberBlocks - 1, auxiliaryPin, startPin, endPin);
}
}
private void movePin(int startPin, int endPin) {
TowersOfHanoiGame.moveTopBlock(startPin, endPin);
}
Here is the code from the GUI that does the work:
I know its terribly written, this is my first time writing with Java Swing, Im learning it as I go. If anyone has any pointers on how to better structure this, I'd love to hear about that also.
I'm pasting the whole class, but the important methods are initListeners, and moveTopBlock, and the methods they call.
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TowersOfHanoiGame {
private static JFrame mainWindow;
private static JPanel mainContentPanel;
private static JPanel content;
private static ArrayList<Block> pegOneBlocks = new ArrayList<Block>();
private static ArrayList<Block> pegTwoBlocks = new ArrayList<Block>();
private static ArrayList<Block> pegThreeBlocks = new ArrayList<Block>();
private Color[] randomColors = new Color[8];
private Dimension menuSize = new Dimension(100, 100);
private static final int DISCSTEXTSIZE = 20;
private static final int MOVESTEXTSIZE = 30;
private ActionListener downButtonListener;
private ActionListener upButtonListener;
private ActionListener solveButtonListener;
private JLabel discs;
private JLabel moves;
private int discsNumber = 3;
private int movesNumber = 0;
private Solver solver = new Solver();
public TowersOfHanoiGame() {
// do nothing
initRandomColors();
initBlocks(3);
}
/**
* Initialize and display the game
*/
public void display() {
initListeners();
initWindow();
mainWindow.setVisible(true);
}
private void initListeners() {
downButtonListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (discsNumber > 3) {
discsNumber--;
updateLabels();
// clearContentFrame();
clearBlockArrays();
initBlocks(discsNumber);
reDrawContentFrame();
}
}
};
upButtonListener = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (discsNumber < 8) {
discsNumber++;
updateLabels();
// clearContentFrame();
clearBlockArrays();
initBlocks(discsNumber);
reDrawContentFrame();
}
}
};
solveButtonListener = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
solver.solve(discsNumber, 0, 1, 2);
}
};
}
private void updateLabels() {
discs.setText("DISCS: " + discsNumber);
moves.setText("MOVES: " + movesNumber);
}
/**
* Init the main window
*/
private void initWindow() {
mainWindow = new JFrame("Towers Of Hanoi");
initContentPanel();
mainWindow.setContentPane(mainContentPanel);
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setSize(1000, 1000);
mainWindow.setResizable(false);
mainWindow.getContentPane().setBackground(Color.WHITE);
}
/**
* Init the main content panel
*/
private void initContentPanel() {
mainContentPanel = new JPanel(new BorderLayout(50, 50));
JPanel menu = initMenuFrame();
content = initContentFrame();
mainContentPanel.add(menu, BorderLayout.PAGE_START);
mainContentPanel.add(content, BorderLayout.CENTER);
}
private static JPanel initContentFrame() {
JPanel ret = new JPanel(new BorderLayout());
JPanel pegs = new JPanel(new BorderLayout());
pegs.setBackground(Color.WHITE);
ret.setBackground(Color.WHITE);
Peg peg1 = new Peg(25, 500, 1.2);
Peg peg2 = new Peg(50, 500, 1.2);
Peg peg3 = new Peg(0, 500, 1.2);
peg1.addBlocks(pegOneBlocks);
peg2.addBlocks(pegTwoBlocks);
peg3.addBlocks(pegThreeBlocks);
pegs.add(peg1, BorderLayout.LINE_START);
pegs.add(peg2, BorderLayout.CENTER);
pegs.add(peg3, BorderLayout.LINE_END);
ret.add(pegs, BorderLayout.CENTER);
return ret;
}
private Color randomColor() {
int R = (int)(Math.random() * 256);
int G = (int)(Math.random() * 256);
int B = (int)(Math.random() * 256);
Color color = new Color(R, G, B); // random color, but can be bright or
// dull
// to get rainbow, pastel colors
Random random = new Random();
final float hue = random.nextFloat();
final float saturation = 0.9f;// 1.0 for brilliant, 0.0 for dull
final float luminance = 1.0f; // 1.0 for brighter, 0.0 for black
color = Color.getHSBColor(hue, saturation, luminance);
return color;
}
private void initRandomColors() {
for (int i = 0; i < 8; i++) {
randomColors[i] = randomColor();
}
}
private void initBlocks(int numBlocks) {
int startWidth = Block.LONGESTWIDTH;
for (int i = 0; i < numBlocks; i++) {
Block b = new Block((startWidth - (i * 15)), randomColors[i]);
pegOneBlocks.add(b);
}
}
private static void clearContentFrame() {
mainContentPanel.remove(content);
mainContentPanel.repaint();
}
private void clearBlockArrays() {
pegOneBlocks.clear();
pegTwoBlocks.clear();
pegThreeBlocks.clear();
}
public static void reDrawContentFrame() {
content = initContentFrame();
mainContentPanel.add(content, BorderLayout.CENTER);
mainContentPanel.repaint();
}
public static void moveTopBlock(int startPin, int destinationPin) {
Block b = null;
if (startPin == 0) {
b = pegOneBlocks.get(pegOneBlocks.size() - 1);
pegOneBlocks.remove(pegOneBlocks.size() - 1);
}
else if (startPin == 1) {
b = pegTwoBlocks.get(pegTwoBlocks.size() - 1);
pegTwoBlocks.remove(pegTwoBlocks.size() - 1);
}
else if (startPin == 2) {
b = pegThreeBlocks.get(pegThreeBlocks.size() - 1);
pegThreeBlocks.remove(pegThreeBlocks.size() - 1);
}
if (destinationPin == 0) {
pegOneBlocks.add(b);
}
else if (destinationPin == 1) {
pegTwoBlocks.add(b);
}
else if (destinationPin == 2) {
pegThreeBlocks.add(b);
}
reDrawContentFrame();
content.validate();
mainContentPanel.validate();
mainWindow.validate();
}
/**
* Build the menu panel
*
* #return menu panel
*/
private JPanel initMenuFrame() {
JPanel ret = new JPanel(new BorderLayout());
ret.setPreferredSize(menuSize);
// left
JPanel left = new JPanel(new FlowLayout());
left.setPreferredSize(menuSize);
JLabel label = new JLabel("DISCS: 3");
discs = label;
label.setFont(new Font("Serif", Font.BOLD, DISCSTEXTSIZE));
Button down = new Button("Decrease");
down.addActionListener(downButtonListener);
Button up = new Button("Increase");
up.addActionListener(upButtonListener);
left.add(label);
left.add(up);
left.add(down);
// mid
moves = new JLabel("MOVES: 0");
moves.setHorizontalAlignment(JLabel.CENTER);
moves.setFont(new Font("Serif", Font.BOLD, MOVESTEXTSIZE));
// right
JPanel right = new JPanel(new FlowLayout());
Button solve = new Button("Solve");
solve.addActionListener(solveButtonListener);
Button reset = new Button("Reset");
right.add(solve);
right.add(reset);
// sync
JPanel menu = new JPanel(new BorderLayout());
menu.add(left, BorderLayout.LINE_START);
menu.add(moves, BorderLayout.CENTER);
menu.add(right, BorderLayout.LINE_END);
ret.add(menu, BorderLayout.CENTER);
return ret;
}
}
solveButtonListener = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
solver.solve(discsNumber, 0, 1, 2);
}
};
The problem is that code invoked for any listener is executed on the Event Dispatch Thread (EDT). The EDT is responsible for responding to event and repaint the GUI. The Thread.sleep() method causes the EDT to sleep and as a result the GUI can't repaint itself until all the code has finished executing.
What you need to do is start a separate Thread when you invoke the solver.solve(...) method.
Read the section from the Swing tutorial on Concurrency for more information.
Note, the above suggestion to use a separate Thread is still not a proper solution. Swing was designed to be single Thread, which means that all updates to the state of your GUI and the repainting of the GUI should be done on the EDT. So this would mean you should also be using SwingUtilities.invokeLater() to add code to the EDT for processing. I have never tried doing this when using recursion, so I'm not sure the best way to do this.
My professor told me to put both of these together to make a running program. I am utilizing Netbeans, and it keeps telling me that there is no main class. Am I supposed to create one or am I missing something? How do I put these together into a working gui java application?
Here is the first file, it is called NumberGame
import java.util.Random;
public class NumberGame {
private Random rand = new Random();
private int min, max;
private int num1, num2;
public NumberGame(int min, int max) {
this.min = min;
this.max = max;
newNums();
}
public int getNum1() {
return num1;
}
public int getNum2() {
return num2;
}
public void newNums() {
num1 = rand.nextInt(max - min + 1) + min;
num2 = rand.nextInt(max - min + 1) + min;
}
public int calcSum() {
return num1 + num2;
}
public boolean checkSum(int num) {
return num == calcSum();
}
}
The second file is called App here it is
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class App extends JFrame implements ActionListener {
/* Canvas ============================================ */
private NumberGame numbers;
private Font mainFont = new Font(Font.SANS_SERIF, Font.PLAIN,16);
/* Components for Canvas ============================= */
private JTextField messageField;
private JLabel lblNum1;
private JLabel lblNum2;
private JTextField sumField;
private JButton btnNext;
private JButton btnCheck;
public App(String title, int width, int height) {
// initialize new number game
numbers = new NumberGame(10, 49);
// initialize components
messageField = new JTextField("", 10);
messageField.setEditable(false);
messageField.setHorizontalAlignment(JTextField.CENTER);
messageField.setFont(mainFont);
// add components to board
add(messageField, BorderLayout.NORTH);
add(createCenter(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.SOUTH);
// add action listeners
btnCheck.addActionListener(this);
btnNext.addActionListener(this);
sumField.addActionListener(this);
// create the window
createWindow(title, width, height);
pack();
}
private void createWindow(String title, int width, int height) {
setVisible(true);
setTitle(title);
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JPanel createCenter() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
JLabel lblNumPrompt1 = new JLabel("Number 1 = ", JLabel.RIGHT);
lblNumPrompt1.setFont(mainFont);
lblNum1 = new JLabel(Integer.toString(numbers.getNum1()), JLabel.CENTER);
lblNum1.setFont(mainFont);
JLabel lblNumPrompt2 = new JLabel("Number 2 = ", JLabel.RIGHT);
lblNumPrompt2.setFont(mainFont);
lblNum2 = new JLabel(Integer.toString(numbers.getNum2()), JLabel.CENTER);
lblNum2.setFont(mainFont);
JLabel lblSumPrompt = new JLabel("Sum = ", JLabel.RIGHT);
lblSumPrompt.setFont(mainFont);
sumField = new JTextField("0", 10);
sumField.setHorizontalAlignment(JTextField.CENTER);
sumField.setFont(mainFont);
// add objects to the panel
panel.add(lblNumPrompt1);
panel.add(lblNum1);
panel.add(lblNumPrompt2);
panel.add(lblNum2);
panel.add(lblSumPrompt);
panel.add(sumField);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel();
btnNext = new JButton("Next");
btnCheck = new JButton("Check");
panel.add(btnNext);
panel.add(btnCheck);
return panel;
}
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button.equals(btnNext)) {
numbers.newNums();
lblNum1.setText(Integer.toString(numbers.getNum1()));
lblNum2.setText(Integer.toString(numbers.getNum2()));
} else {
int num = Integer.parseInt(sumField.getText());
if (numbers.checkSum(num))
messageField.setText("Correct!");
else
messageField.setText("Try Again!");
}
}
}
Simply create a main class and initialize the app class as below, HTH.
public static void main(String args[])
{
//Put in the title and size of the Panel
App app1 = new App("MY game", 1000, 900);
}
Create a main class .
Put all 3 classes into same package.
Simply create an object of App class in main class.
Run the main class.
I need to make a piece of text that scrolls along the page by taking each letter and moving it from one jlabel to the next. This is my code so far. It needs a delay because its too fast but it seem to crash when the string has finished. Any help would be appreciated?.
package Lab4;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Scroll extends JFrame implements ActionListener {
final int scrollNumber = 10;
JTextField inputTextField = new JTextField(10);
JLabel[] output = new JLabel[scrollNumber];
JLabel text = new JLabel("Enter text and press Return",
SwingConstants.CENTER);
public Scroll() {
setLayout(new GridLayout(2, 1));
JPanel row1 = new JPanel(new GridLayout(1, 10));
output[0] = new JLabel();
output[1] = new JLabel();
output[2] = new JLabel();
output[3] = new JLabel();
output[4] = new JLabel();
output[5] = new JLabel();
output[6] = new JLabel();
output[7] = new JLabel();
output[8] = new JLabel();
output[9] = new JLabel();
row1.add(output[9]);
row1.add(output[8]);
row1.add(output[7]);
row1.add(output[6]);
row1.add(output[5]);
row1.add(output[4]);
row1.add(output[3]);
row1.add(output[2]);
row1.add(output[1]);
row1.add(output[0]);
add(row1);
JPanel row2 = new JPanel(new GridLayout(1, 2));
row2.add(text);
row2.add(inputTextField);
add(row2);
inputTextField.addActionListener(this);
}
public void shift() {
output[9].setText(output[8].getText());
output[8].setText(output[7].getText());
output[7].setText(output[6].getText());
output[6].setText(output[5].getText());
output[5].setText(output[4].getText());
output[4].setText(output[3].getText());
output[3].setText(output[2].getText());
output[2].setText(output[1].getText());
output[1].setText(output[0].getText());
}
public void run(String input) {
int length = input.length();
int i = 0;
while (true) {
if (output[0] != null) {
output[0].setText(input.substring(i, i + 1));
} else {
output[0].setText("");
}
i = i + 1;
System.out.println("0" + output[0].getText());
System.out.println("1" + output[1].getText());
System.out.println("2" + output[2].getText());
System.out.println("3" + output[3].getText());
System.out.println("4" + output[4].getText());
System.out.println("5" + output[5].getText());
System.out.println("6" + output[6].getText());
System.out.println("7" + output[7].getText());
System.out.println("8" + output[8].getText());
System.out.println("9" + output[9].getText());
shift();
}
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == inputTextField) {
String j = inputTextField.getText();
run("abcdef");
System.out.println(j);
}
}
}
So first of all. Yes your application crashes. Technically its an IndexOutOfBoundsException that you get when invoking input.substring(i, i + 1) in your run method. You increment i in an infinite loop without resitriction. And so it gets higher than your string length with the result that substring then throws that exception.
So first fix is a restriction when incrementing your index.
[...]
i = i + 1;
if(i > length - 1)
i = 0;
Next fix should be a delay. But thats not as easy as it sounds. You should start learning how Threads work in Java because you will need to start one. Thats because you should never send your main Thread to sleep or your GUI will get unresponsible. So I will give you one simple solution and remind you to learn how Threads work.
So remove your run method and change your actionPerformed method like this:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == inputTextField) {
String j = inputTextField.getText();
// run("abcdef");
new Thread(new Runnable(){
#Override
public void run() {
int length = j.length();
int i = 0;
while (true) {
if (output[0] != null) {
output[0].setText(j.substring(i, i + 1));
} else {
output[0].setText("");
}
i = i + 1;
if(i > length - 1)
i = 0;
try {
Thread.sleep(500); // your delay in ms
} catch (InterruptedException e) {
e.printStackTrace();
}
shift();
}
}
}).start();
}
}
import java.awt.BorderLayout;
import java.applet.Applet;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.*;
import java.awt.*;
public class MemoryGame implements ActionListener
{
Label mostra;
public int delay = 1000; //1000 milliseconds
public void init()
{
//add(mostra = new Label(" "+0));
}
public void Contador()
{
ActionListener counter = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
tempo++;
TempoScore.setText("Tempo: " + tempo);
}
};
new Timer(delay, counter).start();
}
public void updateHitMiss()
{
HitScore.setText("Acertou: " + Hit);
MissScore.setText("Falhou: " + Miss);
PontosScore.setText("Pontos: " + Pontos);
}
private JFrame window = new JFrame("Jogo da Memoria");
private static final int WINDOW_WIDTH = 500; // pixels
private static final int WINDOW_HEIGHT = 500; // pixels
private JButton exitBtn, baralharBtn, solveBtn, restartBtn;
ImageIcon ButtonIcon = createImageIcon("card1.png");
private JButton[] gameBtn = new JButton[16];
private ArrayList<Integer> gameList = new ArrayList<Integer>();
private int Hit, Miss, Pontos;
public int tempo = 0;
private int counter = 0;
private int[] btnID = new int[2];
private int[] btnValue = new int[2];
private JLabel HitScore, MissScore,TempoScore, PontosScore;
private JPanel gamePnl = new JPanel();
private JPanel buttonPnl = new JPanel();
private JPanel scorePnl = new JPanel();
protected static ImageIcon createImageIcon(String path)
{
java.net.URL imgURL = MemoryGame.class.getResource(path);
if (imgURL != null)
{
return new ImageIcon(imgURL);
}
else
{
System.err.println("Couldn't find file: " + path);
return null;
}
}
public MemoryGame()
{
createGUI();
createJPanels();
setArrayListText();
window.setTitle("Jogo da Memoria");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
window.setVisible(true);
Contador();
}
public void createGUI()
{
for (int i = 0; i < gameBtn.length; i++)
{
gameBtn[i] = new JButton(ButtonIcon);
gameBtn[i].addActionListener(this);
}
HitScore = new JLabel("Acertou: " + Hit);
MissScore = new JLabel("Falhou: " + Miss);
TempoScore = new JLabel("Tempo: " + tempo);
PontosScore = new JLabel("Pontos: " + Pontos);
exitBtn = new JButton("Sair");
exitBtn.addActionListener(this);
baralharBtn = new JButton("Baralhar");
baralharBtn.addActionListener(this);
solveBtn = new JButton("Resolver");
solveBtn.addActionListener(this);
restartBtn = new JButton("Recomecar");
restartBtn.addActionListener(this);
}
public void createJPanels()
{
gamePnl.setLayout(new GridLayout(4, 4));
for (int i = 0; i < gameBtn.length; i++)
{
gamePnl.add(gameBtn[i]);
}
buttonPnl.add(baralharBtn);
buttonPnl.add(exitBtn);
buttonPnl.add(solveBtn);
buttonPnl.add(restartBtn);
buttonPnl.setLayout(new GridLayout(1, 0));
scorePnl.add(HitScore);
scorePnl.add(MissScore);
scorePnl.add(TempoScore);
scorePnl.add(PontosScore);
scorePnl.setLayout(new GridLayout(1, 0));
window.add(scorePnl, BorderLayout.NORTH);
window.add(gamePnl, BorderLayout.CENTER);
window.add(buttonPnl, BorderLayout.SOUTH);
}
public void setArrayListText()
{
for (int i = 0; i < 2; i++)
{
for (int ii = 1; ii < (gameBtn.length / 2) + 1; ii++)
{
gameList.add(ii);
}
}
}
public boolean sameValues()
{
if (btnValue[0] == btnValue[1])
{
return true;
}
return false;
}
public void actionPerformed(ActionEvent e)
{
if (exitBtn == e.getSource())
{
System.exit(0);
}
if (baralharBtn == e.getSource())
{
//
}
if (solveBtn == e.getSource())
{
for (int i = 0; i < gameBtn.length; i++)
{
gameBtn[i].setText("" + gameList.get(i));
gameBtn[btnID[0]].setEnabled(false);
gameBtn[btnID[1]].setEnabled(false);
}
}
for (int i = 0; i < gameBtn.length; i++)
{
if (gameBtn[i] == e.getSource())
{
gameBtn[i].setText("" + gameList.get(i));
gameBtn[i].setEnabled(false);
counter++;
if (counter == 3)
{
if (sameValues())
{
gameBtn[btnID[0]].setEnabled(false);
gameBtn[btnID[1]].setEnabled(false);
gameBtn[btnID[0]].setVisible(false);
gameBtn[btnID[1]].setVisible(false);
Hit = Hit +1;
Pontos = Pontos + 25;
}
else
{
gameBtn[btnID[0]].setEnabled(true);
gameBtn[btnID[0]].setText("");
gameBtn[btnID[1]].setEnabled(true);
gameBtn[btnID[1]].setText("");
Miss = Miss +1;
Pontos = Pontos - 5;
}
counter = 1; //permite 2(3) clikes de cada vez
}
/*if (Pontos <= 0)
{
Pontos=0;
} */
if (counter == 1) // se carregar 1º botão
{
btnID[0] = i;
btnValue[0] = gameList.get(i);
}
if (counter == 2) // se carregar 2º botão
{
btnID[1] = i;
btnValue[1] = gameList.get(i);
}
}
}
if (restartBtn == e.getSource())
{
Hit=0;
Miss=0;
tempo=-1;
Pontos=0;
for (int i = 0; i < gameBtn.length; i++) /* what i want to implement(restart button) goes here, this is incomplete because it only clean numbers and "transforms" into regular JButton, the last two clicks
on the 4x4 grid (btnID[0] and btnID[1]), but i want to clean all the visible
numbers in the grid 4x4, and want to transform all grid 4x4 into default (or
regular color, white and blue) JButton, the grid numbers stay in same order
or position. */
{
gameBtn[btnID[0]].setEnabled(true);
gameBtn[btnID[0]].setText("");
gameBtn[btnID[1]].setEnabled(true);
gameBtn[btnID[1]].setText("");
}
/*
restartBtn.addActionListener(new ActionListener()
{
JFrame.dispatchEvent(new WindowEvent(JFrame, WindowEvent.WINDOW_CLOSING)); // this line is getting errors (MemoryGame.java:233: error: <identifier> expected
JFrame.dispatchEvent(new WindowEvent(JFrame, WindowEvent.WINDOW_CLOSING));
illegal start of type,')' expected, ';' expected all in the same line )
private JFrame window = new JFrame("Jogo da Memoria");
// something not right, i think frame is replaced by JFrame but i dont know, be
}); */
}
updateHitMiss();
}
public static void main(String[] args)
{
new MemoryGame();
}
}
</code>
Hi,
I want to add a restart button (mouse click), i am running notepadd++, when i click on restart button (recomeçar), it should restart this memory game, all counters set to zero etc, clean the grid 4x4, all numbers that were visible when i click the restart the button they all disaapear (but they are in same place or order) thus only show regular JButtons, the game should go to the starting point like when it first open the application, all numbers are not visible. (the functionality of restart button is equal to exit application and then restart).
Restart button code in lines 215 to 239, issues reported on comments between those lines.
I'm not sure if I fully understand your question, but here's what i think would help:
Add an ActionListener to your button with:
button.addActionListener(new ActionListener() {
});,
with button being the name of your JButton.
Within your ActionListener, call frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));, with frame being the name of your JFrame.
Then, run all of the methods you use to initialize your game (including the one that opens the JFrame).
Comment if you need clarification or more help.
I am trying to get and set the price from my order form to the order summary. Will you take a look at my code and see what I am doing wrong?
My assignment requires me to use an arrayList and a JOptionPane to list out the orders and totals.
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class Subway extends JFrame {
private String[] breadNames = {"9-grain Wheat", "Italian", "Honey Oat", "Herbs and Cheese", "Flatbread"};
private String[] subTypes = {"Oven Roasted Chicken - $3.50", "Meatball Marinara - $4.50", "Cold Cut Combo - $4.00",
"BLT - $3.75", "Blackforest Ham - $4.00", "Veggie Delight - $2.50"};
private String[] cheesetypes = {"Cheddar", "American", "Provolone", "Pepperjack"};
private String[] size = {"6 inch", "Footlong"};
private String[] toasted = {"Yes", "No"};
private JTextField jtfname = new JTextField(10);
private JComboBox<String> jcbBread = new JComboBox<String>(breadNames);
private JComboBox<String> jcbtype = new JComboBox<String>(subTypes);
private JComboBox<String> jcbcheese = new JComboBox<String>(cheesetypes);
private JButton jbtExit = new JButton("EXIT");
private JButton jbtAnother = new JButton("Next Order");
private JButton jbtSubmit = new JButton("SUBMIT");
private JComboBox<String> jcbSize = new JComboBox<String>(size);
private JComboBox<String> jcbToasted = new JComboBox<String>(toasted);
private JCheckBox jcbLettuce = new JCheckBox("Lettuce");
private JCheckBox jcbSpinach = new JCheckBox("Spinach");
private JCheckBox jcbOnion = new JCheckBox("Onion");
private JCheckBox jcbPickles = new JCheckBox("Pickles");
private JCheckBox jcbTomatoes = new JCheckBox("Tomatoes");
private JCheckBox jcbPeppers = new JCheckBox("Peppers");
private JCheckBox jcbMayo = new JCheckBox("Mayo");
private JCheckBox jcbMustard = new JCheckBox("Mustard");
private JCheckBox jcbDressing = new JCheckBox("Italian Dressing");
public Subway() {
//name
JPanel p1 = new JPanel(new GridLayout(24, 1));
p1.add(new JLabel("Enter Name"));
p1.add(jtfname);
//size
p1.add(new JLabel("Select a size"));
p1.add(jcbSize);
//bread
p1.add(new JLabel("Select a Bread"));
p1.add(jcbBread);
//type
p1.add(new JLabel("What type of sub would you like?"));
p1.add(jcbtype);
//cheese
p1.add(new JLabel("Select a cheese"));
p1.add(jcbcheese);
//toasted
p1.add(new JLabel("Would you like it toasted?"));
p1.add(jcbToasted);
//toppings
p1.add(new JLabel("Select your toppings"));
p1.add(jcbLettuce);
p1.add(jcbSpinach);
p1.add(jcbPickles);
p1.add(jcbOnion);
p1.add(jcbTomatoes);
p1.add(jcbPeppers);
p1.add(jcbMayo);
p1.add(jcbMustard);
p1.add(jcbDressing);
// BUTTON PANEL
JPanel p5 = new JPanel();
p5.setLayout(new BoxLayout(p5, BoxLayout.LINE_AXIS));
p5.add(Box.createHorizontalGlue());// KEEPS THEM HORIZONTAL
p5.add(jbtExit);
p5.add(jbtAnother);
p5.add(jbtSubmit);
// ADDING PANELS AND WHERE THEY GO
add(p1, BorderLayout.NORTH);// TOP
add(p5, BorderLayout.SOUTH);// BOTTOM
// SETTING INVISIBLE BORDERS AROUND PANELS TO SPACE THEM OUT
p1.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
p5.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
// EXIT BUTTON LISTENER
jbtExit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
// Another order BUTTON LISTENER
jbtAnother.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
makeASandwich();
}
});
// SUBMIT BUTTON LISTENER
jbtSubmit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
makeASandwich();
for (Sandwich s : Sandwich.order) {
String Order = " ";
Order = jtfname.getText() + "\n"
+ "\nSize: " + s.getSize()
+ "\nType of Sub: " + s.getName()
+ "\nBread: " + s.getBread()
+ "\nCheese: " + s.getCheese()
+ "\nToasted? " + s.getToasted() + "\nToppings: \n";
if (jcbLettuce.isSelected()) {
Order += jcbLettuce.getText();
}
if (jcbSpinach.isSelected()) {
Order += jcbSpinach.getText();
}
if (jcbPickles.isSelected()) {
Order += jcbPickles.getText();
}
if (jcbOnion.isSelected()) {
Order += jcbOnion.getText();
}
if (jcbTomatoes.isSelected()) {
Order += jcbTomatoes.getText();
}
if (jcbPeppers.isSelected()) {
Order += jcbPeppers.getText();
}
if (jcbMayo.isSelected()) {
Order += jcbMayo.getText();
}
if (jcbMustard.isSelected()) {
Order += jcbMustard.getText();
}
if (jcbDressing.isSelected()) {
Order += jcbDressing.getText();
}
Order +=
"\n Price: " + s.getPrice()
+ "\n\n---Next Order---";
JOptionPane.showMessageDialog(null, Order);
}
}
});
}
private void makeASandwich() {
double BLT_Price = 3.00;
Sandwich sandwich = new Sandwich(jcbtype.getItemAt(jcbtype.getSelectedIndex()));
sandwich.setBread(jcbBread.getItemAt(jcbBread.getSelectedIndex()));
sandwich.setCheese(jcbcheese.getItemAt(jcbcheese.getSelectedIndex()));
sandwich.setToasted(jcbToasted.getItemAt(jcbToasted.getSelectedIndex()));
sandwich.setSize(jcbSize.getItemAt(jcbSize.getSelectedIndex()));
//sandwich.setPrice(jcbtype.getItemAt(jcbtype.getSelectedIndex()));
if (jcbtype.getSelectedIndex() == 0) {
sandwich = new Sandwich(jcbtype.getItemAt(jcbtype.getSelectedIndex()), BLT_Price);
}
Sandwich.order.add(sandwich);
}
public static void main(String[] args) {
Subway frame = new Subway();
frame.pack();
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("SUBWAY");
frame.setVisible(true);
frame.setSize(600, 750);
}// ENDOFMAIN
}// ENDOFCLASS
class HoldOrder {
public static List<Sandwich> order = new ArrayList<Sandwich>();
}
class Sandwich {
String bread = "";
String sandwichName = "";
String cheese = "";
String size = "";
String toasted = "";
String lettuce = "";
private String cost = " ";
public static List<Sandwich> order = new ArrayList<Sandwich>();
public Sandwich(String typeOfSandwich, double SubPrice) {
sandwichName = typeOfSandwich;
cost += SubPrice;
}
public String getPrice() {
return cost;
}
public String getName() {
return sandwichName;
}
public void setBread(String s) {
bread = s;
}
public String getBread() {
return bread;
}
public void setCheese(String s) {
cheese = s;
}
public String getCheese() {
return cheese;
}
public void setSize(String s) {
size = s;
}
public String getSize() {
return size;
}
public void setToasted(String s) {
toasted = s;
}
public String getToasted() {
return toasted;
}
//public void setPrice(double s) {
//total = 0;
//}
//public double getPrice() {
//return total;
//}
}
This is a difficult question to answer as it will depend on portions of code you've not shared, but the basic premise will be the same...
IF the combo box of prices contains String, you will need to parse the value as a double...
Object value = jcbtype.getSelectedItem();
double price = Double.parseDouble(value);
sandwich.setPrice(price);
Beware, this will throw an NumberFormatException if the value is not parsable.
IF the combo box contains double values (which it should and then be formatted with a CellRenderer), then you might need to cast...
Object value = jcbtype.getSelectedItem();
double price = (Double)value;
sandwich.setPrice(price);
(I say might, because if you are using Java 7, you can use generics to return the base type of the JComboBox using something like double price = jcbtype.getItemAt(jcbtype.getSelectedIndex()) for example)
in the source code window of the desired class.
Right click -> Source -> Generate setters and getters ... Eclipse will generate the setter and getter methods for you.