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.
Related
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 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.
Im trying to match a text Config migration from ASA5505 8.2 to ASA5516 in column TITLE.
My program looks like this.
Directory directory = FSDirectory.open(indexDir);
MultiFieldQueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_35,new String[] {"TITLE"}, new StandardAnalyzer(Version.LUCENE_35));
IndexReader reader = IndexReader.open(directory);
IndexSearcher searcher = new IndexSearcher(reader);
queryParser.setPhraseSlop(0);
queryParser.setLowercaseExpandedTerms(true);
Query query = queryParser.parse("TITLE:Config migration from ASA5505 8.2 to ASA5516");
System.out.println(queryStr);
TopDocs topDocs = searcher.search(query,100);
System.out.println(topDocs.totalHits);
ScoreDoc[] hits = topDocs.scoreDocs;
System.out.println(hits.length + " Record(s) Found");
for (int i = 0; i < hits.length; i++) {
int docId = hits[i].doc;
Document d = searcher.doc(docId);
System.out.println("\"Title :\" " +d.get("TITLE") );
}
But its returning
"Title :" Config migration from ASA5505 8.2 to ASA5516
"Title :" Firewall migration from ASA5585 to ASA5555
"Title :" Firewall migration from ASA5585 to ASA5555
Second 2 results are not expected.So what modification required to match exact text Config migration from ASA5505 8.2 to ASA5516
And my indexing function looks like this
public class Lucene {
public static final String INDEX_DIR = "./Lucene";
private static final String JDBC_DRIVER = "oracle.jdbc.OracleDriver";
private static final String CONNECTION_URL = "jdbc:oracle:thin:xxxxxxx"
private static final String USER_NAME = "localhost";
private static final String PASSWORD = "localhost";
private static final String QUERY = "select * from TITLE_TABLE";
public static void main(String[] args) throws Exception {
File indexDir = new File(INDEX_DIR);
Lucene indexer = new Lucene();
try {
Date start = new Date();
Class.forName(JDBC_DRIVER).newInstance();
Connection conn = DriverManager.getConnection(CONNECTION_URL, USER_NAME, PASSWORD);
SimpleAnalyzer analyzer = new SimpleAnalyzer(Version.LUCENE_35);
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_35, analyzer);
IndexWriter indexWriter = new IndexWriter(FSDirectory.open(indexDir), indexWriterConfig);
System.out.println("Indexing to directory '" + indexDir + "'...");
int indexedDocumentCount = indexer.indexDocs(indexWriter, conn);
indexWriter.close();
System.out.println(indexedDocumentCount + " records have been indexed successfully");
System.out.println("Total Time:" + (new Date().getTime() - start.getTime()) / (1000));
} catch (Exception e) {
e.printStackTrace();
}
}
int indexDocs(IndexWriter writer, Connection conn) throws Exception {
String sql = QUERY;
Statement stmt = conn.createStatement();
stmt.setFetchSize(100000);
ResultSet rs = stmt.executeQuery(sql);
int i = 0;
while (rs.next()) {
System.out.println("Addind Doc No:" + i);
Document d = new Document();
System.out.println(rs.getString("TITLE"));
d.add(new Field("TITLE", rs.getString("TITLE"), Field.Store.YES, Field.Index.ANALYZED));
d.add(new Field("NAME", rs.getString("NAME"), Field.Store.YES, Field.Index.ANALYZED));
writer.addDocument(d);
i++;
}
return i;
}
}
PVR is correct, that using a phrase query is probably the right solution here, but they missed on how to use the PhraseQuery class. You are already using QueryParser though, so just use the query parser syntax by enclosing you search text in quotes:
Query query = queryParser.parse("TITLE:\"Config migration from ASA5505 8.2 to ASA5516\"");
Based on your update, you are using a different analyzer at index-time and query-time. SimpleAnalyzer and StandardAnalyzer don't do the same things. Unless you have a very good reason to do otherwise, you should analyze the same way when indexing and querying.
So, change the analyzer in your indexing code to StandardAnalyzer (or vice-versa, use SimpleAnalyzer when querying), and you should see better results.
Here is what i have written for you which works perfectly:
USE: queryParser.parse("\"Config migration from ASA5505 8.2 to ASA5516\"");
To create indexes
public static void main(String[] args)
{
IndexWriter writer = getIndexWriter();
Document doc = new Document();
Document doc1 = new Document();
Document doc2 = new Document();
doc.add(new Field("TITLE", "Config migration from ASA5505 8.2 to ASA5516",Field.Store.YES,Field.Index.ANALYZED));
doc1.add(new Field("TITLE", "Firewall migration from ASA5585 to ASA5555",Field.Store.YES,Field.Index.ANALYZED));
doc2.add(new Field("TITLE", "Firewall migration from ASA5585 to ASA5555",Field.Store.YES,Field.Index.ANALYZED));
try
{
writer.addDocument(doc);
writer.addDocument(doc1);
writer.addDocument(doc2);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static IndexWriter getIndexWriter()
{
IndexWriter indexWriter=null;
try
{
File file=new File("D://index//");
if(!file.exists())
file.mkdir();
IndexWriterConfig conf=new IndexWriterConfig(Version.LUCENE_34, new StandardAnalyzer(Version.LUCENE_34));
Directory directory=FSDirectory.open(file);
indexWriter=new IndexWriter(directory, conf);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return indexWriter;
}
}
2.To search string
public static void main(String[] args)
{
IndexReader reader=getIndexReader();
IndexSearcher searcher = new IndexSearcher(reader);
QueryParser parser = new QueryParser(Version.LUCENE_34, "TITLE" ,new StandardAnalyzer(Version.LUCENE_34));
Query query;
try
{
query = parser.parse("\"Config migration from ASA5505 8.2 to ASA5516\"");
TopDocs hits = searcher.search(query,3);
ScoreDoc[] document = hits.scoreDocs;
int i=0;
for(i=0;i<document.length;i++)
{
Document doc = searcher.doc(i);
System.out.println("TITLE=" + doc.get("TITLE"));
}
searcher.close();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static IndexReader getIndexReader()
{
IndexReader reader=null;
Directory dir;
try
{
dir = FSDirectory.open(new File("D://index//"));
reader=IndexReader.open(dir);
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return reader;
}
Try PhraseQuery as follow:
BooleanQuery mainQuery= new BooleanQuery();
String searchTerm="config migration from asa5505 8.2 to asa5516";
String strArray[]= searchTerm.split(" ");
for(int index=0;index<strArray.length;index++)
{
PhraseQuery query1 = new PhraseQuery();
query1.add(new Term("TITLE",strArray[index]));
mainQuery.add(query1,BooleanClause.Occur.MUST);
}
And then execute the mainQuery.
Check out this thread of stackoverflow, It may help you to use PhraseQuery for exact search.
I am trying to pass data from a db in another class into JFrame in jcombobox but only the last row is displayed. Below is a sample code:
Class A...
public String jcbNames() {
try {
con = connCC.getDBconnection();
stm = con.createStatement();
ResultSet rs = stm.executeQuery("Select customerName From appointment");
while (rs.next()) {
customer = (rs.getString(1));
}
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Appointment.class.getName()).log(Level.SEVERE, null, ex);
}
return customer;
}
Class JFrame...
private void jCBCustomersActionPerformed(java.awt.event.ActionEvent evt) {
Appointment app = new Appointment();
this.jCBCustomers.removeAllItems();
this.jCBCustomers.addItem(app.jcbNames());
}
the problem is there you return just one String in your jcbNames method , use an arraylist and add all of strings to it and then return it as a collection of database data.
so change your methods or use this modified methods.
public ArrayList<String> jcbNames() {
try {
con = connCC.getDBconnection();
stm = con.createStatement();
ResultSet rs = stm.executeQuery("Select customerName From appointment");
ArrayList<String> list = new ArrayList<>();
while (rs.next()) {
list.add(rs.getString(1));
}
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Appointment.class.getName()).log(Level.SEVERE, null, ex);
}
return list;
}
and
private void jCBCustomersActionPerformed(java.awt.event.ActionEvent evt) {
Appointment app = new Appointment();
this.jCBCustomers.removeAllItems();
ArrayList<String> list =app.jcbNames();
for (String str:list){
this.jCBCustomers.addItem(str);
}
}
and if you don't want to use this.jCBCustomers.removeAllItems(); to prevent duplicates , use below code
private void jCBCustomersActionPerformed(java.awt.event.ActionEvent evt) {
Appointment app = new Appointment();
// collect all of your current data in jcombobox
ArrayList<String> current_list = new ArrayList<>();
int count = this.jCBCustomers.getItemCount(); // get count of them
for (int i = 0; i < count; i++) {
current_list.add((String) this.jCBCustomers.getItemAt(i)); // add them to current list
}
// data that returned from database
ArrayList<String> returned_from_db_list = jcbNames(); // calling jcbNames method
/*
for each string that has returned from database ,
if it doesn't in the current_list
you can add it to jcombobox , so ...
*/
for (String str : returned_from_db_list) {
if ( !current_list.contains(str) ) { // check for existing in the current_list
current_list.add(str); // adding fresh data to current_list!
/*
or you can add them directly to jcombobox and remove above statement.
this.jCBCustomers.addItem(str); // add updated data to jcombobox
*/
}
}
/*
if ::: you use current_list.add(str); in above for-each-loop ,
now you must update jcombobox data !
else ::: remove below loop.
*/
for (String singleStr : current_list) {
this.jCBCustomers.addItem(singleStr); // add updated data to jcombobox
}
}
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)