Load data from MySQL into JComboBox - java

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.

Related

Use a Java Class to display data to jTable from a jFrame

I would like to know how can I reference a java class in my jFrame form to display data on the jTable. This is a code from my jFrame and I want to know how can I put it in a java class and just reference the class here in the JFrame so I could save space in this JFrame form
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String sql = "select * from description";
if(jComboBox1.getSelectedIndex() == 0)
try{
PreparedStatement pstmt =conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
jTable1.removeColumn(jTable1.getColumnModel().getColumn(2));
model.setRowCount(0);
while (rs.next()){
model.addRow(new String[]{rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4)});
}
} catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
Something like this?
public class CustomActionHandler {
private JComboBox jComboBox1;
// all the necessary stuff you need for the code to work
CustomActionHandler(JComboBox jComboBox1, etc...) {
this.jComboBox1 = jComboBox1;
// finish passing all the data here
}
public static void JComboActionFollowup() {
// TODO add your handling code here:
String sql = "select * from description";
if(jComboBox1.getSelectedIndex() == 0)
try{
PreparedStatement pstmt =conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
jTable1.removeColumn(jTable1.getColumnModel().getColumn(2));
model.setRowCount(0);
while (rs.next()){
model.addRow(new String[]{rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4)});
}
} catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
}
and in your JFrame:
private CustomActionHandler actionhandler = new CustomActionHandler(jComboBox1, etc...)
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
actionhandler.JComboActionFollowup();
}

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

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

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);
}
}

Insert Date from java (eclipse) to Sql (workbench)

I entered the code and I wanted to send this data to the prepared table in Workbench (SQL). The system shows no connection. I work in an eclipse environment and I have problems to send data from jtable to Workbench
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = (Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/tabela2?autoReconnect=true&useSSL=false","root","Jackpatu205");
String insert = "insert into autohandel values (?, ? , ? , ?,?)";
PreparedStatement ps = (PreparedStatement) conn.prepareStatement(insert);
ps.setString(1, "1");
ps.setString(2, "Citroen");
ps.setString(3, "2015");
ps.setString(4, "12500");
ps.setString(5,"France");
ps.executeUpdate();
if (conn !=null) {
System.out.println("\nConnected Update");
System.out.println(" --------------------------------------");
}
}catch (Exception e) {
System.out.print("No Connection Update");
}
//
}
});

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?

Categories