Im in need of help with my java program code. Basically it is a program that allows users to request an item and the amount they want. If it is in stock they can click a "buy" button. Once clicked a confirm dialog will pop up asking if the user will like to buy 'x' units for 'y' amount. They can either choose yes, no or cancel. If they choose yes a pop up frame with the reciept will come up (havent done this part yet). The problem that i am having is that if they click no or cancel the reciept frame still shows - I dont want it to do this. Please can you tell me what is wrong with my code as it is not performing how i want it to perform. p.s. im a beginner in java as ive only been learning for a month
enter code here
public PurchaseItem() {
this.setLayout(new BorderLayout());
JPanel top = new JPanel();
top.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel bottom = new JPanel();
bottom.setLayout(new FlowLayout(FlowLayout.CENTER));
bottom.add(Buy);
this.add(bottom, BorderLayout.SOUTH);
setBounds(100, 100, 450, 250);
setTitle("Purchase Item");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
top.add(new JLabel("Enter Item Key:"));
top.add(ItemNo);
top.add(new JLabel ("Enter Amount:"));
top.add(AmountNo);
top.add(check);
Buy.setText("Buy"); Buy.setVisible(true);
check.addActionListener(this);
Buy.addActionListener(this);
add("North", top);
JPanel middle = new JPanel();
middle.add(information);
add("Center", middle);
setResizable(true);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
String ItemKey = ItemNo.getText();
String ItemAmount = AmountNo.getText();
String Name = StockData.getName(ItemKey);
int Yes = JOptionPane.YES_OPTION;
int No = JOptionPane.NO_OPTION;
int Amount = Integer.parseInt(ItemAmount);
int Key = Integer.parseInt(ItemKey);
int NewStock = StockData.getQuantity(ItemKey) - Amount;
double Total = Integer.parseInt(ItemAmount) * StockData.getPrice(ItemKey);
if (Name == null){
information.setText("There is no such item");
}
else if (Amount > StockData.getQuantity(ItemKey)) {
information.setText("Sorry there is not enough stock available");
}
else {
information.setText(Name + " selected: " + ItemAmount);
information.append("\nIndividual Unit Price: " + pounds.format(StockData.getPrice(ItemKey)));
information.append("\nCurrent Stock Available: " + StockData.getQuantity(ItemKey));
information.append("\nNew Stock After Sale: " + NewStock);
information.append("\n\nTotal: " + ItemAmount + " Units" + " at " + pounds.format(StockData.getPrice(ItemKey)) + " each");
information.append("\n= " + pounds.format(Total));
}
if (e.getSource() == Buy) {
JOptionPane.showConfirmDialog(null, "Buy " + ItemAmount + " Units" + " for " + pounds.format(Total) + "?");
if (Yes == JOptionPane.YES_OPTION) {
JFrame frame2 = new JFrame();
frame2.pack(); frame2.setBounds(250, 250, 500, 500); frame2.setTitle("Reciept"); frame2.setVisible(true);
JPanel middle = new JPanel();
middle.setLayout(new FlowLayout(FlowLayout.CENTER));
middle.add(reciept);
reciept.setBounds(260,260,400,400);
reciept.setVisible(true);
}
}
}
}
if (Yes == JOptionPane.YES_OPTION) { is always true (Yes been equal to JOptionPane.YES_OPTION; int Yes = JOptionPane.YES_OPTION;).
You need to get the return value from JOptionPane.showConfirmDialog and compare that
int response = JOptionPane.showConfirmDialog(null, "Buy " + ItemAmount + " Units" + " for " + pounds.format(Total) + "?");
if (response == JOptionPane.YES_OPTION) {
...
}
Related
I have a blackjack game with a guy that has a reset button in the ActionListener. However, when I use it, much of the program's functionality isn't there. The reset is invoked by:
public class BlackjackGameTable extends JFrame{
JButton stayButton = new JButton("STAY");
JButton hitButton = new JButton("HIT");
JButton resetButton = new JButton("Reset");
JLabel background;
Hand playerhand = new Hand();
Hand dealerhand = new Hand();
JLabel score;
JLabel text;
class DecisionListener implements ActionListener{
public void actionPerformed(ActionEvent a){
if(a.getSource() == hitButton){
CardGame2.hit(playerhand, dealerhand);
playerAddCardToTable(new CardRender2(playerhand.cardlist.get(playerhand.getSize()-1)));
score.setText("Your score: " + playerhand.getScore());
System.out.println("YOU CHOSE HIT! Your Score: " + playerhand.getScore());
}
else if(a.getSource() == stayButton){
System.out.println("YOU CHOSE STAY!");
}
else if (a.getSource() == resetButton){
//I've tried this below
dispose();
new BlackjackGameTable()
//this almost works but the main doesn't execute
//I've also tried:
dispose();
main(null);
//I get a black jframe
//and lastly
dispose();
new BlackjackGameTable().main(null);
}
}
}
public BlackjackGameTable(){
this.setTitle("Blackjack");
background = new TableComponent();
background.setLayout(null);
this.add(background,BorderLayout.CENTER);
this.setVisible(true);
this.setSize(1300,867);
JPanel buttonPanel = new JPanel();
score = new JLabel("Your score: " + playerhand.getScore() );
text = new JLabel("WELCOME TO BLACKJACK!");
ActionListener pressChoice = new DecisionListener();
hitButton.addActionListener(pressChoice);
stayButton.addActionListener(pressChoice);
resetButton.addActionListener(pressChoice);
buttonPanel.setSize(300,150);
buttonPanel.add(text, BorderLayout.PAGE_START);
buttonPanel.add(hitButton,BorderLayout.WEST);
buttonPanel.add(stayButton,BorderLayout.EAST);
buttonPanel.add(score, BorderLayout.PAGE_END);
buttonPanel.add(resetButton, BorderLayout.EAST);
buttonPanel.setVisible(true);
this.add(buttonPanel, BorderLayout.SOUTH);
CardGame2.dealIn(playerhand);
CardGame2.dealInDealer(dealerhand);
CardRender2 playerFirstCard = new CardRender2(playerhand.cardlist.get(0));
CardRender2 playerSecondCard = new CardRender2(playerhand.cardlist.get(1));
background.add(playerFirstCard);
playerFirstCard.setBounds(0,110, playerFirstCard.image.getWidth(), playerFirstCard.image.getHeight());
background.add(playerSecondCard);
playerSecondCard.setBounds(120, 110, playerSecondCard.image.getWidth(), playerSecondCard.image.getHeight());
CardRender2 dealerFirstCard = new CardRender2();
CardRender2 dealerSecondCard = new CardRender2(dealerhand.cardlist.get(1));
background.add(dealerFirstCard);
dealerFirstCard.setBounds(0, 550, dealerFirstCard.image.getWidth(), dealerFirstCard.image.getHeight());
background.add(dealerSecondCard);
dealerSecondCard.setBounds(120,550,dealerSecondCard.image.getWidth(), dealerSecondCard.image.getHeight());
score.setText("Your score: " + playerhand.getScore());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void playerAddCardToTable(CardRender2 c){
background.add(c);
c.setBounds((playerhand.getSize() - 1) * c.image.getWidth(), 110, c.image.getWidth(), c.image.getHeight());
revalidate();
}
public void dealerAddCardToTable(CardRender2 d){
background.add(d);
d.setBounds((dealerhand.getSize() -1) * d.image.getWidth(), 550, d.image.getWidth(), d.image.getHeight());
revalidate();
}
public void dealerReveal(){
CardRender2 dealerOGCard = new CardRender2(dealerhand.cardlist.get(0));
background.add(dealerOGCard);
dealerOGCard.setBounds(0, 500, dealerOGCard.image.getWidth(), dealerOGCard.image.getHeight());
}
public static void main(String[] args){
System.out.println("Welcome to Blackjack!\n");
BlackjackGameTable g = new BlackjackGameTable();
System.out.println("Dealer hand: " + g.dealerhand.cardlist + " " + g.dealerhand.getScore());
System.out.println("Your hand: " + g.playerhand.cardlist + " " + g.playerhand.getScore());
boolean playerStillIn = true;
while((playerStillIn) && (!CardGame2.isBusted(g.playerhand))){
if(g.playerhand.getScore() != 21){
g.text.setText("Hit or stay?");
if(g.hitButton.getModel().isPressed()){
g.score.setText("Your score: " + g.playerhand.getScore());
System.out.println("YOUR HAND: " + g.playerhand.cardlist);
System.out.println("YOUR SCORE: " + g.playerhand.getScore());
}
else if (g.stayButton.getModel().isPressed()){
playerStillIn = false;
}
}
else{
System.out.println("BLACKJACK 21!!! YOU WIN BIGLY");
g.text.setText("BLACKJACK 21!!! YOU WIN BIGLY");
g.dealerReveal();
break;
}
}
if (CardGame2.isBusted(g.playerhand)){
System.out.println("BUSTED! YOU LOSE!!");
g.text.setText("BUSTED! YOU LOSE!!");
g.dealerReveal();
}
else{
while(((g.dealerhand.getScore() < 17) && (CardGame2.noBusted(g.playerhand,g.dealerhand))) &&(g.playerhand.getScore() != 21)) {
CardGame2.hit(g.dealerhand,g.playerhand);
g.dealerAddCardToTable(new CardRender2(g.dealerhand.cardlist.get(g.dealerhand.getSize()-1)));
}
if ((g.playerhand.getScore() == g.dealerhand.getScore())) {
System.out.println("DEALER HAND: " + g.dealerhand.getHand() + " and SCORE: " + g.dealerhand.getScore());
System.out.println("YOUR HAND: " + g.playerhand.getHand() + " and SCORE: " + g.playerhand.getScore());
System.out.println("PUSH");
g.text.setText("PUSH");
g.dealerReveal();
}
else if((CardGame2.isBusted(g.dealerhand)) && (g.playerhand.getScore() != 21)){
System.out.println("DEALER HAND: " + g.dealerhand.getHand() + " and SCORE: " + g.dealerhand.getScore());
System.out.println("YOUR HAND: " + g.playerhand.getHand() + " and SCORE: " + g.playerhand.getScore() );
System.out.println("YOU WIN");
g.text.setText("YOU WIN");
g.dealerReveal();
}
else if ((g.playerhand.getScore() < g.dealerhand.getScore())) {
System.out.println("DEALER HAND: " + g.dealerhand.getHand() + " and SCORE: " + g.dealerhand.getScore());
System.out.println("YOUR HAND: " + g.playerhand.getHand() + " and SCORE: " + g.playerhand.getScore());
System.out.println("YOU LOSE");
g.text.setText("YOU LOSE");
g.dealerReveal();
}
else if ((g.playerhand.getScore() > g.dealerhand.getScore()) && g.playerhand.getScore() != 21) {
System.out.println("DEALER HAND: " + g.dealerhand.getHand() + " and SCORE: " + g.dealerhand.getScore());
System.out.println("YOUR HAND: " + g.playerhand.getHand() + " and SCORE: " + g.playerhand.getScore());
System.out.println("YOU WIN");
g.text.setText("YOU WIN");
g.dealerReveal();
}
}
}
}
how might I go about getting this reset?
I am working on a simple file reader. It reads the .txt file then formats the output and displayed the output in a JTextArea. For some reason, the output does not display correctly. I have given my current code, followed by the text file contents below.
Code
public static JTextArea display = new JTextArea();
public static void main(String[] args) {
// GUI
JFrame frame = new JFrame("Haberdasher");
frame.setSize(450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JPanel container = new JPanel();
container.setLayout(null);
frame.setContentPane(container);
JScrollPane scroll = new JScrollPane(display);
scroll.setBounds(10, 10, 415, 150);
container.add(scroll);
frame.toFront();
frame.setVisible(true);
// Logic
String path = "src//employees.txt";
boolean endOfFile = false;
String output = "Name" + "\t\t" + "Weekly Sales" + "\t\t" + "Weekly Pay" + "\n";
try {
FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr);
while (!endOfFile) {
String name = br.readLine();
if(name == null) {
endOfFile = true;
} else {
int sale = Integer.parseInt(br.readLine());
if(name.length() >= 16) {
output += name + "\t" + sale + "\t\t" + "300" + "\n";
} else {
output += name + "\t\t" + sale + "\t\t" + "300" + "\n";
}
}
}
br.close();
System.out.println(output);
display.setText(output);
} catch (IOException e) {
System.out.println(e);
}
}
employees.txt Contents: http://hastebin.com/ijuyedizil.nginx
Current Output:
Expected Output: http://hastebin.com/epesipatot.nginx
Now, the output is fine in the console, but not in the JTextArea.
If you want the text to align like it does on the console need to use a monospaced font
textArea.setFone( new Font("monospaced", Font.PLAIN, 10) );
You may also need to use:
textArea.setTabSize(...);
I would like to apologize in advance I am new to java and don't know very much so stick with me please. I would like to know how to get my character attributes from one ActionListener method in one class to another ActionListener method in another class. I would like to get the inputs from the user about player1 in one class and then use them in the other class. Please help, and I appreciate your time.
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
if(event.getSource() == create){
Character player1 = new Character( Integer.parseInt(strength.getText()), Integer.parseInt(defense.getText()), Integer.parseInt(health.getText()) , Integer.parseInt(dexterity.getText()));
player1.name = name.getText();
JOptionPane.showMessageDialog(this, "\nName: " + player1.name + "\nHealth: " + player1.health + "\nStrength: " + player1.strength + "\nDefense: " + player1.defense + "\nDexterity: " + player1.dexterity);
dispose();//To close the current window
GameWindow gwindow = new GameWindow();
gwindow.setVisible(true);//Open the new window
}
put into
#Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
Character Goblin = new Character(10, 3, 6, 10);
Character Witch = new Character(2, 7, 3, 20);
Character Zombie = new Character(5, 5, 5, 15);
int damage;
if (event.getSource() == right) {
label1.setText("You have encountered a goblin!");
label2.setText("Do you wish to fight or flee?");
fight.setVisible(true);
flee.setVisible(true);
}
if(event.getSource() == fight) {
System.out.println(player1 + " VS. " + Goblin.name);
while(player1.isAlive() && Goblin.isAlive()){
// player 1 attack
damage = player1.attack(Goblin);
System.out.println(player1.name + " hits " + Goblin.name + " for " + damage + " damage.");
// player 2 attack
damage = Goblin.attack(player1);
System.out.println(Goblin.name + " hits " + player1.name + " for " + damage + " damage.\n");
}
// Check to see who won
if( player1.isAlive()){
System.out.println(player1.name + " wins!");
}
else{
System.out.println("You have perished");
}
}
}
Declare Player1 as public Static member
So it's Value can;t be changed.
and You can use player1 Through the object of that particular Class.
Class First{
//Declare That Character object as a static public here
//Player1;
}
Class Second{
//First Create Object Of that class....
First f = new First(//Parameter For Constructor);
f.Player1;
}
Change your GameWindow constructor like this.
class GameWindow extends JFrame implements ActionListener{
private Character player1;
public GameWindow(Character player1){
this.player1 = player1;
}
#Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
Character Goblin = new Character(10, 3, 6, 10);
Character Witch = new Character(2, 7, 3, 20);
Character Zombie = new Character(5, 5, 5, 15);
int damage;
if (event.getSource() == right) {
label1.setText("You have encountered a goblin!");
label2.setText("Do you wish to fight or flee?");
fight.setVisible(true);
flee.setVisible(true);
}
if(event.getSource() == fight) {
System.out.println(player1 + " VS. " + Goblin.name);
while(player1.isAlive() && Goblin.isAlive()){
// player 1 attack
damage = player1.attack(Goblin);
System.out.println(player1.name + " hits " + Goblin.name + " for " + damage + " damage.");
// player 2 attack
damage = Goblin.attack(player1);
System.out.println(Goblin.name + " hits " + player1.name + " for " + damage + " damage.\n");
}
// Check to see who won
if( player1.isAlive()){
System.out.println(player1.name + " wins!");
}
else{
System.out.println("You have perished");
}
}
}
}
And pass parameter to new contructor.
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
if(event.getSource() == create){
Character player1 = new Character( Integer.parseInt(strength.getText()), Integer.parseInt(defense.getText()), Integer.parseInt(health.getText()) , Integer.parseInt(dexterity.getText()));
player1.name = name.getText();
JOptionPane.showMessageDialog(this, "\nName: " + player1.name + "\nHealth: " + player1.health + "\nStrength: " + player1.strength + "\nDefense: " + player1.defense + "\nDexterity: " + player1.dexterity);
dispose();//To close the current window
GameWindow gwindow = new GameWindow(player1);
gwindow.setVisible(true);//Open the new window
}
Figured out the problem , Now I just don't know how to fix it .
The problem is when the user clicks Save Button , it saves all the textfields to the correct strings and to the Summary but it doesn't add the JPanel to the ArrayList of Panels .
saveEntryButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String name = nametf.getText();
String username = usernametf.getText();
String password = passwordtf.getText();
String description = descriptiontf.getText();
String summary = "Name: " + name + "\n"
+ "Username: " + username + "\n"
+ "Password: " + password + "\n"
+ "Description: " + description + "\n\n";
JPanel entryPanel = new JPanel();
JLabel entryLabel = new JLabel(summary);
entryPanel.add(entryLabel);
entries.add(entryPanel);
entryFrame.dispose();
mainMenu mmaa = new mainMenu();
mmaa.menuFrame();
}
});
When debugging I saw that the ArrayList entries , was empty (size of 0) .
So that's why nothing is showing on the ViewFrame. Does anyone know how to make a List of JPanels ? Or any other container that is able to Add and Remove JPanels ?
I am not sure what I am doing wrong to get my frame to change when I have the user input data and press enter to adjust the string that was set to display on the frame. I am just going to include the code that I feel is applicable since the whole code is pretty long, but if someone would like to see more of something, let me know and I can post more. Thank you for the help!
//adds the Flower data to the Array and list
ActionListener flowerAddAction = new ActionListener(){
#Override
public void actionPerformed(ActionEvent flowerAddAction){
if(flowerAddAction.getActionCommand().equals("Enter")){
Name = NameTxt2.getText();
Colors = ColorTxt2.getText();
Smell = SmellTxt.getText();
ID = (int) IDCmbo.getSelectedItem();
if(((String) ThornCmbo.getSelectedItem()).equals("Yes"))
Thorns = true;
else
Thorns = false;
plants[count] = new Flower(Name, ID, Colors, Smell, Thorns);
displayEntered.setText(displayArray);
count++;
frame.repaint();
frameB.setVisible(false);
}
}
};
enterFlrData.addActionListener(flowerAddAction);
this code above is to add the action to when the user presses enter after inputting data into the textFields and ComboBoxes. Below creates a long string of an array that is created by the input. (If anyone has a better way of displaying an array on a JLabel I'd love to know because I know this is a little sloppy.
//create a string of all values for the array
displayArray = " ";
String displayArraytemp = " ";
for(int n = 0; n < 25; n++){
if(plants[n] != null){
if(plants[n] instanceof Flower){
displayArraytemp = (n + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Flower)plants[n]).getColor() + ", " + ((Flower)plants[n]).getSmell() + ", Thorny: " + ((Flower)plants[n]).getThorns() + "/n");
}
else if(plants[n] instanceof Fungus){
displayArraytemp = (n + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Fungus)plants[n]).getColor() + ", Poisonous: " + ((Fungus)plants[n]).getPoisonous() + "/n");
}
else if(plants[n] instanceof Weed){
displayArraytemp = (n + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Weed)plants[n]).getColor() + ", Edible: " + ((Weed)plants[n]).getEdible() + ", Medicinal: " + ((Weed)plants[n]).getMedicinal() + ", Poisonous: " + ((Weed)plants[n]).getPoisonous() + "/n");
}
else if(plants[n] instanceof Herb){
displayArraytemp = (n + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Herb)plants[n]).getColor() + ", " + ((Herb)plants[n]).getFlavor() + ", Medicinal: " + ((Herb)plants[n]).getMedicinal() + ", Poisonous: " + ((Herb)plants[n]).getSeasonal() + "/n");
}
displayArray += (displayArraytemp + "/n");
}
}
Below is showing the rest creating the label and includes the main method.
final JPanel p2Base = new JPanel();
displayEntered = new JLabel(displayArray);
//entire constant GUI put together
p2Base.setLayout(new BorderLayout(10,10));
p2Base.add(menuBar, BorderLayout.NORTH);
p2Base.add(p1Right, BorderLayout.EAST);
p2Base.add(displayEntered, BorderLayout.WEST);
public static void main(String[] args) {
frame = new GUI();
frame.setTitle("Plant Database");
frame.setSize(900,700);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
This looks suspicious to me:
flowerAddAction.getActionCommand().equals("Enter")
If you want this ActionListener respond to pressing the enter button then this will fail since the actionCommand String will not be "Enter". I'm not even sure what it will be, and don't really care, since I usually use ActionListener's for each component and so usually don't test the actionCommand String.
As for your messy array code, consider instead giving your flowers a decent toString() method or method of a similar idea that returns a useful String that can be displayed. That way you can get rid of all of those instanceof operations and have much simpler smaller code.
Edit
I should just shut up and read the API. The action command of a JTextField is the text it contains, unless you set it explicitly.
import java.awt.event.*;
import javax.swing.*;
public class EnterActionCommand {
public static void main(String[] args) {
JTextField field1 = new JTextField(10);
JTextField field2 = new JTextField(10);
// **** set the action command explicitly for field2 ****
field2.setActionCommand("Field 2");
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.printf("action command: \"%s\"%n", e.getActionCommand());
}
};
field1.addActionListener(actionListener);
field2.addActionListener(actionListener);
JPanel panel = new JPanel();
panel.add(new JLabel("Field 1:"));
panel.add(field1);
panel.add(new JLabel("Field 2:"));
panel.add(field2);
JOptionPane.showMessageDialog(null, panel);
}
}