Ok guys here is the deal, I am trying to populate a JList's rows using a JtextArea that contains a string value, but when I run my program all that is shown in the JList's rows are the JTextArea's properties(?) instead of the string I am passing. So, can you please take a look at my code and point out what i am missing?
Here is the Code:
public void DoConnect() {
try{
String host="jdbc:derby://localhost:1527/Project";
String username="Adminn";
String pass="password";
Connection con = DriverManager.getConnection( host, username, pass );
System.out.println("connected");
Statement stmt = con.createStatement( );
String SQL = "SELECT * FROM TEAMS";
ResultSet rs=stmt.executeQuery(SQL);
while(rs.next()){
String s = rs.getString("NAME");
JTextArea ta = new JTextArea();
ta.setText(s);
listModel.addElement(ta);
}
jList1.setModel(listModel);
jButton1.addActionListener ((ActionEvent e) -> {
listModel.removeAllElements();
DoConnect();
});
}
catch ( SQLException err ){
System.out.println( err.getMessage( ) );
}
}
And here is the output I am getting:
The default renderer of a JList simply displays the toString() implementation of the object that you add to the model.
Don't add a JTextArea to the ListModel. Add the String to the ListModel
Also, why are you using "select * from Teams" when you only want a single column of data. Be more explicit with your SQL and make the query more efficient.
Edit:
Because the string I am trying to display has multiple lines.
Then you need to create a custom renderer and use the JTextArea as the renderer. In any case you would only ever add the String text to the ListModel. Read the section from the Swing tutorial on Writing a Custom Renderer.
Or a second option is to display the text as HTML. A JLabel will render the HTML in multiple line:
listModel.addElement("<html>1<br>2<br>3<br></html>");
I believe you need JTable and not JTextArea for that purpose, correct me if i'm wrong.
For example, check this image
If you want to go with the JTable solution, there is a library called rs2xml.jar which makes your life easier to populate JTable with the data you wanted.
Usage:
Statement stmt = con.createStatement();
String SQL = "SELECT * FROM TEAMS";
ResultSet rs = stmt.executeQuery(SQL);
table.setModel(DbUtils.resultSetToTableModel(rs)); //this line requires the rs2xml.jar
Credits to: http://learnerarena.com for the picture.
Sorry, i could not comment due to low reputation.
Related
I have a problem with this for a while. Importing data from TEXT field into textArea make no problem for me (even if it's longer than String), but I have no idea how to make it work opposite way. (Using sqlite)
My code to get data from db:
Statement myStmt = con.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT * from test");
while(myRs.next())
{
if(myRs.getInt("Id_przepisu") == przepis.getId_przepisu() )
{
textArea.setText(myRs.getString("text"));
}
}
myStmt.close();
myRs.close();
code to save data in db
insert = con.prepareStatement
( "INSERT INTO test (Id_przepisu, text) VALUES ('"+przepis.getId_przepisu()+"','"+
textArea.getText()+"')");
insert.executeUpdate();
You might find a good answer and workaround for you problem here: https://stackoverflow.com/a/17785119/575643
In short, if is bigger than the TEXT type you would need to split it manually. Search for substring, it would help.
I wanted to create an update button for a dropdown list that gets the data from the database in the netbeans. Tried this method below but couldn't get it to work. Any suggestions? Thanks alot.
public class ViewProduct extends javax.swing.JFrame {
ResultSet rs;
PreparedStatement pst;
Connection conn;
final void FillList(){
try{
//establish connection to table
String url = "jdbc:derby://localhost:1527/ProductInformation";
String username = "admin1";
String password = "admin1";
Connection conn = DriverManager.getConnection(url,username,password);
Statement stat = conn.createStatement();
// get data from table in sql database
String Query = "SELECT * FROM VIEWPRODUCT";
ResultSet rs = stat.executeQuery(Query);
//
DefaultListModel DLM = new DefaultListModel();
while(rs.next()){
JList list = new JList();
JComboBox ProductID_dropdown = new JComboBox();
DefaultComboBoxModel listModel = new DefaultComboBoxModel();
list.setModel(listModel);
ProductID_dropdown.setModel(listModel);
}
}catch(SQLException ex){
JOptionPane.showMessageDialog(null, ex.toString());
}
There are several things not right or missing in your code. For instance you have no GUI.
And as I dont know the exact structure of your project or your database, I have to improvise and give you a pseudo-code approach.
You will have to change and configure several things I am showing here.
First, create a JComboBox outside of your method and add it to a container like JPanel:
JPanel pane = new JPanel();
JComboBox productID_dropdown = new JComboBox();
JButton btn_updateViewProducts = new JButton("Update Results");
Here the Button for updating your results is added, it contains an ActionListener, that "listens" to when someone is clicking on the button.
Usually you want to retrieve a ResultSet and put its contents into variables, like in this example:
// ActionListener for the button
btn_updateViewProducts.add(new ActionListener{
#Override
// When the button is clicked...
public void actionPerformed(ActionEvent arg0) {
// ... get the results out of your database (here it's an example database!
// Configure for your own one)
ResultSet rs = stat.executeQuery(Query);
while(rs.next()){
// "de-construct" every result of the ResultList into variables
String query = "select COF_NAME, SUP_ID, PRICE, " + "SALES, TOTAL " + "from " + dbName + ".COFFEES";
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "\t" + supplierID + "\t" + price + "\t" + sales + "\t" + total);
// Put items into JComboBox
productID_dropdown.addItem(coffeeName);
}
}
});
// Add the now filled JComboBox to the pane
pane.add(productID_dropdown);
Other issues you should think about:
GUI is missing
the method FillList is final, which seems unusual, any reason behind this? final in a method means, that it cant be overridden by subclasses, it this needed here?
FillList is a method and should be written with a small letter at the start due to coding convention, the same goes for ProductID_dropdown (coding convention)
most of the time it's quite okay to use short variables like rs for a ResultSet, but if your projects get bigger, it gets harder to keep all those variables in mind. Better: make them tell you, what they are. Instead of rs -> resultSetViewProduct or similar.
PreparedStatement pst is never used
I hope this helps. :)
so what I am trying to do is update a JLabel that is going to represent the number of files that are stored in my database.
I will use JDBC to communicate my Java application with my database (Oracle) and pass a SQL statement to my database to return output in this case it will be: SELECT COUNT(File_ID) FROM Files; which would give an output of say 50.
So now I would like to update my Jlabel I have to display the output, in this case it would read 50.
I know how to update a JTable with the results from a database like so:
try {
String query = "SQL STATEMENT GOES HERE";
pat = conn.prepareStatement(query);
rs = pat.executeQuery();
myTable.setModel(DbUtils.resultSetToTableModel(rs));
}catch (Exception e) {
e.printStackTrace();
}
However I have never used output to update a Jlabel, if you have any suggestions or advice on how to achieve this it would be greatly appreciated. Thanks!
Just use label.setText()
Edited: I didn't find an equivalent TextModel for jlabel (it exits for other components such as JTextField). Is it critical for you to go through a "Model" or is it good enough to setText("50")?
To extract the count do something like:
int count=0;
pat = conn.prepareStatement("SELECT COUNT ..."); // complete as required
ResultSet rs=pat.executeQuery();// assuming it's "SELECT COUNT..."
if(rs.next())
count=rs.getInt(1);
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
I've a table in database named customer that have attribute like code and name. I've called the value of the customer in other table and displayed it using combo-box. I've displayed the code in combo-box, and all I wanna do is when I choose the code in combo-box, value 'name' can be displayed in text-field , the 'name' appear based on code.
here is my code :
try {
Connections con = new Connections();
con.setConnections();
String sql = "select * from customer";
Statement stat = con.conn.createStatement();
ResultSet rs=stat.executeQuery(sql);
while (rs.next()){
cmb_custCode.addItem(rs.getString("custCode"));
txt_custName.setText(rs.getString("custName")); // i'm confused in here, how can i call the name based on the code
}
}
catch(Exception e){
e.printStackTrace();
}
}
for example :
when the code 'B0001' is selected in the combobox, the Jtextfield must also display "Bob" , because code B0001 is belongs to Bob.
EDIT:
Ok. So let's say that you have a user Bob and his code is B001.
ItemStateChanged Method
...
String code = (String) cmb.getSelectedItem();
try{
String sql = "SELECT * FROM customer WHERE code='"+code"'"
PreparedStatement prst = con.prepareStatement();
ResultSet rs = prst.executeQuery(sql);
String name = "";
while(rs.next()){
name = rs.getString('name');
}
txt.setText(name);
}catch(Exception ex){
}
You shouldn't actually connect inside the itemStateChanged but this is just an example.
Take a look at this article. It tells you everything you need to know on how to use combo boxes.
http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html
In your own example code, you can declare the enclosing class as an ActionListener. then use the following after declaring your cmb_custCode
...
cmb_custCode.addActionListender(this);
...
when implementing an ActionListener, you have to implement the method actionPerformed(). I've cribbed the following from : http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#listeners but adapted to your code
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String custCode = (String)cb.getSelectedItem();
updateLabel(custCode);
}
I've maintained the encapsulation of updateLabel(String custCode) from the example on the trail. You can assume that that method is defined as something like :
private void updateLabel(String code) {
txt_custName.setText(map_cust.get(code));
}
I've brough a Map into it with map_cust. It's just a map between code and name, stored in a field
Map<String, String> map_cust = new HashMap<String, String>();
and populated it, this would go in your code, just after retrieving the ResultSet
...
cmb_custCode.addItem(rs.getString("custCode"));
map_cust.put(rs.getString("custCode"), rs.getString("custName");
So, when you get your result set, you populate a map and your combo box, when the client picks and item from the combo box, he fires and actionPerformed, into the registered listener, where the event is manipulated to get the selected item, the String of which is the key to the map_cust, containing mapped key, value pairs, custCode mapped to custName. When that name is pulled from the map, it may be used to update the text of the label.
Here is my code, and it solved my problem. Hope it's useful for you too :).
private void fillText(){
String code = (String) cmb_custCode.getSelectedItem();
try {
Connections con = new Connections();
con.setConnections();
String sql = "select * from customer WHERE custCode='"+code +"'";
Statement stat = con.conn.createStatement();
ResultSet rs=stat.executeQuery(sql);
while (rs.next()){
txt_custName.setText(rs.getString("custName"));
}
}
catch(Exception e){
e.printStackTrace();
}