Adding a GUI to my application - java

I have this library application that has a few different methods in its controller class. One of them is called checkOut which is used to checkout library items.
I'm trying to make this happen when the "checkout" button is now pressed and am hoping that it can get all the necessary information from the txt fields I have created.
I did the following and it is just blowing up with red errors everywhere when I press "checkout" while running. Any help is appreciated, thx!
if (source == checkoutButton)
{
/*JDialog checkout = new JDialog(checkoutContent, "Checkout", true);
JPanel panel = new JPanel();
checkout.setBounds(750, 300, 350, 190);
checkout.setResizable(false);
checkout.add(panel);
checkout.setVisible(true);*/
String borrowerID = userIDTxtField.getText();
String code = itemIDField.getText();
String date = dateField.getText();
String copyString = code.substring(1);
int copy=Integer.valueOf(copyString);
if (ctrl.checkBorrower(borrowerID))
{
boolean valid = false;
SimpleDateFormat sdf1= new SimpleDateFormat("M/dd/yyyy");
sdf1.setLenient(false);
while (!valid)
{
try
{
sdf1.parse(date);
catalogArea.setText(ctrl.checkOut(borrowerID, code, copy, date));
valid = true;
}
catch (Exception e)
{
catalogArea.setText("Date is not valid. Please try again.");
continue;
}
}
}
else
{
catalogArea.setText("Sorry Invalid ID");
}
}

while (!valid)
{
try
{
sdf1.parse(date);
catalogArea.setText(ctrl.checkOut(borrowerID, code, copy, date));
valid = true;
}
catch (Exception e)
{
catalogArea.setText("Date is not valid. Please try again.");
continue;
}
}
This code will cause an effectively infinite loop if the date is invalid. The GUI would most probably be blocked (if this is happening on the EDT - if not on the EDT, the GUI updates are incorrect) so the user would be prevented from changing the invalid date that is causing the loop.
To solve this problem, I'd look to 1st changing code not shown in the loop. Basically, the dateField (presumably a JTextField), should be a JSpinner.
See How to Use Spinners in the tutorial for that screen shot, working code, and further tips.
If the text field was instead a spinner, the entire validation shenanigans is made redundant. The spinner will provide a valid (but not necessarily correct - User Intelligence API required) date.

Related

PlaceHolderAPI not working

As part of my plugin i have a clear chat command and at the end of the blank messages there is an option to display text. My problem is that the PlaceHolderAPI isn't working as it should.
Command Code:
if (label.equalsIgnoreCase("clearchat") || label.equalsIgnoreCase("mcc")) {
if (p.hasPermission("mystic.chat.admin.clearchat")) {
for (int i = 0; i < getConfig().getInt("clearChat.blankLines"); i++) {
Bukkit.broadcastMessage(" ");
}
for (String s : getConfig().getStringList("clearChat.endMessage")) {
s = PlaceholderAPI.setPlaceholders(p, s);
// This is here to check if the PlaceHolderAPI even knows there is place holders in it
p.sendMessage(String.valueOf(PlaceholderAPI.containsPlaceholders(s)));
Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', s));
}
return true;
} else {
p.sendMessage(ChatColor.RED + "You are lacking the required permission node!");
return true;
}
}
Config File section:
clearChat:
blankLines: 256
endMessage:
- '&bChat was cleared by %player_name%'
When i run the command "/mcc" or "/clearchat" it always says false (for not recognizing any placeholders) and none of the place holders are replaced.
I do have the API correctly in the build path, and the command words perfectly, other than the place holders not converting.
I feel as if im making a stupid mistake, or that im doing this the complete wrong way...
You shouldn't need to use another api using p.getName() should suffice then using String.replace to replace the %name%
You are using the API wrong
You did this
s = PlaceholderAPI.setPlaceholders(p, s);
If the API would throw an error if there are no placeholders just surround that line with a try{} catch (Exception e) then send it to the player
p.sendMessage(s);
There is no need for the String.valueOf(s) as the API [is expected to] return a String, anyways setting the String s = PlaceholderAPI.setPlaceholders(p, s); will cast whatever object is there to a string.

Problems with setting text to a textField

I am creating a client-server chat application and I intend required to store the username for a better user experience.As soon as I fire the main method, the load() method is called.This method sets the user name automatically by reading from the configurations file.The configuration file is not null (I have the user name stored). But the textField is not updating.Any ideas?Here is my load method:
public static void load()
{
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
prop.load(input);
textField.setText(prop.getProperty("user")); //not updating!!!!
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Thanks for your help, guys.I figured out the problem.Actually, I had declared textfield as:
static JTextField textField=new JTextField();
outside main() and then again as:
textField=new JTextField();
inside the constructor.I removed the one inside the constructor and it solved the problem.
Once again thank you all for your help.
To add on to what Andreas Fester said above. You should first do a check on the file, if it exists or not, this will allow you to verify you are pointing to the right directory in the case the root of the project. Also add a clause saying something like if(prop.getProperty("user")==null){//handle null} then also try using textField.append("text"); just to see a different method and then verify by doing System.out.println("TextField: "+textField.getText()) to see if it is setting the text
If anything look at this demo given by oracle to use textfield. Also its a good practice to know when to separate member variable (belongs to instance) or class variables(static), I would avoid static like in the demo provided.
hope this helps.

Sikuli - Click on element does not work with Java API but it works from IDE - WPF app

I am evaluating tools for testing a WPF based app. I am currently trying Sikuli with the Java API. When I try to click on an object from Java code, the mouse cursor goes to the object and the object is highlighted, however the click action does not work, because the expected menu does not open. The click() method returns status 1 though.
If I am doing a click from Sikuli IDE, it works fine.
I tried 1.0.1 version and also the nightly build. Here's my code:
#Test
public void testLogin() {
Screen s = new Screen();
try {
s.wait(Constants.overflowMenu);
System.out.println(s.click(Constants.overflowMenu));
s.wait(Constants.signInMenuOption, 5);
} catch (FindFailed e) {
Assert.fail(e.getMessage());
}
}
What am I doing wrong?
try this code, it worked for me. what it does, it checks the image, click on it and then check this image again on the screen, if it still exists, click again.
Screen screen = new Screen();
Pattern pattern = null;
try
{
pattern = new Pattern(imageLocation);
screen.wait(pattern,30);
screen.click(pattern);
System.out.println("First Attempt To Find Image.");
}
catch(FindFailed f)
{
System.out.println("Exception In First Attempt: " +f.getMessage());
System.out.println("FindFailed Exception Handled By Method: ClickObjectUsingSikuli. Please check image being used to identify the webelement. supplied image: " +imageLocation);
Assert.fail("Image wasn't found. Please use correct image.");
}
Thread.sleep(1000);
//In case image/object wasn't clicked in first attempt and cursor stays in the same screen, then do second atempt.
if(screen.exists(pattern) != null)
{
try
{
screen.getLastMatch().click(pattern);
System.out.println("Second Attempt To Find Image.");
System.out.println("Object: " +imageLocation + " is clicked successfully.");
}
catch(FindFailed f)
{
System.out.println("Exception In Second Attempt: " +f.getMessage());
System.out.println("FindFailed Exception Handled By Method: ClickObjectUsingSikuli. Please check image being used to identify the webelement. supplied image: " +imageLocation);
}
}
In my case it seems it was a problem with the fact that I have two monitors..

Printing chatter names from server file in a textfield Java

I would like to ask about how can I print the names of the chatters in a textfield that I created in my client file. Here is the code snippet of the server file that I have:
while (true) {
out.println("SUBMITNAME");
name = in.readLine();
if (name == null) {
return;
}
synchronized (names) {
if (!names.contains(name)) {
names.add(name);
}
break;
}
}
}
This piece of code gets the names of the chatters but I cannot display them in a textfield. Thank you very much for your help!
You can try jTextArea.append("ChatterName\n") or jTextArea.append("ChatterName<br/>"), (I think the break tag might be the issue).
But a JList IMO would be much nicer.
private DefaultListModel defaultListModel = new DefaultListModel() ;
private JList jList = new JList(defaultListModel) ;
defaultListModel.addElement(chatterName);
That appends a chatter name nicely to a JList.

create a text file in java

I have a problem about creating a textfile with the name I want.
I want to create a textfile named : 'username' Subjects.
private void saveSubjects(){
RegisterFrame r = new RegisterFrame();
String username = r.txtUser.getText();;
try{
FileWriter f = new FileWriter(username + "" + "Subjects" + ".txt", true);
String subjects[] = lstSubjects.getItems();
for(int i = 0; i<subjects.length; i++){
f.write(subjects[i] + "\r\n");
}
f.close();
JOptionPane.showMessageDialog(null, "Data saved!", "Data Saved", JOptionPane.INFORMATION_MESSAGE);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Nothing Inputted!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
I want to get the username from RegisterFrame as it is inputted there but it's not working.
I know it's a simple thing but I'm still a beginner in this. How can I solve this?
Thanks in advance
try this:
String username = r.txtUser.getText();
System.out.println("The loaded username is: " + username);
then you will see where your problem is : writing into the file OR getting the username text.
If the problem is in getting the text, consider other way of getting it or modify the question by removing the file write part and specifiing the username getting part.
Otherwise, IDK where the error is.
BTW: how is it not working? the file is not created at all? do you see any errors? the file has wrong name? please specify
Your code for writing the file seems to be fine. Based on your code I tried this which worked perfectly:
public static void main(String[] args) {
FileWriter f = null;
try {
f = new FileWriter("Subjects.txt", true);
String subjects[] = {"subject1", "subject2"};
for (String subject : subjects) {
f.write(subject + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(f);
}
}
I'd say your problem is elsewhere.
Please note that best practice dictates that Closeable objects such as FileWriter should be closed in a finally block
Assuming new RegisterFrame() starts up a GUI window, the issue is your code runs before you have a chance to type in your name. Instead you need to use event listeners to capture the contents of text fields, otherwise the code to get the name runs immediately after the window opens, long before you have a chance to type anything in.
The timeline is like this:
RegisterFrame starts a new thread to display the GUI without blocking your code
Your code immediately pulls "" from txtUser, which is of course empty
Now you type your name in
Nothing happens, because nothing in your code is paying attention to that action
Instead, it should be:
RegisterFrame starts a new thread to display the GUI without blocking your code
The method returns, or starts doing work that isn't dependent on the GUI
Now you type your name in
An event listener is triggered from the new thread, and the associated action to get the name and write to a file is executed
You have to decide what sort of listener makes sense for your use case, for instance you might want to wait until the user clicks a button (that says "Submit" or "Write File" for instance) and register an ActionListener on that button. Then you put your username polling and file writing behavior in that action* and you're golden!
*I should add that in truth you want to do as little as possible in ActionListeners, and it would be better to check if the username is not empty, then pass the actual work off to another thread, for instance with a SwingWorker, but for your purposes I suspect it will be alright to not worry about that.

Categories

Resources