Empty search bar, displays nothing in the jtable connected to database - java

When I search somethings it displays records correctly, but when I clear the search bar text it displays nothing. How can I make it so when there is nothing typed in the search bar it shows all the table records?
image of searching text in search bar
image of empty search bar
Code:
txtKerko = new JTextField();
txtKerko.setBounds(814, 60, 157, 38);
frmRegjistrimi.getContentPane().add(txtKerko);
txtKerko.setColumns(10);
txtKerko.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
try {
String id = txtpacientID.getText();
pst = con.prepareStatement("select * from pacientat where emri = ?");
pst.setString(1,txtKerko.getText());
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
if(rs.next()==true)
{
String emri = rs.getString(1);
String mbiemri = rs.getString(2);
String mosha = rs.getString(3);
String tel = rs.getString(4);
String vendbanimi = rs.getString(5);
String gjinia = rs.getString(6);
String sherbimi = rs.getString(7);
String pagesa = rs.getString(8);
String mjeku = rs.getString(9);
txtemri.setText(emri);
txtmbiemri.setText(mbiemri);
txtmosha.setText(mosha);
txttel.setText(tel);
txtvendbanimi.setText(vendbanimi);
combobox_gjinia.setSelectedItem(gjinia);
combobox_sherbimi.setSelectedItem(sherbimi);
txtpagesa.setText(pagesa);
txtmjeku.setText(mjeku);
}
else
{
txtemri.setText("");
txtmbiemri.setText("");
txtmosha.setText("");
txttel.setText("");
txtvendbanimi.setText("");
combobox_gjinia.setSelectedItem("Zgjidhni Gjininë:");
combobox_sherbimi.setSelectedItem("Zgjidhni Shërbimin:");
txtpagesa.setText("");
txtmjeku.setText("Dr.");
}
}
catch (SQLException ex) {
}
}}
);
The txtkerko is the search bar when is in JTextField
image of searched records

Related

How can I display the data (column) from a database in a text in JavaFX, so that I get the next row from the column after clicking a button?

I am a newbie here. First of all I would like to apologize for my bad english. It's not my mother tongue. I haven't used the language for a long time.
I have a problem with my code. I want to display the first row of the column of my database in a text and when I click a button I want that I then get the second row of the column of my database. And so it should go on until I have no more rows to display in that particular column.
So far I've managed to show a row from the database in a "text", but the row is the last row from the database :)
This is the method in the Database class:
public static String deutscheVokAn() {
Connection conn = null;
Statement stmt = null;
String b = null;
try {
conn = DriverManager.getConnection(connString);
String str= "SELECT " + VocabelDeutsch + " FROM " + VocabelTable;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(str);
while (rs.next()) {
b = rs.getString(VocabelDeutsch);
}
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
That is the scene in JavaFx and the text "txt" where it should be displayed:
Button zurueck = new Button("Zurück zum Hauptmenü");
Label evl = new Label("Deutsch");
Text txt = new Text();
richtigfalsch = new Label();
txtrichtig = new TextField("");
txtrichtig.setPrefColumnCount(40);
Button weiter = new Button("Weiter");
HBox h1 = new HBox(10, txtrichtig, weiter);
VBox v1 = new VBox(10, zurueck, evl, txt, richtigfalsch, h1);
v1.setPadding(new Insets(5));
Scene scene2 = new Scene(v1, 550, 300);
This is the implementation after you have clicked on the "weiter" (in English: Next) button:
weiter.setOnAction(e -> {
primaryStage.show();
txt.setText(Datenbank.deutscheVokAn());
checkAnswer();
});
I don't know if anyone would want to see the checkAnswer () method as well, but this is what it looks like:
public void checkAnswer() {
if (txtrichtig.getText().equals(Datenbank.englischeVokAn())) {
richtigfalsch.setText("Richtig");
} else {
richtigfalsch.setText("Falsch");
}
}
If someone wants to see the method englishVokAn() here:
public static String englischeVokAn() {
Connection conn = null;
Statement stmt = null;
String b = null;
try {
conn = DriverManager.getConnection(connString);
String str= "SELECT " + VocabelEnglisch + " FROM " + VocabelTable;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(str);
while (rs.next()) {
b = rs.getString(VocabelEnglisch);
}
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
My database class:
public class Datenbank {
private static final String DBlocation = "C:\\Users\\musta\\Vokabeltrainer15_db";
private static final String connString = "jdbc:derby:" + DBlocation + ";create=true";
private static final String VocabelTable = "Vokabel";
private static final String VocabelID = "VokabelID";
private static final String VocabelDeutsch = "VokabelDeutsch";
private static final String VocabelEnglisch = "VokabelEnglisch";
The actual questions are:
Shouldn't I see the second row of the column when I click the Next button? (Apparently not: D)
How could I change my code so that I see the data (1st row, then after clicking the button "weiter" the second row) in this column "VocabelEnglisch" in the text "txt"?
Can someone help me?
Thank you in advance.

Image not visible in JLabel with mouse click in JTable

I'm making a small application for a school project. Inserting photos into SQL database is fine, I rename the photos in a JTable and can also open blob photos in SQL editor. It is not possible to make the photos visible on a JLabel.
Can someone help me on this?
The intention is to get a preview of the information that has been entered at a mouse click. the application is an image bank where you can enter different healthcare devices.
Code JTable
DefaultTableModel model = (DefaultTableModel) tableDom.getModel();
try {
Class.forName("com.mysql.jdbc.Driver"); //database connectie maken
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybrains?
allowMultiQueries=true&serverTimezone=America/Winnipeg&dummyparam=", "", "")) {
String sql = "Select * from Telefonie ";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery(sql);
model.setRowCount(0);
while (rs.next()) {
int id = rs.getInt("ID");
String naam = rs.getString("naam"); // naam is een kollom in de database
String model_type = rs.getString("Model_Type");
String functionaliteit = rs.getString("Functionaliteit");
String troubleshoot = rs.getString("Troubleshoot");
String oplossing = rs.getString("Oplossing");
String voorbeeld = rs.getString("Fotonaam");
byte[] fotos = rs.getBytes("Uploadfoto");
// ImageIcon imageicon = new ImageIcon(fotos);
//voorbeeldfoto.setIcon(imageicon);
//voorbeeldfoto.setIcon(foto());
model.addRow(new Object[]{id, naam, model_type, functionaliteit, troubleshoot,
oplossing, voorbeeld, fotos});
}
}
} catch (ClassNotFoundException | SQLException e) {
}
Code Mouse Clicked
try {
int i = tableDom.getSelectedRow();
Class.forName("com.mysql.jdbc.Driver"); //database connectie maken
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybrains?
allowMultiQueries=true&serverTimezone=America/Winnipeg&dummyparam=", "", "");
String sql = "Select * from Telefonie";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery(sql);
if (rs.next());
//int i = tableDom.getSelectedRow();
TableModel model = tableDom.getModel();
iD.setText(model.getValueAt(i, 0).toString());
name.setText(model.getValueAt(i, 1).toString());
modelt.setText(model.getValueAt(i, 2).toString());
func.setText(model.getValueAt(i, 3).toString());
oplos.setText(model.getValueAt(i, 4).toString());
troubl.setText(model.getValueAt(i, 5).toString());
photoNaam.setText(model.getValueAt(i, 6).toString());
byte[] voorbeeldfoto = rs.getBytes("Uploadfoto");
JLabel image1 = (JLabel) model.getValueAt(i, 8);
ImageIcon image1Icon = (ImageIcon) image1.getIcon();
voorbeeldfoto.setIcon(image1Icon);
} catch (ClassNotFoundException | SQLException ex) {
JOptionPane.showMessageDialog(rootPane, name);
}
}

How to fill a JTable with data from a DB?

I'm trying to display a list of data when I click on a button.
Now, I have a an homepage (a jframe that is the homepage of the program) with a button that will open the list frame and that button, when it will be clicked, will get the data from my DB and update the table.
This is the code that I've wrote on the button that is in the homepage and not in the list frame
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new List().setVisible(true);
}
});
this.dispose();
String DB_URL = "jdbc:mysql://localhost:3306/registropassword?autoReconnect=true&useSSL=false";
String DB_Username = "root";
String DB_Password = "root";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, DB_Username, DB_Password);
PreparedStatement prepstmt = null;
ResultSet rs = null;
String query = "SELECT * FROM registro";
prepstmt = conn.prepareStatement(query);
rs = prepstmt.executeQuery();
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
} catch (ClassNotFoundException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
}
}
NOTE:
On this line of code the jTable2, that is the name of the table that should be updated, I got a 'cannot find symbol' error on this line.
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
Can someone help me to figure out where I'm wrong?

Load data from MySQL into JComboBox

I have two MySQL tables as image below
movie
movie_title
JComboBox combo = new JComboBox();
combo.setBounds(125, 15, 190, 20);
try {
DatabaseConnection db=new DatabaseConnection();
Connection connect=db.getConnection();
String sql="Select title FROM movie_title";
PreparedStatement ps=connect.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String name = rs.getString("title");
combo.addItem(name);
}
} catch (Exception e) {
System.out.println("null");
}
combo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
JComboBox comboBox=(JComboBox) event.getSource();
Object selected = comboBox.getSelectedItem();
displayDay(selected);
}
private void displayDay(Object selected) {
// TODO Auto-generated method stub
try {
combo1.removeAllItems();
DatabaseConnection db=new DatabaseConnection();
Connection connect=db.getConnection();
String sql="Select movie_day FROM movie WHERE movie_title = ?";
PreparedStatement ps=connect.prepareStatement(sql);
ps.setObject(1, selected);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String day = rs.getString("movie_day");
combo1.addItem(day);
}
} catch (Exception e) {
System.out.println("null");
}
}
});
I have implemented ActionListener in comboBox. When user select movie Marvel's Captain America, it will get the movie_day item from movie and load into combo1. Is there a way I can make the combo1 display the movie_day which is Sunday, 28 Apr 2016 one time only instead of two ?
Edit
private void displayDay(Object selected) {
// TODO Auto-generated method stub
try {
combo1.removeAllItems();
DatabaseConnection db=new DatabaseConnection();
Connection connect=db.getConnection();
String sql="Select movie_day FROM movie WHERE movie_title = ?";
PreparedStatement ps=connect.prepareStatement(sql);
ps.setObject(1, selected);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String day = rs.getString("movie_day");
DefaultComboBoxModel model = (DefaultComboBoxModel)combo1.getModel();
if (model.getIndexOf(day) == -1)
{
combo1.addItem(day);
}
}
} catch (Exception e) {
System.out.println("null");
}
Is there a way I can make the combo1 display the movie_day which is Sunday, 28 Apr 2016 one time only instead of two ?
Before adding the date to the combo box you need to check if the date already exists.
DefaultComboBoxModel model = (DefaultComboBoxModel)comboBox.getModel();
if (model.getIndexOf(theDate) == -1)
{
comboBox.addItem( theDate );
}
You could also change the SQL statement to only get "unique" dates, but I don't know SQL well enough to give you the actual syntax. Maybe this SQL Tutorial will help, otherwise you need to find a better tutorial.

embed MS Access database with runnable jar

So my aim is to make a runnable jar. I've made a program using swings which uses MS Access database to fetch records. So, I've used an absolute path to refer to the database for connection.
Now, I intend to distribute this runnable jar to other people as well. So I guess the best option would be to embed the MS Access database as well in the jar file. But I don't know how to do that. Where should I keep the database in my Project Explorer ? Should I use a relative path etc. Any form of help would be appreciable.
I've found many tutorials for using Derby database that would implement the same but none pertaining to Ms Access database. Suggestions are welcome !
This is my code:-
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class r_search extends JFrame implements ActionListener {
JFrame frame1;
JLabel l0, l1, l2;
JComboBox c1;
JButton b1;
Connection con;
ResultSet rs, rs1;
Statement st, st1;
PreparedStatement pst;
String ids;
static JTable table;
String[] columnNames = {"SECTION NAME", "REPORT NAME", "CONTACT", "LINK"};
String from;
r_search() {
l0 = new JLabel("Fetching Search Results...");
l0.setForeground(Color.blue);
l0.setFont(new Font("Serif", Font.BOLD, 20));
l1 = new JLabel("Search");
b1 = new JButton("submit");
l0.setBounds(100, 50, 350, 40);
l1.setBounds(75, 110, 75, 20);
b1.setBounds(150, 150, 150, 20);
b1.addActionListener(this);
setTitle("Search Executive Reports :) ");
setLayout(null);
//setVisible(true);
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
add(l0);
add(l1);;
add(b1);
try {
Vector v = new Vector();
String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\users\\ppreeti\\executive_db.accdb";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection(url,"","");
/*con = DriverManager.getConnection("jdbc:oracle:thin:#mcndesktop07:1521:xe", "sandeep", "welcome");*/
st = con.createStatement();
rs = st.executeQuery("select index_name from Index1");
// Vector v = new Vector();
while (rs.next()) {
ids = rs.getString(1);
v.add(ids);
}
c1 = new JComboBox(v);
c1.setBounds(150, 110, 150, 20);
add(c1);
st.close();
rs.close();
} catch (Exception e) {
}
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == b1) {
showTableData();
}
}
public void showTableData() {
frame1 = new JFrame("Database Search Result");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLayout(new BorderLayout());
//TableModel tm = new TableModel();
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
//DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames());
//table = new JTable(model);
table = new JTable();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
from = (String) c1.getSelectedItem();
//String textvalue = textbox.getText();
String uname = "";
String email = "";
String pass = "";
String cou = "";
try {
/* pst = con.prepareStatement("select * from emp where UNAME='" + from + "'");*/
pst = con.prepareStatement("select distinct Section.Section_Name,Report.Report_Name,Report.Link,Contact.Contact_Name "
+ "FROM (( Section INNER JOIN Report ON Report.Section_ID=Section.Section_ID ) INNER JOIN Contact ON Contact.Contact_ID=Report.Contact_ID ) LEFT JOIN Metrics ON Metrics.Report_ID=Report.Report_ID "
+ " WHERE Section.Section_Name LIKE '%"+from+"%' OR Report.Report_Name LIKE '%"+from+"%' OR Metrics.Metric_Name LIKE '%"+from+"%' OR Contact.Contact_Name LIKE '%"+from+"%' ");
ResultSet rs = pst.executeQuery();
int i = 0;
while (rs.next()) {
uname = rs.getString("Section_Name");
email = rs.getString("Report_Name");
pass = rs.getString("Contact_Name");
cou = rs.getString("Link");
model.addRow(new Object[]{uname, email, pass, cou});
i++;
}
if (i < 1) {
JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
}
if (i == 1) {
System.out.println(i + " Record Found");
} else {
System.out.println(i + " Records Found");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
frame1.setSize(1000, 400);
}
public static void main(String args[]) {
new r_search();
}
}
The following worked for me using Eclipse and JavaSE-1.7. Eclipse shows the following in its Package Explorer
The [folders] and files in my project folder are
[C:]
[Users]
[Gord]
[workspace]
[com.example.jartest]
[src]
[com]
[example]
[jartest]
JarTestMain.java
[resources]
JarData.mdb
The Java code in JarTestMain.java is
package com.example.jartest;
import java.io.*;
import java.nio.file.*;
import java.sql.*;
public class JarTestMain {
public static void main(String[] args) {
String mdbFileName = "JarData.mdb";
String tempDbPath = System.getenv("TEMP").replace('\\', '/') + "/" + mdbFileName;
// retrieve .mdb database from the JAR file and save to %TEMP% folder
InputStream strmIn = JarTestMain.class.getResourceAsStream("resources/" + mdbFileName);
File f = new File(tempDbPath);
try {
Files.copy(strmIn, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
// open the copy of the database in %TEMP% folder and read from its table
String connectionString =
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};" +
"DBQ=" + tempDbPath;
try (Connection con = DriverManager.getConnection(connectionString)) {
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM Table1");
while (rs.next()) {
System.out.println(String.format(
"%d: %s",
rs.getInt("ID"),
rs.getString("TextField")));
}
rs.close();
con.close();
f.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
After I exported the project to a "Runnable JAR file" named JarTest.jar I was able to run it on my 32-bit Windows test machine using...
"C:\Program Files\Java\jre7\bin\java" -jar JarTest.jar
...and on my 64-bit Windows development machine via
"C:\Program Files (x86)\Java\jre7\bin\java" -jar JarTest.jar

Categories