How can I convert string to label in javafx? - java

In my project, a have a bunch of labels for some purpose. Since I am able to move them on stackpane using drag, I want to be able to save their new location in my app. So I was thinking about database, with columns for X and Y position, name of the label and its text.
However, since i want to use quite a lot of labels, I didn't want to code load of labels from database one by one, so I used this:
private void button_load(ActionEvent event) {
try{
String host = "jdbc:sqlite:C://app/app.sqlite";
Connection con = DriverManager.getConnection(host);
PreparedStatement pst = null;
String SQL = "select * from labels";
pst=con.prepareStatement(SQL);
ResultSet rs=pst.executeQuery();
while(rs.next()){
String name=rs.getString("Name");
Double Y=rs.getDouble("Y");
Double X=rs.getDouble("X");
String Text=rs.getString("Text");
name.setLayoutX(X);
name.setLayoutX(Y);
name.setText(Text);
}}
catch (SQLException ex)
{ Logger.getLogger(app.class.getName()).log(Level.SEVERE, null, ex);}}
Obvious problem is, that I am not allowed to use content of the string ("name" in this case) for further use as label ("string cannot be converted to label"). I have been searching for some solution, but haven't found any.
So I would like to ask, is there a way, how to convert string to label or any other way that would help be in this situation?
Thanks

You need to create a new Label for each record and add it to your pane:
private Pane pane = ... // Or group or some other form of a container
private void button_load(ActionEvent event) {
try{
String host = "jdbc:sqlite:C://app/app.sqlite";
Connection con = DriverManager.getConnection(host);
PreparedStatement pst = null;
String SQL = "select * from labels";
pst=con.prepareStatement(SQL);
ResultSet rs=pst.executeQuery();
while(rs.next()){
Label label = new Label();
String name=rs.getString("Name");
Double Y=rs.getDouble("Y");
Double X=rs.getDouble("X");
String Text=rs.getString("Text");
label.setLayoutX(X);
label.setLayoutX(Y);
label.setText(Text);
label.setId(name);
pane.getChildren().add(label);
}
} catch (SQLException ex){
Logger.getLogger(app.class.getName()).log(Level.SEVERE, null, ex);
}
}
I am not sure what you store under name, my guess is that it could be the id of the node.

Related

Java-Output all the columns and rows of a ResultSet

ta.setText is a TextArea where I want to show all my data from the database, after a button click. But with rs.get("name") I just output one value and it is always the last. How can I print out the whole table from the database, so all the information which are stored there?
try { String newquery = "SELECT * FROM kunden";
java.sql.PreparedStatement ps = con.prepareStatement(newquery);
rs = ps.executeQuery(newquery);
while (rs.next()){
ta.setText(rs.getString("name"));
ta.setText(rs.getString("nachname"));
}
}// try
catch(Exception e1) {
JOptionPane.showMessageDialog(null, "fail");
}
}//actionperformed
Either you build a string an then set that string using setText()
StringBuilder builder = new StringBuilder();
while (rs.next()) {
builder.append(rs.getString(“name”));
builder.append(“ “);
builder.append(rs.getString(“nachname”));
builder.append(“\n“);
}
ta.setText(builder.toString());
Or you use the append method that exists for TextArea
while (rs.next()) {
ta.append(rs.getString(“name”));
ta.append(“ “);
ta.append(rs.getString(“nachname”));
ta.append(“\n“);
}

Retrieving image in a jtable

I wrote a program in java to retrieve images and text data from a table. Everything is right, only when i try to retrieve an image(Blob) from the table, i get an exhausted result set error.I tried google it, but the explanation was fa too condensed. Can anyone help me with this? I will appreciate a nice explanation.
Here is the code
try {
Class.forName(classforname);
Connection con = DriverManager.getConnection(Connectionurl, username, password);
String sql = "Select * from teacherdata where teachername='" + tf1.getText() + "'";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery(sql);
rs.next();
String thename = rs.getString("teachername");
String sub1, sub2, sub3, sub4;
sub1 = rs.getString("sub1");
sub2 = rs.getString("sub2");
sub3 = rs.getString("sub3");
sub4 = rs.getString("sub4");
String sql2 = "select tid,tpic from teacherimages where teachername='" + tf1.getText() + "'";
PreparedStatement ps2 = con.prepareStatement(sql2);
ResultSet rs2 = ps2.executeQuery(sql2);
rs2.next();
String Tid = rs2.getString("tid");
Blob b = rs.getBlob("tpic");
byte barr
[] = new byte[(int) b.length()]; //an array is created but contains no data
barr = b.getBytes(3, (int) b.length());
Image im = jInternalFrame1.getToolkit().createImage(barr);
ImageIcon icon = new ImageIcon(im);
JLabel label = new JLabel(icon);
Object[] row = {
thename,
sub1,
sub2,
sub3,
sub4,
b,
Tid,
icon
};
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(row);
jTable1.setVisible(true);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(SearchBox.class.getName()).log(Level.SEVERE, null, ex);
}
You are not checking the return value of next on the ResultSet.
Please consider changing your code to
if(result.next()){
// the logic
}
EDIT
Further on the code change , please check that your tables are not empty. If your tables are empty you will not return values.
The error Exhausted Resultset set occurs when you attempt to access the result set after iterating or not checking if the result set returns data
while (resultSet.next()) {
//result set logic
}
//
resultset.getString[1] //<- will throw error Exhausted Resultset

Make a List from a DB varchar data - NetBeans + Derby

my problems is that i dont know how to make a list (Jlist from NetBeans) with some data from my derby db
EX:
I have a form that saves the id,name,phone and email from a "client", and i want to show all the names from my previously registered clients in a list, the problem is that i need to convert the varchar data into a listmodel. How can i do that? I tried this, but didn't work:
while (rs.next()){
int id_col = rs.getInt("clientID");
String name = rs.getString("clientName");
client_listClients.setText(name);
}
It says that "couldn't find symbol" for .setText
EDIT using DefaultListModel
WORKING RESULT!
public void DoConnect( ) {
DefaultListModel model = new DefaultListModel();
client_listClients.setModel(model);
try {
String host = "jdbc:derby://localhost:1527/ANAIA_DB";
String uName = "*****";
String uPass = "*****";
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement();
String sql = "SELECT * FROM APP.CLIENT";
rs = stmt.executeQuery(sql);
while (rs.next()){
int id_col = rs.getInt("clientID");
String name = rs.getString("clientName");
model.addElement(name);
}
} catch (SQLException err) {
JOptionPane.showMessageDialog(main.this, err.getMessage());
}
}
Thx aloooot #peeskillet
"It says that "couldant find symbol" for .setText"
JList has no method setText(). When in doubt, read the docs
Instead, you'll want to use a ListModel. If you don't want to create your own, you can use the provided DefaultListModel implementation. There you have the method addElement.
You first need to declare your your list with the model.
DefaultListModel model = new DefaultListModel();
JList client_listClients = new JList(model);
Then you can use the method addElement, which will automatically update the UI after all additions are made. No need to do anything with the list.
while (rs.next()){
String name = rs.getString("clientName");
model.addElement(name);
}
You can see more at How to use Lists, and focus on the section Creating a Model

Displaying datatable from database

I am trying to display data from the database into a datatable and I am getting no results. I tested the queries with JDBC with exact select statement to see if it returns any row, and it always worked. But when I try to have the data from the database into my datatable I get no results. I even made a fake dummy data just to populate my datatable. I must be doing something wrong in the index.xhtml file that I don't know of. What could I doing wrong ? any help would be appreciated ?
edit: first I went to with Primefaces with their datatable example, and than I went with simple jsf style datatable like I have here and neither of those worked when I try to do it with the database
UserDAO.java
public class UserDAO {
private static final String USERNAME = "something";
private static final String PASSWORD = "something";
private static final String CONN_STRING =
"jdbc:sqlserver://petunia.arvixe.com.....something";
public List<Report> getUserList() {
List<Report> list = new ArrayList<Report>();
PreparedStatement ps = null;
Connection con = null;
ResultSet result = null;
try {
con = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
String sql = "SELECT id, tag,asset_name, model, ser_no, value, \n" +
" asset_condition, asset_type FROM assets";
String sql1 = "SELECT name, address, city,state,zip, phone, district FROM location";
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
while (result.next()) {
Report rep = new Report();
rep.setId(result.getInt("id"));
rep.setTag(result.getString("tag"));
rep.setName(result.getString("asset_name"));
rep.setModel(result.getString("model"));
rep.setSerial(result.getString("ser_no"));
rep.setValue(result.getFloat("value"));
rep.setCondition(result.getString("asset_condition"));
rep.setType(result.getString("asset_type"));
rep.setLocationName(result.getString("name"));
rep.setAddress(result.getString("address"));
rep.setCity(result.getString("city"));
rep.setState(result.getString("state"));
rep.setZip(result.getString("zip"));
rep.setPhone(result.getString("phone"));
rep.setDistrict(result.getInt("district"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
}
Well, you are making a report:
Report rep = new Report();
...but not adding it to your list. Add this:
Report rep = new Report();
list.add(rep);
I suppose your problem is this code:
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
You are overwriting your sql statement immediately with the statement sql1.
I think, you probably want to select the assets with THEIR locations. In SQL you can use a JOIN to achieve that.
If you use this syntax
String sql = "SELECT id, tag,asset_name, model, ser_no, value, \n" +
" asset_condition, asset_type FROM assets";
String sql1 = "SELECT name, address, city,state,zip, phone, district FROM location";
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
You will get as a result only the execution of the second query. I think that in your case you are trying to get a result from both tables assets and location so you should use a join between the 2 tables.

Retrieving data based on the ID java

i wanted to retrieve the data from the database with ID.. So, i wanted to do like this: i have number on my combobox 1 to 4. Whenever i select 1 in combobox, the textbox firstname and lastname text will be change based on the selected id. How do i do that?
I already tried like this, but it won't work:
private void Edit(Connection conn, Statement state, ResultSet result)
{
try
{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String url = "jdbc:odbc:Database";
conn = DriverManager.getConnection(url);
String query = "select FirstName, LastName, Status, JoinedDate from Customer where ID = ?";
PreparedStatement statement = conn.prepareStatement(query);
statement.setInt(1, jComboBox1.getSelectedIndex());
result = statement.executeQuery();
while(result.next())
{
jTextField3.setText("FirstName");
jTextField2.setText("LastName");
jTextField3.setText("Status");
JoinedDateLabel.setText("JoinedDate");
}
}
catch (Exception e)
{
System.err.println(e.getMessage());
_sound.PlaySound(2);
_infoBox.ShowMessageBox(e.getMessage(), "Error", 2);
_reminder = new Reminder(1);
JOptionPane.showOptionDialog(null, "Program will be closed due to error!", "Error", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new Object[]{}, null);
System.exit(0);
}
Thank you
Try this
while(result.next())
{
jTextField1.setText(result.getString("FirstName"));
jTextField2.setText(result.getString("LastName"));
jTextField3.setText(result.getString("Status"));
JoinedDateLabel.setText(result.getString("JoinedDate"));
}
All you're doing with your current code is setting the text to the strng literal "FirstName". You need to actually retrieve the data from the ResultSet and set the text as that data.
Also, note JComboBox indices are 0 based. So if you are selecting the first index, it would return 0. You should make sure (in your case) that the db has Id's of 0,1,2,3

Categories