UnsupportedOperationException ERROR in Java Arraylist - java

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.

Related

How to populate jTable from database?

Hello I want to populate a table from database but I have some difficult to do since I am newbie in java programming
here is the Users.java where the method getData(select) is implemented:
#Override
public Users getData(Users u) throws Exception {
Connection con = null;
Users user = null;
ResultSet rs = null;
PreparedStatement ps = null;
try{
con = getConnection();
String sql = "SELECT * FROM USERS";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
user = new Users();
user.setFirstName(rs.getString("First_NAME"));
user.setLastName(rs.getString("LAST_NAME"));
user.setAge(rs.getInt("AGE"));
}
}catch(Exception ex){
JOptionPane.showMessageDialog(null,ex.getMessage());
}finally{
rs.close();
ps.close();
closeConnection(con);
}
return user;
}
Well the data is stored in Users object now and I want to display it on a jTable which is located in patientJframe file can you tell me how to do that?
I created a method on patientJframe but I dont know what to do Im stuck onhere.
PatientJframe :
public void PopulatejTable(){
try {
Users u = null;
Users user = UsersDB.getInstance().getData(u);
if(user== null){
DefaultTableModel dtm = (DefaultTableModel)jTable.getModel();
dtm.setRowCount(0);
Vector vector = new Vector();
vector.add(user.getCin());
vector.add(user.getLastName());
vector.add(user.getFirstName());
}else{
JOptionPane.showMessageDialog(null,"Faild");
}
} catch (Exception ex) {
Logger.getLogger(AddNewPatient.class.getName()).log(Level.SEVERE, null, ex);
}
}
The method it is correct ? please can you help me ?

Get selected JComboBox value and add to SQL query for second JComboBox

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.

Database table items don't display in JList

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.

How to get value at particular index from a vector?

When I return vector data using elementAt(2), I am getting this output.
Hello [162, Experiment 3.doc, E:\Desktop\Experiment 3.doc, doc, 35.5 kb]
I want the index value: "Experiment 3.doc".
// Function to fetch data from Database and store in jtable
public Vector getEmployee(String searchQuery)throws Exception
{
Connection con = null;
try{
Class.forName(driver);
} catch(java.lang.ClassNotFoundException e) {
e.printStackTrace();
}
try{
Vector<Vector<String>> employeeVector = new Vector<>();
con = DriverManager.getConnection(url,"conjure","conjure");
String query = "SELECT * FROM APP.FILES WHERE NAME LIKE '%"+searchQuery+"%'";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()) {
Vector<String> file = new Vector<>();
file.add(rs.getString(1)); //Empid
file.add(rs.getString(2)); //name
file.add(rs.getString(3)); //position
file.add(rs.getString(4)); //externsion
file.add(rs.getString(5)); //size
employeeVector.add(file);
}
rs.close();
return employeeVector;
} catch (Throwable err) {
err.printStackTrace();
System.out.println("Inside two");
} finally {
con.close();
}
return null;
}
// Button click, show data in jtable.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
String searchQuery = jTextField1.getText();
//get data from database
DBEngine dbengine = new DBEngine();
try {
data = dbengine.getEmployee(searchQuery);
System.out.println("Hello "+data.elementAt(2));
jTable1.setModel(new DefaultTableModel(data,header));
} catch (Exception ex) {
ex.printStackTrace();
}
}
Now I want to use column 3, i.e. filename (Experiment 3.doc) somewhere else.
How can I do that?
You have a Vector of Vectors.
data.elementAt(2) will return a Vector of Strings. You then need to get the next element from this resulting Vector, presumably data.elementAt(2).getElementAt(2)

Displaying lucene search results in java jTable

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.

Categories