EDIT: Basically the UI class sends #login to the client, the client sends it to the server, the server sends back "#login" to the client indicating successful log-in and the client sends the "#login" along to the UI via UI.display()
Apologies for bad grammar/formatting.
Here's the most relevant block of code, with explanation to follow:
else if (e.getSource() == this.loginButton)
{
if (this.soundON == true)
{
this.clickSound.play();
}
this.client.handleMessageFromClientUI("#login "+this.loginField.getText());
this.client.handleMessageFromClientUI("#balance");
this.client.setLoginID(this.loginField.getText());
if (this.loggedIn)
{
this.loginButton.setEnabled(true);
this.note.setText("Account Screen");
this.status.setText("Logged in to: "+this.client.getLoginID());
this.mainDisplay.removeAll();
this.controlBar.removeAll();
this.mainDisplay.add(Box.createRigidArea(new Dimension(0,30)));
this.mainDisplay.add(this.title);
this.mainDisplay.add(Box.createRigidArea(new Dimension(0,50)));
this.mainDisplay.add(Box.createRigidArea(new Dimension(100,0)));
this.mainDisplay.add(this.balanceLabel);
this.mainDisplay.add(Box.createRigidArea(new Dimension(0,110)));
this.controlBar.add(debitButton);
this.controlBar.add(creditButton);
this.controlBar.add(quitButton);
this.repaint();
}
else
{
JOptionPane.showMessageDialog(null, "Log-in Failed.", "alert", JOptionPane.ERROR_MESSAGE);
}
}
public void display(String msg)
{
if (msg.startsWith("#LOGIN"))
{
this.loggedIn = true;
}
else if (msg.startsWith("#BALANCE"))
{
this.balanceLabel.setText("Balance: $"+msg.substring(43));
this.repaint();
}
else if (msg.startsWith("#ALERT"))
{
JOptionPane.showMessageDialog(null, msg.substring(7), "Server Message", JOptionPane.PLAIN_MESSAGE);
}
else
{
//JOptionPane.showMessageDialog(null, msg, "Server Message", JOptionPane.INFORMATION_MESSAGE); //For debugging
}
}
This is just part of the class, here's the rest: http://pastebin.com/3f99eFWk
My problem is in actionPerformed(ActionEvent e) in the loginButton case. It always goes to this Block once initially when the button is clicked:
else
{
JOptionPane.showMessageDialog(null, "Log-in Failed.", "alert", JOptionPane.ERROR_MESSAGE);
}
then if I click the button again it works and goes to the if (this.loggedIn) case block. loggedIn=true is obtained when This line is executed:
this.client.handleMessageFromClientUI("#login "+this.loginField.getText());
which in turn calls:
public void handleMessageFromClientUI(String message)
{
else
{
try
{
sendToServer(message);
}
catch(IOException e)
{
clientUI.display("Could not send message to server.");
//quit();
}
}
}
Which calls server.handleMessageFromClient(Object msg, Connection client) that has the following relevant code in it:
try
{
client.sendToClient("#LOGIN Logging in to account: "+tempStr);
}
catch (IOException e)
{
System.out.println("Failed to send message to client");
}
client.setInfo("loginID", tempStr);
I know it doesn't fail to send, I've tested it out. The problem is why does the if statement in actionPerformed fail the first time the button is pressed even though the text is typed in the textfield, then passes the second time??
Related
I created a basic selfhosted SignalR server with the following code:
class Program
{
static void Main(string[] args)
{
// This will *ONLY* bind to localhost, if you want to bind to all addresses
// use http://*:8080 to bind to all addresses.
// See http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx
// for more information.
string url = "http://localhost:8080";
using (WebApp.Start(url))
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
public class MyHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
}
}
Which is taken from: https://learn.microsoft.com/en-us/aspnet/signalr/overview/deployment/tutorial-signalr-self-host and works with the Javascript client.
I am now trying to create a Java client and got the following code that is simply supposed to send a message to the server:
String host = "http://localhost:8080";
HubConnection connection = new HubConnection(host);
HubProxy proxy = connection.createHubProxy("MyHub");
connection.start();
try {
System.out.println("Sendng message...");
proxy.invoke( "Send", "Client", "Hello world!" ).get();
System.out.println("Message sent!");
} catch (InterruptedException e) {
System.out.println("err1");
// Handle ...
} catch (ExecutionException e) {
System.out.println("err2");
// Handle ...
}
The problem that im having is that the message is not received by the server, it seems like the code is stuck at the invoke call and doesn't print the Hello world! message. Does someone know what im doing wrong?
hubProxy.invoke("sendMessageByUser", Message, WebApiToken).done(new Action<Void>() {
#Override
public void run(Void aVoid) {
if (aVoid != null)
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(MyApplicationService.this, "Mesaj gönderildi", Toast.LENGTH_SHORT).show();
}
});
}
}).onError(new ErrorCallback() {
#Override
public void onError(final Throwable error) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(MyApplicationService.this.getApplicationContext(), "Bir hata oluştu" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
}
});
I am making a gui for POP3 commands I am having a problem editing my JTextPane in the GUI outside of the initialize() method
Part of the Action Listener:
public void actionPerformed(ActionEvent e)
{
String Input = Commands.getText();
verifyUserAndPass();
if(Input.substring(0).equals("QUIT")) {
System.exit(0);
}
if(Input.substring(0,4).equals("LIST")) {
ListCommand(Input);
}
if(Input.substring(0,4).equals("STAT")) {
ListCommand(Input);
}
if(Input.substring(0,4).equals("RETR")) {
try {
RETRCommand(Input);
} catch (IOException e1) {
e1.printStackTrace();
}
}
if(Input.substring(0,4).equals("DELE")) {
Delete(Input);
}
if(Input.substring(0,4).equals("NOOP")) {
Display.setText("+OK");
}
if(Input.substring(0,4).equals("UIDL")) {
if(userEntered == true && passEntered == true) {
Display.setText("the UIDL is"+String.valueOf(ui));
ui++;
}else {
Display.setText("Please sign in first");
}
}
if(Input.substring(0,3).equals("TOP")) {
try {
TOP(Input);
} catch (IOException e1) {
e1.printStackTrace();
}
}
if(Input.substring(0,4).equals("RSET")) {
Delete(Input);
}
the verifyUserAndPass method:
public void verifyUserAndPass() {
String Input = Commands.getText();
System.out.println(Input+"randomstring");
if(Input.substring(0, 4).equals("USER")) {
try {
if(verifyUser(Input.substring(5))) {
Display.setText("+OK");
Commands.setText("");
userEntered = true;
} else {
Display.setText("-ERR");
}
} catch (IOException e1) {
e1.printStackTrace();
Display.setText("-ERR");
}
}
if(Input.substring(0, 4).equals("PASS")) {
try {
if(userEntered == true) {
if(verifyPass(Input.substring(5))) {
Display.setText("+OK");
Display.setText("Welcome, you are now logged in");
Commands.setText("");
passEntered = true;
} else {
Display.setText("-ERR");
}
} else {
Display.setText("Please enter USER first");
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Commands is a JTextField,
Display is a JTextPane.
for some reason, I can edit Commands outside the ActionListener but not Display
e.g. The Display.setText under the NOOP if works but not the one in verifyUserAndPass() method
but the Commands.setText works
What am I doing wrong?
It is quite hard to answer this question without you providing more details, but I can name a common issue:
Display may not be initialized, check your program's flow and then you can see why it is not being initialized.
Moreover, please abide the Java conventions for everyone's sake. Variables and methods are typed in camelcasing. So these ones would need to be changed:
String Input to String input.
ListCommand() to listCommand().
etc. I hope you get the idea.
I have a form that give Fname and Lname and Date and a method to write this information to a file.
If Fname or Lname contain digit, the program should display an error message and not run all below statements ,(like write to file and generate random number and...), and not exit.
since i dont know how to do like this, in my code i write if Fname or Lname have digit, exit !
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
setFName(jTextField1.getText());
if(havedigit(getFName())==true) {
System.exit(1);
}
setLName(jTextField2.getText());
if(havedigit(lastName)==true) {
System.exit(1);
}
WriteToFile(getFName());
WriteToFile(getLName());
setDate(Integer.parseInt(jTextField3.getText()));
WriteToFile(String.valueOf(getDate()));
Random rnd1=new Random();
Registration_Number=rnd1.nextInt(100);
setRegNum(Registration_Number);
WriteToFile(String.valueOf(getRegNum()));
jLabel6.setText(String.valueOf(getRegNum()));
}
catch(Exception e){
jLabel6.setText("Error!");
}
}
public boolean havedigit(String in){
for(int i=0;i<in.length();i++){
if(Character.isDigit(in.charAt(i))) return true;
}
return false;
}
please help!
That's why you need checked exceptions. Just throw SomeException instead of System.exit(1) and process it properly in block:
catch (SomeException e){
jLabel6.setText("Error!");
}
Don't think that catching all exceptions is a good idea.
Here's one way you could do it:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
setFName(jTextField1.getText());
setLName(jTextField2.getText());
boolean firstNameHasDigit = havedigit(getFName());
boolean lastNameHasDigit = havedigit(getLName());
if (firstNameHasDigit || lastNameHasDigit) {
jLabel6.setText("Names cannot contain digits");
}
else {
WriteToFile(getFName());
WriteToFile(getLName());
setDate(Integer.parseInt(jTextField3.getText()));
WriteToFile(String.valueOf(getDate()));
Random rnd1=new Random();
Registration_Number=rnd1.nextInt(100);
setRegNum(Registration_Number);
WriteToFile(String.valueOf(getRegNum()));
jLabel6.setText(String.valueOf(getRegNum()));
}
}
catch(Exception e){
jLabel6.setText("Error!");
}
}
public boolean havedigit(String in){
for(int i=0;i<in.length();i++){
if(Character.isDigit(in.charAt(i))) return true;
}
return false;
}
As a general rule, try to stay away from using System.exit() in GUI-driven applications. It'll just make the whole program quit, leaving the user wondering what happened. System.exit() is usually better suited for command line applications that want to provide an exit code to the shell and it's a parallel to the system exit calls available in most operating systems.
Try this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
setFName(jTextField1.getText());
if(havedigit(getFName())) {
jLabel6.setText("First name error!");
return;
}
setLName(jTextField2.getText());
if(havedigit(lastName)) {
jLabel6.setText("Last name error!");
return;
}
WriteToFile(getFName());
WriteToFile(getLName());
setDate(Integer.parseInt(jTextField3.getText()));
WriteToFile(String.valueOf(getDate()));
Random rnd1=new Random();
Registration_Number=rnd1.nextInt(100);
setRegNum(Registration_Number);
WriteToFile(String.valueOf(getRegNum()));
jLabel6.setText(String.valueOf(getRegNum()));
}
catch(Exception e){
jLabel6.setText("Error!");
}
}
if(havedigit(getFName())==true) {
System.exit(1);
}
setLName(jTextField2.getText());
if(havedigit(lastName)==true) {
System.exit(1);
}
should be
if(havedigit(getFName())) {
JOptionPane.showMessageDialog(.....);
return; //get out of method, no need to continue
}
setLName(jTextField2.getText());
if(havedigit(lastName)) {
JOptionPane.showMessageDialog(.....);
return; //get out of method, no need to continue
}
Search on Google about how to use JOptionPane.showMessageDialog.
In your if statements, instead of
System.exit(1);
You should have something
throw new MyException("Error Text");
and then your catch should look like this:
catch(MyException e){
jLabel6.setText(e.getMessage());
}
where MyException extends Exception.
Sometimes the doInBackgorund() method of my SwingWorker seems not to be executed, it goes directly to the done() method without saving or printing anything on some of my clients machines, so i suppose it's a random thing , and i can't figure out why. Here 's my code :
public class saveCmdWorker extends SwingWorker<Integer, Integer> {
Order ord;
public saveCmdWorker(Order ord) {
this.ord = ord;
}
#Override
public Integer doInBackground() {
if(999 != ord.getCaissier().getIdCaissier())
saveCmd(ord); // database queries
else
JOptionPane.showMessageDialog(null,"Error",JOptionPane.WARNING_MESSAGE);
if(ord.isIsProd() == false){
try {
// print via serial port
Printer.print(ord, false, Restaurant.numCaisse);
} catch (Exception ex) {
PosO2.errorLogger.log(Level.SEVERE, "Printing error", ex);
}
}
try {
Printer.printFacture(ord, false);
if(btnDuplicata.getForeground() == Color.red)
Printer.printFacture(ord, true);
} catch (Exception ex) {
PosO2.errorLogger.log(Level.SEVERE, "Printing error", ex);
}
return 1;
}
#Override
protected void done() {
try {
btnDuplicata.setForeground(Color.black);
ARendre = 0.0;
ord.clear();
for (int j = 0; j < tab_paiement.size(); j++) {
tab_paiement.get(j).setVisible(true);
}
montantRestant.setBackground(Color.red);
} catch(Exception e) {
PosO2.errorLogger.log(Level.SEVERE, "Refresh Error", e);
}
}
}
I execute this worker via this actionlistener :
ActionListener encaissListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
worker = new saveCmdWorker(cmd);
worker.execute();
}
};
I don't have any logs available so i assume no exception is caught. I saw that a JOptionPane was fired in the doInBackground()(consider as ui modification in an other thread?) but the problem exists when the application doesn't go in the else statement. Can this be the cause of my problems? I don't have this bug on my computer, it just works fine.
As per the SwingWorker documentation (http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html#execute()):
SwingWorker is only designed to be executed once. Executing a SwingWorker more than once will not result in invoking the doInBackground method twice.
So, it looks like you need to create a new instance of your subclass each time you want to run the execute method properly.
**** Please note that my question is regarding the answers in another thread. However, when I posted the question in that thread, it was deleted. So I'm reposting the question here (with a link to the exact post that I'm referring to). ****
I have a couple of questions that go along with this thread. If I have a Timer (updateTimer), which I want to cancel when the window is closing, can I put that in place of the System.out.println("Windows Closing"); statement? Or would I have to put it in the actual "View" class (I have three classes DesktopApplication.App, DesktopApplication.View, and DesktopApplication.AboutBox and the configure Window method is in the .App class).
Along that line, if I can put the updateTimer.cancel(); line in, then does this mean I can read/write from a file, and popluate textboxes also (WindowOpen event) and write the information to the file in the closing event?
What I want to do is the following: When my application starts (and the main window opens) I want to check for a configuration file. If it exists, then I want to get the username, password, tunnel ID, and IP Address from that file--and populate their respective text boxes in the main jPanel. If it doesn't exist, then I won't do anything with it.
On closing the application, I want two things to happen: 1) any UpdateTimers that are running will be cancelled (to effectively and cleanly close the application) and 2) write the username, password, tunnel ID and IP Address to the configuration file for the next run.
I've created the file in Netbeans, so the "exitMenu" is automatically generated, and there is no "close button" configured. So I need to use WindowClosing to accomplish this (or hack the "exitMenu" method in a text editor and hope it doesn't create issues with Netbeans).
I should also add that the username and password are actually MD5 hashes of the real username and password. So, while someone can possibly open the text file and read them, they'll only see something like this:
c28de38997efb893872d893982ac
3289ab83ce8f398289d938999cab
12345
192.168.2.2
Thanks, and have a great day:)
Patrick.
Edited to include information about the "Username and Password" that will be stored.
can I put that in place of the System.out.println("Windows Closing"); statement?
Yes, you can put arbitrary code in your listener
Along that line, if I can put the updateTimer.cancel(); line in, then does this mean I can read/write from a file, and popluate textboxes also (WindowOpen event) and write the information to the file in the closing event?
Yes
How I ended up accomplishing this is like this.
In my "TunnelbrokerUpdateView" class (the one that actually handles the main frame), I added the following code:
WindowListener wl = new WindowListener(){
public void windowOpened(WindowEvent e)
{
try
{
FileReader fr = new FileReader (new File("userinfo.txt"));
BufferedReader br = new BufferedReader (fr);
jTextField1.setText(br.readLine());
jPasswordField1.setText(br.readLine());
jTextField2.setText(br.readLine());
oldIPAddress = br.readLine();
br.close();
}
catch (FileNotFoundException ex) {
// Pop up a dialog box explaining that this information will be saved
// and propogated in the future.. "First time running this?"
int result = JOptionPane.showConfirmDialog((Component)
null, "After you enter your user information, this box will no longer show.", "First Run", JOptionPane.DEFAULT_OPTION);
}
catch (java.io.IOException ea)
{
Logger.getLogger(TunnelbrokerUpdateView.class.getName()).log(Level.SEVERE, null, ea);
}
}
public void windowClosing(WindowEvent e) {
updateTimer.cancel();
BufferedWriter userData;
//Handle saving the user information to a file "userinfo.txt"
try
{
userData = new BufferedWriter(new FileWriter("userinfo.txt"));
StringBuffer sb = new StringBuffer();
sb.append(jTextField1.getText());
sb.append(System.getProperty("line.separator"));
sb.append(jPasswordField1.getText());
sb.append(System.getProperty("line.separator"));
sb.append(jTextField2.getText());
sb.append(System.getProperty("line.separator"));
sb.append(oldIPAddress);
userData.write(sb.toString());
userData.close();
}
catch (java.io.IOException ex)
{
Logger.getLogger(TunnelbrokerUpdateView.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void windowClosed(WindowEvent e) {
System.exit(0);
}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
};
super.getFrame().addWindowListener(wl);
}
I added this into the "public TunnelbrokerUpdateView(SingleFrameApplication app)" method. So, everything works as I wanted it to. I'm sure there are better ways of incorporating the user information, but this was quick and dirty. In the future, I do plan on encrypting the data (or making it into a format that isn't readable normally), since there's a password hash involved.
Hopefully this will help someone else in the future.
(for reference, here's the entire method (including the stuff that Netbeans automatically puts in)
public TunnelbrokerUpdateView(SingleFrameApplication app) {
super(app);
initComponents();
// status bar initialization - message timeout, idle icon and busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName)) {
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
} else if ("done".equals(propertyName)) {
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
} else if ("message".equals(propertyName)) {
String text = (String)(evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
} else if ("progress".equals(propertyName)) {
int value = (Integer)(evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
// This will take care of Opening and Closing
WindowListener wl = new WindowListener(){
public void windowOpened(WindowEvent e)
{
try
{
FileReader fr = new FileReader (new File("userinfo.txt"));
BufferedReader br = new BufferedReader (fr);
jTextField1.setText(br.readLine());
jPasswordField1.setText(br.readLine());
jTextField2.setText(br.readLine());
oldIPAddress = br.readLine();
br.close();
}
catch (FileNotFoundException ex) {
// Pop up a dialog box explaining that this information will be saved
// and propogated in the future.. "First time running this?"
int result = JOptionPane.showConfirmDialog((Component)
null, "After you enter your user information, this box will no longer show.", "First Run", JOptionPane.DEFAULT_OPTION);
}
catch (java.io.IOException ea)
{
Logger.getLogger(TunnelbrokerUpdateView.class.getName()).log(Level.SEVERE, null, ea);
}
}
public void windowClosing(WindowEvent e) {
updateTimer.cancel();
BufferedWriter userData;
//Handle saving the user information to a file "userinfo.txt"
try
{
userData = new BufferedWriter(new FileWriter("userinfo.txt"));
StringBuffer sb = new StringBuffer();
sb.append(jTextField1.getText());
sb.append(System.getProperty("line.separator"));
sb.append(jPasswordField1.getText());
sb.append(System.getProperty("line.separator"));
sb.append(jTextField2.getText());
sb.append(System.getProperty("line.separator"));
sb.append(oldIPAddress);
userData.write(sb.toString());
userData.close();
}
catch (java.io.IOException ex)
{
Logger.getLogger(TunnelbrokerUpdateView.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void windowClosed(WindowEvent e) {
System.exit(0);
}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
};
super.getFrame().addWindowListener(wl);
}
Have a great day:)
Patrick.