I am trying to get items from a table and display them into JList. I ran the code and nothing was displayed in JList and there was no error. I debugged the code and it counted until table item length.
Followed this answer.
static Connection conn = new DBConnection().connect();
private JList listDepartments = null;
public AddDepartment() {
listDepartments = new JList();
listDepartments.setBounds(189, 33, 1, 1);
contentPane.add(listDepartments);
update_departments(listDepartments);
}
private static void update_departments(JList listDepartments) {
try {
String sql = "Select * FROM Departments";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
DefaultListModel listModel = new DefaultListModel();
while (rs.next()) {
System.out.println("inside while");
String departmentName = rs.getString("Name");
listModel.addElement(departmentName);
}
listDepartments.setModel(listModel);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
Table Content:
Name: Departments
Columns:
Id - INT primary key, auto increment, unique
Name - VARCHAR(255)
Changed with JTable and added followed codes in public addDepartment()
model = new DefaultTableModel();
tableDepartments = new JTable(model);
removed listDepartments.setModel(listModel); from update_departments() function.
Related
I have two forms, first is for the Login and second one is the Main Form with JTable on it, that can display data from the database. This the code I used for viewing and studentlist. I can't figure out how I got the "UnsupportedOperationExemption" Error. I am new in Java. I am using Apache Netbeans.
ArrayList<Student> list;
myQuery mq = new myQuery();
public MainForm(){
initComponents();
view();
}
void view(){
list = mq.studentlist();
DefaultTableModel model = (DefaultTableModel)studTable.getModel();
Object[] row = new Object[11];
for(int i=0; i<list.size(); i++){
row[0]=list.get(i).getStudID();
row[1]=list.get(i).getLRN();
row[2]=list.get(i).getGrade();
row[3]=list.get(i).getLName();
row[4]=list.get(i).getFName();
row[5]=list.get(i).getMName();
row[6]=list.get(i).getGender();
row[7]=list.get(i).getBday();
row[8]=list.get(i).getAge();
row[9]=list.get(i).getCNumber();
row[10]=list.get(i).getAdviser();
model.addRow(row);
}
}
}
//----------------ArrayList Here---------------------------
ArrayList<Student> studentlist = new ArrayList<>();
DefaultTableModel model = new DefaultTableModel();
PreparedStatement ps;
ResultSet rs;
String query;
Student stud;
try{
query = "SELECT * FROM students";
ps = myConnection.getConnection().prepareStatement(query);
rs = ps.executeQuery();
while(rs.next()){
stud = new Student(rs.getInt("idstudents"),
rs.getInt("LRN"),
rs.getString("Grade"),
rs.getString("LName"),
rs.getString("FNname"),
rs.getString("MName"),
rs.getString("Gender"),
rs.getString("Bday"),
rs.getInt("Age"),
rs.getInt("CNumber"),
rs.getString("Adviser"));
studentlist.add(stud);
}
}catch(Exception ex){
ex.printStackTrace();
//return false;
}
return studentlist;
}
Just put a pair of backticks (``) around "students" in your query. That declares the table in the query.
I am designing a simple database application that features 2 jComboBoxes in the GUI. The first jComboBox is populated with the results of an SQL query. I would like the second jComboBox to populate with the results of a second query that incorporates the user selected value in the first box, but I can't quite get it to work.
I have created 2 classes, one that draws the GUI and contains the main method, and a second class that queries my Oracle database.
My GUI class:
public class TestUI extends javax.swing.JFrame {
// Create new form TestUI
public TestUI() {
initComponents();
}
#SuppressWarnings("unchecked")
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jComboBox1 = new javax.swing.JComboBox<>();
jTextField1 = new javax.swing.JTextField();
jComboBox2 = new javax.swing.JComboBox<>();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
// Combo box 1 population
jComboBox1.removeAllItems();
createConnection c1 = new createConnection();
c1.getEmployee().forEach((employee) -> {
jComboBox1.addItem(employee);
});
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
// ComboBox 2 population
jComboBox2.removeAllItems();
}
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add handling code here:
}
public static void main(String args[]) {
DRAW GUI
}
}
And my database class:
import java.util.List;
import java.util.ArrayList;
import java.sql.*;
public class createConnection {
String empName;
public Connection createConnection() {
try {
Class.forName(driver);
java.sql.Connection conn = DriverManager.getConnection(DB_URL, DB_username, DB_password);
return conn;
} catch (ClassNotFoundException | SQLException e) {
return null;
}
}
// ComboBox 1
public List<String> getEmployee() {
List<String> list = new ArrayList();
Connection conn = createConnection();
try {
Statement stmt = conn.createStatement();
String query = "SELECT * FROM hr.employees ORDER BY last_name";
ResultSet results = stmt.executeQuery(query);
while (results.next()) {
list.add(results.getString("last_name"));
}
} catch (Exception e) {
System.out.println("Exception = " + e);
}
return list;
}
// Combo Box 2
public List<String> getEmpLocation() {
List<String> list = new ArrayList();
Connection conn = createConnection();
try {
Statement stmt = conn.createStatement();
String query = "SELECT country_id FROM hr.location WHERE hr.location.emp_name = " + empName;
ResultSet results = stmt.executeQuery(query);
while (results.next()) {
list.add(results.getString("last_name"));
}
} catch (Exception e) {
System.out.println("Exception = " + e);
}
return list;
}
}
I have left out irrelevant code like db connection variables and GUI coordinates etc.
I am wondering how to properly get the getEmpLocation() method in the database class to populate the 2nd ComboBox. This will involve adding code to both classes and passing the variable value but I can't figure it out! Any help would be greatly appreciated here.
I'm assuming that you'd like select a value from your first JComboBox then click on a button to process your selected data and load new data to your second JComboBox.
In this case you need an ActionListener to your JButton instead of your JComboBox:
jButton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
selectedName = (String) jComboBox1.getSelectedItem();
}
});
You also need to store your selected value in a variable. The getSelectedItem() method returns an Object so it needs to be cast to a String in your case.
Since we added an ActionListener to a button you dont need this one:
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
In your createConnection class (by naming convention class names should start with a capital letter):
If you are not using try-with-resources statement you should close your connections after the catch block.
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
You need to pass your selectedName variable to getEmpLocation() method:
public List<String> getEmpLocation(String name) {
You should use a PreparedStatement instead of Statement:
String query = "SELECT first_name FROM employees WHERE last_name = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, name);
ResultSet results = ps.executeQuery();
To be honest I don't know what you'd like to achieve with your select queries. First, this select query won't work. Table name is LOCATIONS instead of location, and it doesnt have a column called emp_name.
"SELECT country_id FROM hr.location WHERE hr.location.emp_name = ?"
If you'd like to get locations you should use a query like this:
"SELECT dep.department_name, loc.city, cou.country_name
FROM employees emp, departments dep, locations loc, countries cou
WHERE emp.last_name = ?
AND emp.department_id = dep.department_id
AND dep.location_id = loc.location_id
AND loc.country_id = cou.country_id"
You can choose which location you'd like to use department, city or country name. But my main problem is that if you select last names first and put them in a JComboBox it is most likely you will get only one row of data, so there is no point in using the second JComboBox. Let's approach this problem from the other side. What if you select location first and then select your employee. That could solve this issue.
Quick Example:
You select all first names from database, then you can select proper last name.
Selecting all first name from database:
public List<String> getEmpFirstName() {
List<String> list = new ArrayList();
Connection conn = createConnection();
try {
Statement stmt = conn.createStatement();
String query = "SELECT DISTINCT first_name "
+ "FROM hr.employees "
+ "ORDER BY first_name";
ResultSet results = stmt.executeQuery(query);
while (results.next()) {
list.add(results.getString("first_name"));
}
} catch (Exception e) {
System.out.println("Exception = " + e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
return list;
}
Selecting last name(s) based on first name using PreparedStatement:
public List<String> getEmpLastName(String name) {
List<String> list = new ArrayList();
Connection conn = createConnection();
try {
String query = "SELECT last_name "
+ "FROM employees "
+ "WHERE first_name = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, name);
ResultSet results = ps.executeQuery();
while (results.next()) {
list.add(results.getString("last_name"));
}
} catch (Exception e) {
System.out.println("Exception = " + e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
return list;
}
Update your ActionListener:
jButton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Store selected value
selectedName = (String) jComboBox1.getSelectedItem();
// Create Connection and pass selected value to getEmpLastName
createConnection c1 = new createConnection();
names = c1.getEmpLastName(selectedName);
// Clear your second comboBox and fill with data
jComboBox2.removeAllItems();
for (String lastName : names) {
jComboBox2.addItem(lastName);
}
}
});
Try to select common names like Alexander, David, James, John, Julia and so on.
I'm trying to display values in JComboBox B when I select items from JComboBox A. So far, nothing happened when I select a value from JComboBox A. Here is my data and code. So for instance, if I select 1 from my JComboBox A(paperid), my result in JComboBox B(authorid) will be 1,2,4.
JComboBox A
JComboBox B
private void comboboxAPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
String display = (String) comboboxA.getSelectedItem();
String sql = "Select authorid from submission where paperid =?";
try {
ps=conn.prepareStatement(sql);
ps.setString(1,display);
rset = ps.executeQuery();
if (rset.next()){
String add1 = rset.getString("authorid");
System.out.println(add1);
comboboxB.setSelectedItem(add1);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null,e);
}
}
I think that I've understood your question at last. You want the result of the query to be charged in the second combobox, don't you?
If that's the case, try this
private void comboboxAPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
String display = (String) comboboxA.getSelectedItem();
String sql = "Select authorid from submission where paperid =?";
comboboxB.removeAllItems(); // <- Clear comboboxB
try {
ps = conn.prepareStatement(sql);
ps.setString(1, display);
rset = ps.executeQuery();
while (rset.next()) { // <- Include all authors found
String add1 = rset.getString("authorid");
System.out.println(add1);
comboboxB.addItem(add1);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null,e);
}
}
Maybe you have to force a repaint in the container where the JComboBoxes are displayed after the execution of this method. "myContainer" is not the variable name, replace with the name of your panel or your frame.
myContainer.revalidate();
myContainer.repaint();
private void fillCombo(){
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/MTD","root","");
PreparedStatement ps = con.prepareStatement("Select * from sa where municipalities ='" + municipality.getSelectedItem().toString()+ "'");
ResultSet rs = ps.executeQuery();
while(rs.next()){
String mun = rs.getString("Province");
municipality.addItem(mun);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
I have two combo boxes that get values from the database. The first combo (province) comes from a table with one column which is a list of provinces. So on province.itemchangedstate I want it to set the values of combo2 (municipalities) in relation to the province selected by combo1 (province).
Am new to java and stuck on that and don't know how to proceed further. Can anyone help?
According to me,your requirement is to populate one combobox on the basis of selection of other.
like
might be this sample code work for you.
private void populateDropDownOfEnum(){
EncDecImageFrame encDecImageFrame = new EncDecImageFrame();
jComboBox1.setEditable(true);
String[] jComboBox1Values = getListOfAllEnumNames();
if (jComboBox1Values != null && jComboBox1Values.length != 0) {
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(jComboBox1Values));
}
Object item = jComboBox1.getSelectedItem();
jComboBox2.removeAllItems();
jComboBox2.setEditable(true);
String[] enumValuesByEnumNames = getListOfAllEnumValues(
item.toString(), artifcatoryPathOfJar.getText());
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(
enumValuesByEnumNames));
jComboBox1.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
Object item = jComboBox1.getSelectedItem();
jComboBox2.removeAllItems();
jComboBox2.setEditable(true);
String[] enumValuesByEnumNames = getListOfAllEnumValues(
item.toString(), artifcatoryPathOfJar.getText());
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(
enumValuesByEnumNames));
}
});
I am building a java desktop application that uses
lucene 3.6.2 search engine to search for data in a derby database
java swing JTable and netbeans
A user enters a search query into the testfield and
the search result is displayed in a Jtable and the defaulttablemodel.
I have tried my hands on tutorials about displaying database
information in a jTable.
But this time I want to have a search field
and a search button. a string is entered into the search field after
finding the matches , then the result is displayed in the JTable
below are code snippets
public class GNSSJFrame extends javax.swing.JFrame {
String searchField;
DBSearch dbs = new DBSearch();
Vector<String> header = new Vector<>();;
Vector<Vector<String>> tabledata = new Vector<>();;
TableData td = new TableData();
public GNSSJFrame() {
initComponents();
}
searchResultTable.setModel(new javax.swing.table.DefaultTableModel(
tabledata, header
));
searchResultTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
jScrollPane1.setViewportView(searchResultTable);
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel2.setText(" SEARCH RESULTS");
private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
searchField = searchTextField.getText();
if(!searchField.isEmpty())
{
tabledata = dbs.searchDatabase(searchField + "*");
td.fillHeader();
header = td.getHeader();
}
} catch (CorruptIndexException ex) {
Logger.getLogger(GNSSJFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (LockObtainFailedException ex) {
Logger.getLogger(GNSSJFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | ParseException ex) {
Logger.getLogger(GNSSJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void searchTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
Code for the lucene search engine
public class DBSearch {
//Field Declarations
Version matchVersion = Version.LUCENE_36;
String host = "jdbc:derby://localhost:1527/NSS_DB";
String uName = "staff";
String uPass = "password";
String qString;
Statement stmt;
ResultSet rs;
Connection con;
Document doc;
Vector<Vector<String>> docVector;
Document d;
public DBSearch()
{}
public Vector<Vector<String>> searchDatabase( String qs) throws CorruptIndexException, LockObtainFailedException, IOException, ParseException
{
qString = qs;
// create some index
Directory index = new RAMDirectory();
StandardAnalyzer analyzer = new StandardAnalyzer(matchVersion);
IndexWriterConfig IWConfig = new IndexWriterConfig(Version.LUCENE_36, analyzer);
IndexWriter iw = new IndexWriter(index,IWConfig) ;
try {
con = DriverManager.getConnection(host, uName, uPass);
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM APP.REGISTRY";
rs = stmt.executeQuery(sql);
rs.beforeFirst();
while(rs.next()) {
doc = new Document();
doc.add(new Field("subject",rs.getString("SUBJECT"),Field.Store.YES,Field.Index.ANALYZED));
doc.add(new Field("letter_from",rs.getString("LETTER_FROM"),Field.Store.YES,Field.Index.ANALYZED));
iw.addDocument(doc);
}
iw.close();
stmt.close();
rs.close();
}
catch(SQLException err)
{System.out.println(err.getMessage());}
//Oen the index
IndexReader ir = IndexReader.open(index);
//create the searcher object
IndexSearcher searcher = new IndexSearcher(ir);
QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_36,
new String[]{"subject","letter_from","remarks","office_dispatched_to"}, analyzer);
Query query = queryParser.parse(qString);
//Displaying the search results
TopDocs topDocs = searcher.search(query,10);
ScoreDoc[] hits = topDocs.scoreDocs;
System.out.println("Total hits "+topDocs.totalHits);
for(int q = 0; q<7 ;q++)
{
Vector<String> vn = new Vector<>();
vn.add(d.get("subject"));
vn.add("letter_from");
vn.add("remark");
vn.add("office_dispatched_to");
}
return docVector;
}
public class TableData {
private Vector<Vector<String>> matrix = new Vector<>();
private Vector<String> header = header = new Vector<>();;
public TableData()
{ }
public Vector<Vector<String>> getMatrix() {
return matrix;
}
public void setMatrix(Vector<Vector<String>> matrix) {
this.matrix = matrix;
}
public Vector<String> getHeader() {
return header;
}
public void setHeader(Vector<String> header) {
this.header = header;
}
public void fillHeader(){
header.add(0,"ID");
header.add(1,"SUBJECT");
header.add(2,"LETTER DATE");
header.add(3,"DATE RECEIED");
header.add(4,"REMARKS");
header.add(5,"DATE DISPATCHED");
header.add(6,"DESTINATION OFFICE");
}
}
}
It looks like you are constructing an anonymous DefaultTableModel using a suitable Vector, but you subsequently update the Vector rather than the TableModel itself. Updating the model should cause the table to refresh itself. You can obtain a reference to your model from table.getModel(), and you can update it using model.setDataVector(). Extending AbstractTableModel, as shown here, may be an alternative.