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();
}
Related
I'm developing a cinema Database, using PostgreSQL, and implementing it graphically with Java.
Everything is working fine but this: i have a PreparedStatement used in a method written like this:
getFilmByGenrePS = connection.prepareStatement("SELECT * FROM Film WHERE genre = ?");
public List<Film> getFilmByGenre(String Genre) throws SQLException{
getFilmByGenrePS.setString(1, Genre);
ResultSet rs = getFilmByGenrePS.executeQuery();
List<Film> list = new ArrayList<Film>();
while(rs.next()) {
Film f = new Film(rs.getInt("CodF"));
f.setFilmName(rs.getString("Name"));
f.setGenreFilm(rs.getString(3));
f.setLenght(rs.getInt("lenght"));
f.setCast(rs.getString("castfilm"));
f.setDirector(rs.getString("director"));
f.setDate(rs.getDate("date"));
f.setDateout(rs.getDate("dateout"));
list.add(f);
}
rs.close();
return list;
}
Genre is an ENUM TYPE in pgadmin.
Then, in my GUI, i have a Combobox with every Genre listed in it, written like this:
JComboBox GenrecomboBox2 = new JComboBox();
GenrecomboBox2.setBounds(60, 485, 150, 27);
panelViewFilm.add(GenrecomboBox2);
GenrecomboBox2.addItem("Animation");
GenrecomboBox2.addItem("Adventure");
GenrecomboBox2.addItem("Action");
Then, I have a button that, when pressed, takes my selected Genre from the Combobox, and passes it to the GetAllFilmByGenre() method as a parameter, so it can substitute it to the '?' in the PreparedStatement.
JButton btnViewFilmGenre = new JButton( new AbstractAction("Vai") {
#Override
public void actionPerformed( ActionEvent e ) {
String genreFilm = (String) GenrecomboBox.getSelectedItem();
DefaultTableModel model = (DefaultTableModel) tableViewFilm.getModel();
model.setRowCount(0);
try {
List<Film> listfilm = new ArrayList<>();
listfilm = filmdao.getFilmByGenre(genreFilm);
System.out.println(listfilm);
for (Film f : listfilm) {
Object[] o = new Object[8];
o[0] = f.getCodF();
o[1] = f.getFilmName();
o[2] = f.getDirector();
o[3] = f.getGenreFilm();
o[4] = f.getCast();
o[5] = f.getLenght();
o[6] = f.getDate();
o[7] = f.getDateEnd();
((DefaultTableModel) tableViewFilm.getModel()).addRow(o);
}
} catch (SQLException e1) {
System.out.println("");
}
}
});
Thing is, this does absolutely nothing. Overall, I think the code works. I used exact same versions of these code by retrieving different parameters and it works flawlessly.
Worth noting: the problem is that it doesn't populate my list at all. I tried to print the list after creating it, and nothing shows up. I get no SQLExceptions or anything.
I think the problem is the parameter i pass. Like, the query "SELECT * FROM FILM WHERE Genre = ?" (with ? substituted with, for example, 'Action') gets executed, but simply doesn't find anything that matches, thus giving me nothing. But if I write "SELECT * FROM FILM WHERE Genre = 'Action'", the query works.
I don't know how to resolve this. I used this exact Combobox for inserting values in my Database and it works. I tried for hours. I'm sure I'm slipping on something stupid, maybe the interaction between the String I use as a parameter in substitution of the '?' is wrong on syntax, but i can't get it. Any help?
when i click button , it show one value . Then i click again and it's still the same ,how to click button and it show a new value next ?
try {
String bdUrl = jdbc:sqlserver://127.0.0.1:1433;databaseName=login;user=sa;password=123;"
Connection conn = DriverManager.getConnection(bdUrl);
String sql = "select cauhoi , caul,cau2,cau3,caudung from tracnghiem";
Statement statement = conn.createStatement();
Resultset rs = statement.excuteQuery(sql);
while (rs.next())
{
String cauhoil = rs.getString(1);
String dapana = rs.getString(2);
String dapanb = rs.getString(3);
String dapanc = rs.getString(4);
String dapand = rs.getString(5);
lbl.setText(""+cauhoil);
jrd1.setText(dapana);
jrd2.setText(dapanb);
jrd3.setText(dapanc);
jrd4.setText(dapand);
}}
catch (Exception e)
{
System.out.println(e);
}
It shows the same value because your SQL statement is the same every time it is executed. You will always see the last value in the ResultSet since you keep updating the Swing components inside the loop.
Instead you need to:
create a custom object to store each of the 5 values for each row of data in the database
Then you need to read the data once and inside your while loop you need to create an instance of this object with each of the 5 values.
This object will then be added to an ArrayList
When you click a button you get an object from the ArrayList and display the values in your Swing components.
You then increment an index variable so that then next time you click a button you get the next object from the ArrayList.
I want to get the DAO list values in controller.like my list contain 10 values i want all the 10 values in controller in 10 separate object or variable.`public List getcountrydata() throws Exception {
conn = connectionDB.getConnection();
Statement stmt = conn.createStatement();
List<wrapper> list = new ArrayList<wrapper>();
list.clear();
ResultSet rs1 = stmt.executeQuery("select * from country ORDER BY country_code ASC");
while (rs1.next()) {
wrapper obj1 = new wrapper();
obj1.setCountry_name(rs1.getString("country_name"));
obj1.setCountry_id(rs1.getInt("country_id"));
list.add(obj1);
}
return list;
}`
From the above code I want to get the country_name and country_id in controller in separate variable like,
String country_name=country_name;
int country_id=country_id;
Use Environment.NewLine where you want to need new line after EOL.
Hope that will help you.
If you are trying to show/save the text of the TextBox you need to create a JavaScript function which runs on submit button push, The process of this function is to change every enter key pressed into <br/> this would show as well as save requirement Format.
I have two combo boxes.1 is for main department and other is for sub department. I want to load all the data in Main_department table to combo box. When selecting combo box item i want to load sub_departments relevant to that selected item.
try {
Conn c=new Conn();
Statement s=c.createConn().createStatement();
String query ="SELECT * FROM main_dep";
ResultSet rst = s.executeQuery(query);
DefaultComboBoxModel dc=(DefaultComboBoxModel)maindep.getModel();
while(rst.next()){
dc.addElement(rst.getString(2));
}
} catch (Exception e) {
e.printStackTrace();
}
This is how i got the main Departments. Then i wrote following code for itemStateChange event in main Department combobox.
String main = maindep.getSelectedItem().toString();
Conn c=new Conn();
try {
//Conn c=new Conn();
Statement s=c.createConn().createStatement();
String query ="SELECT Description FROM sub_dep WHERE Main_dep_ID IN (SELECT Main_Dep_Id FROM main_dep WHERE description = '"+main+"')";
ResultSet rst = s.executeQuery(query);
DefaultComboBoxModel dc=(DefaultComboBoxModel)subdep.getModel();
while(rst.next()){
dc.addElement(rst.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
When Main Department is changed sub Departments relevant to that department is loaded to sub Department combobox. But loaded items are Still remaining when another one is selected.
How can i overcome that issue?
But loaded items are Still remaining when another one is selected
You can use:
dc.removeAllElements();
before you start adding new elements to the model.
This case call dependent combo-box.
You have to load data to first combo-box first then, when user select the value of that combo-box, it will cal Ajax or another technology back to server to retrieve data to second combo-box.So , that is idea.
You can see this link for reference here
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.