Hi, I'm an -extreme- newbie, please be merciful and kind to me. ;)
ServerData() is kept in a separate file. I dunno... I'm trying to create an event exactly the way it looks in my course book but for some reason it stops at:
System.out.println("Getting source from Button");
If I keep clicking the button it keeps showing that printout, so surely it's not hanging, but it's not actually starting the server. The server used to work before I started trying to make a button that starts it so I don't think it's the server self?
Some help would really really be appreciated. Thank you for your time. Sorry if I'm wasting your time with a silly question, it's like I said... I'm -very- new. Lol.
Hi Tessa, welcome to the Ranch!
Could you please UseCodeTags next time? I've added them for you this time, and see how much easier it is to read your code.
In the mouseClicked event handler you declare two new variables called button1 and button2. These are initialized to be null, and never get any value. These are most definitely not your actual buttons. Two suggestions:
- move the declaration of your button1 and button2 JButtons to your class, making them instance fields. The initialization stays in the constructor.
- switch from using a MouseListener to an ActionListener instead. Buttons use ActionListener, not MouseListener.
The improved code (minus the Session and SessionData):
As said in comments, MouseEvent.getButton() returns an indication for the mouse's button. This is an int that is equal to MouseEvent.NOBUTTON, MouseEvent.BUTTON1, MouseEvent.BUTTON2 or MouseEvent.BUTTON3. By assigning it to an Object reference you were auto-boxing it into an Integer. EventObject, the root of all event objects like MouseEvent and ActionEvent, has a method called getSource() that returns the object that triggered the event. In this case, it's the button you clicked.
Well, yeah. Your code says "Whenever the mouse is clicked, execute this code". And the code includes displaying that message. So yeah, every time you click the mouse that message will be displayed. But that doesn't mean that processing stops there. It continues on with the rest of the code in that method.
If you aren't seeing any other output after that message, that simply means that the code which could display other output isn't being executed. This is entirely possible, since the other output-writing statements are inside an if-statement.
Joined: Oct 12, 2010
Thank you very much, Rob! That was EXTREMELY helpful, everything is working now the way it should.