Currently using Swing to create a GUI, for a login system. I retrieve a couple things from the database, one is a String named Username, and one is a int, named points. I have a class, where I have all my getters and setters in, which is called DBHandler. Upon retrieving these values, I use:
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
When I set these values (points is set inside the DBHandler.login method) using:
public login(){
DBHandler db = new DBHandler();
db.setUsername(usernameTemp.getText());
db.login();
}
However, when in another JFrame, that I call the instance of DBHandler, all values seem to be null. I use the getters to retrieve the values, but they are always empty.
public StudentScreen() {
DBHandler db = new DBHandler();
initComponents();
showUser.setText(db.getUsername());
showScore.setText("" + db.getPoints());
}
I know this is a fairly simple problem, but I just haven't been able to get past this. I've checked a couple posts, but nothing helped understanding this issue.
Best Regards
Inside StudentScreen you are creating a new instance of DBHandler which has all its values set to their default values. You have to use the same instance everywhere. You either achieve this with a singleton pattern or by just passing the DBHandler as a parameter to the constructor of StudentScreen
Related
So I am creating a chat app for android and I'm using Java and I need some help wrapping my head around some things. Whenever the user first registers, I am creating a new object of a class named User. When they enter the next layout, I need to access that objects data.
public class User {
public String username;
public User() {}
public User(String username) {
this.username = username;
}
public String getUsername(){
return username;
}
}
This is my User class. When they send a message, I need to be able to grab their username from this User object from an entirely different method without passing the object through a parameter. I can't seem to wrap my head around how to access their information and none of my methods seem to work. Any help is appreciated
If you do
User myUser = new User();
the variable myUser contains a reference to the newly created object. You must keep this reference around in order to later access the object. How exactly you do this depends on the logic of your program. Sometimes you would keep it in a field of another object or pass it around as parameter. For example
un = myUser.getUsername();
or
void myMethod(User theUser) {
...
String un = theUser.getUsername();
}
...
// call the method passing the user reference
myMethod(myUser);
in the main class make the data object... static
public static Model obj;
obj= new Model();
then from other class access it with your class name
example
main.obj;
I solved this issue by just using SharedPreferences. I stored the username associated with the key of each user. This way, I can always search the username for each user.
I want to make a class that can interact with a database, which has the following desired functionality:
It has a method to return all fields from the database, later can be changed such that it can also limit with it returns.
It has a method to insert a specific instance of this class.
It has a method to update a specific instance of this class.
I will show the code in a moment after further explanation.
Now I want to extract an interface, or rather an abstract class I think might be more appriopiate, to be sure that all classes/datafields follow the same 'interface', and to be able to use them as a supertype in Lists etc.
The data class, in this case Account.java, should represent a table in a database which stores {Username, Password}, I am omitting an explicite unique identifier for now, still not sure if I will make an additional ID field or use the uniqueness of the Username field.
It would be best if the abstract class itself would handle all the MySQL interaction 'mess'.
Account.java so far:
package testthing;
import java.util.Map;
/**
*
* #author Frank
*/
public class Account {
private final static String ALL_QUERY = "SELECT * FROM accounts";
private final static String INSERT_QUERY = "INSERT INTO accounts (username, password) VALUES(?, ?)";
private final static String UPDATE_QUERY = "UPDATE accounts SET password=? WHERE username=?";
private String username;
private String password;
public Account(final String username, final String password) {
this.username = username;
this.password= password;
}
public String getUsername() {
return username;
}
public void setUsername(final String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(final String password) {
this.password = password;
}
public static Map<String, Account> getAll() {
//return a map using the ALL_QUERY string
}
public void insert() {
//insert this using INSERT_QUERY
}
public void update() {
//update this using UPDATE_QUERY
}
}
I know that I haven't been that clear I'm afraid, but I hope this is enough to help me get going.
Basically I want to always be able to use the followings methods when working with a TableObject, which Account would be a subset of:
Account.getAll();
new Account("test", "test").insert();
currentAccount.setPassword("newPassword"); currentAccount.update();
All the nasty SQL stuff should be hidden inside the proposed abstract class. The only thing you cannot escape in a TableObject class is the definition of the SQL queries.
Regards.
EDIT: In current example Account.getAll() returns a Map<String, Account>, but in reality the first generic argument should be the type of the key in the database. So if you would use an unique ID then it would need to return a Map<Integer, Account>. I hope this change makes it in time for people to read it.
Is it not more logical, to have the connection code and all the "nasty" stuff in the superclass, but simply have a more general method in the superclass, that is used by it's sub classes. For example:
public void executeUpdate(String query)
{
// Code to execute update.
}
public Map<String, Data> getData(String query)
{
// Code to get data.
return data;
}
This way, these methods are more general. It means that you can implement several classes that simply pass query data, rather than constantly having to update a superclass every single time you want to add new functionality.
Obviously I've just assumed a type Data here, but that might be something to look into. The aim here is to decouple your classes as much as possible. This means you can add as many new classes as you want, and they can use their supertype without hinderence.
This also means things like
Account.getAll();
is a little less complicated, because if you have getAll in your superclass, where is the reference that you want to get all accounts? If the code is actually in the Account class, you can customize the query, and send it off to the getData method to be executed.
We are working on a multi process projects which use RMI for RPCs.
The problem that we are facing is that the main object which must be passed between processes is very big (when serialized), and this dropped the performance of the code dramatically.
Since, none of the processes change the whole object and only alter small parts of it, we decided to just pass "the modifications" through RMI.
but I found no proper way to implement such concept. The first idea was to keep track of all changes of the main instance. But this seems not easy according to this.
I need a way which we can:
develop fast
performs fast
any suggestion?
Just make this 'main object' a remote object that implements a remote interface, and export it, instead of serializing it backwards and forwards.
I think the best way is to customize your serialization so you will be able to send only the changes. you can do it by implementing private method of
private void writeObject(java.io.ObjectOutputStream stream) and of course also readObject from the other side. well, what you should do in this functions?
I suggest you will manage a bitmap of all the members that were changed and only send them in the serialization, just change the unchanged members to null send the object in serialization and than return there values. in the other side read the bitmap and than you will know how to
First time you need to pass the whole object.
Use PropertyChangeListener on the object, this would generate an PropertyChangeEvent.
You can pass the PropertyChangeEvent around. It has the getSource(), by which you can identify the object. If this is not enough, if you need IOR or any other sort of reference, create a wrapper and sent it across..
-Maddy
Have a look to http://docs.oracle.com/javase/tutorial/uiswing/events/propertychangelistener.html
public class Test {
PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
String oldName = this.name;
this.name = name;
pcs.firePropertyChange("name", oldName, name);
}
public int getAge() {
return age;
}
public void setAge(int age) {
int oldAge = this.age;
this.age = age;
pcs.firePropertyChange("age", oldAge, age);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcs.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcs.removePropertyChangeListener(listener);
}
public Test(){
}
public static void main (String[] args){
Test myTestObject = new Test();
myTestObject.addPropertyChangeListener(new MyPropertyChangeListener());
myTestObject.setAge(12);
myTestObject.setName("Rick");
myTestObject.setName("Andrew");
}
private static class MyPropertyChangeListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent event) {
String clazz = event.getSource().getClass().getName();
System.out.println(clazz+"::"+event.getPropertyName()+" changed from "+event.getOldValue()+" to "+event.getNewValue());
}
}
}
This is a simple example but using this approach you can create different PropertyChangeListeners and provide different logic inside theirs method propertyChange.
Also is possible to fire only the changes over a small set of attributes and not over all of them (not storing the oldValue and not firing the firePropertyChange method of PropertyChangeSupport).
Of course that you can use AOP, but perhaps you are looking for a solution like presented above. I hope this helps.
I'm using Metawidget to automatically see/edit values in objects in the GUI. I'm able to bind the object's initial values, and see them in their respective GUI components. However, when I change the values in the GUI, these changes are not sync'ed back to the object. This is more or less documented here (deprecated) and here.
Here is my business object:
public static class Person {
private String mName;
public String getName() { return this.mName; }
public void setName( String name ) { this.mName = name; }
#UiAction
public void showPersonObject() {
JOptionPane.showMessageDialog(frame, this.mName);
}
#UiAction
public void bind() {
metawidget.getWidgetProcessor(
BeansBindingProcessor.class)
.save( metawidget );
}
}
Here is my main method, where metawidget is configured:
public static void main( String[] args ) {
// Person
Person person = new Person();
person.setName("A cool name");
// Metawidget
metawidget = new SwingMetawidget();
metawidget.setInspector( new CompositeInspector(
new CompositeInspectorConfig().setInspectors(
new PropertyTypeInspector(),
new MetawidgetAnnotationInspector(),
new BeanValidationInspector())));
metawidget.addWidgetProcessor(
new BeansBindingProcessor(
new BeansBindingProcessorConfig().setUpdateStrategy(
UpdateStrategy.READ_WRITE )) );
metawidget.setToInspect( person );
// Create Frame
...
}
In the documentation it is said that:
If set to READ or READ_WRITE (the default is READ_ONCE), the object
being inspected must provide PropertyChangeSupport. If set to
READ_WRITE, updates to the UI are automatically sync'ed back to the
setToInspect, otherwise the client must manually call save:
myMetawidget.getWidgetProcessor( BeansBindingProcessor.class ).save( myMetawidget )
I've tried setting the UpdateStrategy to READ and/or READ_WRITE, and/or calling save() on BeansBindingProcessor. I've also tried to provide PropertyChangeSupport to the Person object (I think its refering to this), which is the same as adding the following code:
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
public void addPropertyChangeListener(PropertyChangeListener listener) {
this.pcs.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
this.pcs.removePropertyChangeListener(listener);
}
public void setName( String name ) {
String oldName = this.mName;
this.mName = name;
this.pcs.firePropertyChange("name", oldName, mName);
}
However, the Person object always maintains the original values.
Thanks in advance.
Well, I solved the problem. There is a "rogue" version of beansbinding.jar on the internet, that's why binding wasn't working. I used the version distributed with Metawidget examples, and now everything works fine.
This problem is reported here.
Sorry for the confusion regarding the 'rogue' version of BeansBinding. I have updated the Metawidget documentation to save frustration for others in future.
I have two JFrames login.java and account.java
I need to get the username from the login.java page and put it in a variable in the account.java JFrame. How can I do this in the Java NetBeans using the Swing?
Instead of Using JFrames for passing values between different forms you can use CardLayout which will persist your data which you have entered in the previous form.
All you have to do is Create a JFrameForm and add panels to it.
You can use getter and setter methods...
Set the username in a setter. And using object of login.java use it in account.java through getter...
public class login {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = this.usernameTextField.getText();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = this.passwordTextField.getText();
}
}
Using objects of login.java access getPassword(), getUsername() in account.java.
you need to pass object of login.java to account.java first...
Since you have asked how to pass a variable value from one JFrame to Another JFrame (using swing). So for this put one textbox(tx) and a button(jButton3) in login.java and one label(lx) in account.java where we will print the value of the textbox from login.java .
Type this in login.java :-
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String msg= tx.getText();
new NewJFrame2(msg).setVisible(true);
}
Then overload constructor in account.java :-
public NewJFrame2(String abc ){
initComponents();
lx.setText(abc);
}
Well you have very nice way to do it.
Define new Static Final Objects of that class.
and Save that value into the Object.
and in other Class u can easily use that objects and as well as that values.
By using
CLASSNAME.OBJECT VALUE.
use that.
The 100% working solution. Suppose u r calling welcome.java
Account ac= new Account(new JFrame(), true);
After this line call a method of welcome.java which u have to create like:
wc.setUser(username);
For account.java
create a method:void setUser(String username) {
user1 = user;
cname.setText(user1);
}
User1 is global variable and available for all which u have to define lke:
String user1;
after it is assigning the username value to user1. here cname is a label which name is cname; so, we are seeting the text of cname to the user.