JPanel, List, JFrame - java

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 ?

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.

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

How to update Java HashTable?

I have two Hashtables and one LinkedList in order like:
Hashtable<Character, Hashtable<String, LinkedList<String>>> hashTab = new Hashtable();
Hashtable<String, LinkedList<String>> string_list = new Hashtable();
LinkedList<String> data_list = new LinkedList();
Now i have a function through which i am passing values in the hashtables and linkedlist
public String createPlayerAccount(String FirstName, String LastName, int Age, String Username, String Password, String IPAddress)
{
char username_first_char = Username.charAt(0);
try
{
boolean username_exists = hashTab.get(username_first_char).containsKey(Username);
if(!username_exists)
{
String data_string = FirstName + " " + LastName + " " + Age + " " + Password + " " + IPAddress + playerStatus; //Pass user details to a string
data_list.add(data_string); //Add user details to the linked list
string_list.put(Username, data_list);
hashTab.put(username_first_char, string_list);
return("Dear " + FirstName + ", You have successfully registered");
}
else
{
return("Username already exists");
}
}
catch(Exception e)
{
String data_string = FirstName + " " + LastName + " " + Age + " " + Password + " " + IPAddress +" "+ playerStatus; //Pass user details to a string
data_list.add(data_string); //Add user details to the linked list
string_list.put(Username, data_list);
hashTab.put(username_first_char, string_list);
return("Username successfully added \n ");
}
}
The playerStatus is set to 0 by default. Now i am creating another function for Signin() in which i want the value of playerStatus to be updated to 1. What should i do?
Signin():
public String playerSignIn(String Username, String Password, String IPAddress)
{
char username_first_char = Username.charAt(0);
try
{
String user_profile;
boolean username_exists = hashTab.get(username_first_char).containsKey(Username);
if(username_exists)
{
playerStatus = "1";
//String data_string = Password + " " + IPAddress +" "+ playerStatus; //Pass user details to a string
//data_list.add(data_string); //Add user details to the linked list
//string_list.put(Username, data_list);
//hashTab.put(username_first_char, string_list); //Add user details to the linked list
//return();
//hashTab.put(username_first_char, string_list);
//user_profile = hashTab.get(username_first_char).get(Username).get(0);
return(user_profile);
/*String data_string = Username + " " + Password + " " + IPAddress +" "+ "1"; //Pass user details to a string
data_list.add(data_string); //Add user details to the linked list
string_list.put(Username, data_list);
hashTab.put(username_first_char, string_list);
String get_user_data = hashTab.get(username_first_char).get(Username).get(0);
String[] user_record = get_user_data.split(" ");
String users_status = user_record[5];*/
//return("User status updated: " + user_record[5]);
}
else
{
return("Invalid username or password");
}
}
catch(Exception e)
{
return("PAWNED");
}
}
NOTE: This is the server side of the code. I am making a Client-Server distributed System.
As mentioned in the comments, you need to create a POJO (object class) that will hold information about a given player. I'd name that class Player. If you need to have a string with the information about the player, for sending to the clients, just have a toString() method on the Player class.
When I developer multiplayer games, on the server side I usually use a ConcurrentHashMap to store the information. If the messaging system you are using needs hashtable then you will have headaches with synchronization, which can cause deadlocks if you don't know what you are doing.
Start refactoring your code. After you are using the Player class, the code should be much more readable, and you should be able to spot where another POJO might be useful too.

frame won't repaint after adjusting string

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

how to check if user has input something or not in JDialogBox?

I have created a custom dialog box which requires 3 fields
public class Test{
public static void main(String args[])
{
JTextField firstName = new JTextField();
JTextField lastName = new JTextField();
JPasswordField password = new JPasswordField();
final JComponent[] inputs = new JComponent[] {
new JLabel("First"),
firstName,
new JLabel("Last"),
lastName,
new JLabel("Password"),
password
};
JOptionPane.showMessageDialog(null, inputs, "My custom dialog",JOptionPane.PLAIN_MESSAGE);
System.out.println("You entered " +firstName.getText() + ", " +lastName.getText() + ", " +password.getText());
}
}
How do I check if the user has inserted all fields or not? And even if user close the dialog box it display
You entered , ,
I want to check user input in field and close application if user close dialog box without dsplaying
"You entered , , "
You can check if user has inserted all fields or not as follows:
if(firstName.getText() != "" && lastName.getText() != "" && password.getText() != "")
System.out.println("All fields have been filled!");
else
System.out.println("Some fields are need to be filled!");
EDIT:
For displaying a message after closing the dialog box, you can do it like:
myframe.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
JOptionPane.showMessageDialog(null,"You entered " + firstName.getText() + ", " + lastName.getText() + ", " +password.getText());
}
});
EDIT2:
OK, I think I understand your question now, try this:
public class Test
{
public static void main(String args[])
{
JTextField firstName = new JTextField();
JTextField lastName = new JTextField();
JPasswordField password = new JPasswordField();
final JComponent[] inputs = new JComponent[]
{
new JLabel("First"),
firstName,
new JLabel("Last"),
lastName,
new JLabel("Password"),
password
};
int i = JOptionPane.showConfirmDialog(null, inputs, "My custom dialog",JOptionPane.PLAIN_MESSAGE);
if(i == 0) System.out.println("You entered " + firstName.getText() + ", " + lastName.getText() + ", " + password.getText());
}
}
I suggest a different approach of delimiting each datum.
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Test {
public static void main(String args[])
{
JTextField firstName = new JTextField();
JTextField lastName = new JTextField();
JPasswordField password = new JPasswordField();
final JComponent[] inputs = new JComponent[] {
new JLabel("First"),
firstName,
new JLabel("Last"),
lastName,
new JLabel("Password"),
password
};
JOptionPane.showMessageDialog(null, inputs, "My custom dialog",JOptionPane.PLAIN_MESSAGE);
System.out.println("You entered '" +
firstName.getText() + "', '" +
lastName.getText() + "', '" +
//don't ignore deprecation warnings!
new String(password.getPassword()) + "'.");
}
}
That way, you can tell which field(s) is missing in.
You entered '', 'johnson', ''.
You entered 'john', '', ''.
You entered '', '', 'johnsjohnson'.
Short answer, check to see if there is anything left in the String before print.
if(firstName.getText().equals("")) {
//Respond appropriately to empty string
} else {
// Respond appropriately to non-empty string
}

Categories

Resources