frame won't repaint after adjusting string - java

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

Related

Unable to append text to jtextarea, upon performing a task

I'm trying to achieve something similar to this. Live debug text area.
In my case, I have a scrollPanel which has a textArea. I need to run a bunch of SQL queries and output the query and the result one by one.
private JTextArea uploadProcess = new JTextArea();
I click a button to perform the update, and it has a MouseListener with mouseClicked action.
btnFinish.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
String countNumber = textField.getText();
String mcu = textField_1.getText();
if(!countNumber.isEmpty() && !mcu.isEmpty()) {
if(mcu.length()==12) {
upload(path, countNumber, mcu,environment[env]);
}
} else {
JOptionPane.showMessageDialog(contentPane,
"UPLOAD FAILED!!",
"ERROR!",
JOptionPane.ERROR_MESSAGE);
}
}
});
ps. I know that mouseClicked action is waiting for all the upload method, and then updating.
The upload method:
uploadProcess.setText("Uploading Process Started...\nThere are "+ sqls.size() + " records.\n\n");
Database db = new Database();
db.connect(envo);
int resluts = 0;
for(int i =0; i<sqls.size();i++) {
resluts = db.updateQuery(sqls.get(i));
uploadProcess.append("Query #" + i + "\n " +sqls.get(i));
uploadProcess.append("\n " + resluts + " row(s) updated in " + envo);
sqls.set(i, sqls.get(i) + " \n " + resluts + " row updated.");
}
Any help/advice is helpful.

How to call variables from another class into an ActionListener method?

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
}

Java Button for program

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) {
...
}

Issue changing JPanel with JButton

I'm having a problem! I'm making an app with multiple panels. I'm using Card Layout and I don't have this problem with changing to the other panels. I have a JButton (in a panel called optionsPanel) that should first change to the panel "panelCargando" (which has two JLabel, one with text and the other with a squared animated GIF (72x72)) and then looks after some info using Twitter4J that is showed in another JPanel called tweetsPanel. The problem is that when I press the button, it doesn't hide the other panels and make "panelCargando" visible, it keeps the options panel in the front and when it finishes looking for the info, it puts both panels together. Here's the code that I'm using in the ActionListener of the JButton:
btnNewButton_2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
mainPanel.setVisible(false);
optionsPanel.setVisible(false);
tweetsPanel.setVisible(false);
panelCargando.setVisible(true);
long lCursor = -1;
IDs friendsIDs;
try
{
friendsIDs = twitter.getFriendsIDs(twitter.getId(), lCursor);
System.out.println(twitter.showUser(twitter.getId()).getName());
do
{
for (long i : friendsIDs.getIDs())
{
if(textArea.getText().isEmpty())
{
textArea.setText(textArea.getText() + "ID de usuario: " + i +
"\nNombre de usuario: #" + twitter.showUser(i).getScreenName() +
"\nNombre: " + twitter.showUser(i).getName() +
"\nDescripción: " + twitter.showUser(i).getDescription() +
"\nImagen de perfil: " + twitter.showUser(i).getProfileImageURLHttps() +
"\nSigue a " + twitter.showUser(i).getFriendsCount() + " usuarios" +
"\nTiene " + twitter.showUser(i).getFollowersCount() + " seguidores\n");
}
else
{
textArea.setText(textArea.getText() + "\nID de usuario: " + i +
"\nNombre de usuario: #" + twitter.showUser(i).getScreenName() +
"\nNombre: " + twitter.showUser(i).getName() +
"\nDescripción: " + twitter.showUser(i).getDescription() +
"\nImagen de perfil: " + twitter.showUser(i).getProfileImageURLHttps() +
"\nSigue a " + twitter.showUser(i).getFriendsCount() + " usuarios" +
"\nTiene " + twitter.showUser(i).getFollowersCount() + " seguidores\n");
}
}
}
while(friendsIDs.hasNext());
frame.setTitle("Información sobre seguidores de " + twitter.showUser(twitter.getId()).getName() + " - BISmart");
panelCargando.setVisible(false);
tweetsPanel.setVisible(true);
tweetsPanel.setFocusable(true);
tweetsPanel.requestFocusInWindow();
So, finally I see the "tweetsPanel" panel with the textArea and the "panelCargando" in the front. In that code that I put here, I changed it and added "panelCargando.setVisible(false)", but this way I can't see it at all.
Can anyone help me with this? If it's not clear please let me know! Thank you all!
EDIT
Now the code is this one, but I keep having problems with the same. Even if I do "layout.show(frame.getContentPane(), "panelCargando")", the panel doesn't show. I added this:
layout = new CardLayout(0,0);
frame.getContentPane().setLayout(layout);
frame.getContentPane().add(splashPanel, "splashPanel");
frame.getContentPane().add(newTweetPanel, "newTweetPanel");
frame.getContentPane().add(mainPanel, "mainPanel");
frame.getContentPane().add(tweetsPanel, "tweetsPanel");
frame.getContentPane().add(optionsPanel,"optionsPanel");
frame.getContentPane().add(panelCargando, "panelCargando");
And the actionPerformed looks like this:
public void actionPerformed(ActionEvent arg0)
{
layout.show(frame.getContentPane(), "panelCargando");
long lCursor = -1;
IDs friendsIDs;
try
{
friendsIDs = twitter.getFriendsIDs(twitter.getId(), lCursor);
System.out.println(twitter.showUser(twitter.getId()).getName());
do
{
for (long i : friendsIDs.getIDs())
{
if(textArea.getText().isEmpty())
{
textArea.setText(textArea.getText() + "ID de usuario: " + i +
"\nNombre de usuario: #" + twitter.showUser(i).getScreenName() +
"\nNombre: " + twitter.showUser(i).getName() +
"\nDescripción: " + twitter.showUser(i).getDescription() +
"\nImagen de perfil: " + twitter.showUser(i).getProfileImageURLHttps() +
"\nSigue a " + twitter.showUser(i).getFriendsCount() + " usuarios" +
"\nTiene " + twitter.showUser(i).getFollowersCount() + " seguidores\n");
}
else
{
textArea.setText(textArea.getText() + "\nID de usuario: " + i +
"\nNombre de usuario: #" + twitter.showUser(i).getScreenName() +
"\nNombre: " + twitter.showUser(i).getName() +
"\nDescripción: " + twitter.showUser(i).getDescription() +
"\nImagen de perfil: " + twitter.showUser(i).getProfileImageURLHttps() +
"\nSigue a " + twitter.showUser(i).getFriendsCount() + " usuarios" +
"\nTiene " + twitter.showUser(i).getFollowersCount() + " seguidores\n");
}
}
}
while(friendsIDs.hasNext());
frame.setTitle("Información sobre seguidores de " + twitter.showUser(twitter.getId()).getName() + " - BISmart");
layout.show(frame.getContentPane(), "tweetsPanel");
}

JPanel, List, JFrame

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 ?

Categories

Resources