I need to disable edit on double click in each cell from Jtable in Java Netbeans. The JTable is connected to sqlite database and shows the database table record.
private void DisplayTable() {
try{
Class.forName("org.sqlite.JDBC");
Connection conn=DriverManager.getConnection("jdbc:sqlite:clientrec.sqlite");
String sql = "SELECT * FROM client";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
t1.setModel(DbUtils.resultSetToTableModel (rs));
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
} finally{
try{
rs.close();
pst.close();
}
catch(Exception e){
}
}
}
I also created onmouseclick event for the jtable to display selection in Jtextfields, combobox, jcalendar
private void t1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
DefaultTableModel model=(DefaultTableModel) t1.getModel();
int number=t1.getSelectedRow();
String tc=t1.getModel().getValueAt(number, 0).toString();
try{
Class.forName("org.sqlite.JDBC");
Connection conn=DriverManager.getConnection("jdbc:sqlite:clientrec.sqlite");
String sql = "SELECT * FROM client WHERE ID="+tc+"";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if(rs.next()){
String id=rs.getString("ID");
String fullname=rs.getString("FullName");
String phone=rs.getString("Phone");
String allergy=rs.getString("Allergy");
String date=rs.getString("Date1");
String budgetpayed=rs.getString("BudgetPayed");
String totalbudget=rs.getString("TotalBudget");
String budgetleft=rs.getString("BudgetLeft");
String currency=rs.getString("Currency");
String datea=rs.getString("Dateappointment");
String description=rs.getString("Description");
FullName.setText(fullname);
Phone.setText(phone);
Allergy.setText(allergy);
((JTextField)Date1.getDateEditor().getUiComponent()).setText(date);
BudgetP.setText(budgetpayed);
TBudget.setText(totalbudget);
BudgetL.setText(budgetleft);
Curr.setSelectedItem(currency);
((JTextField)Date2.getDateEditor().getUiComponent()).setText(datea);
Desc.setText(description);
}
}catch (Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
Override the isCellEditable(...) method of the JTable:
JTable table = new JTable(...)
{
#Override
public boolean isCellEditable(int row, int column)
{
return false;
}
};
Related
I need to display the details of students in a particular stream of a schoolclass in Jtable from a database containing all the names of students in the school. I have two jComboboxes, on to select which class and the other to select the stream. I am asking for a way to define these two conditions in order to display all the students in a particular stream in a jtable. I apologize in advance if my code is messy.
public Classes() {
initComponents();
show_student();
}
public Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sms", "root", "");
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return con;
}
public ArrayList<Individualclass> studentList(String ValToSearch) {
ArrayList<Individualclass> list = new
ArrayList<Individualclass>();
Statement st;
ResultSet rs;
try {
Connection con=getConnection();
st = con.createStatement();
String searchQuery = "SELECT * FROM `students` WHERE CONCAT(`firstName`, `surname`, `otherNames`, `regNo`) LIKE '%"+ValToSearch+"%'";
rs = st.executeQuery("searchQuery ");
Individualclass ic;
while(rs.next()) {
ic = new Individualclass(
rs.getString("firstName"),
rs.getString("surname"),
rs.getString("otherNames"),
rs.getInt("regNo")
);
list.add(ic);
}
} catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return list;
}
public void findStudents() {
}
private void sClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sClassActionPerformed
try {
Connection con = getConnection();
String fetch_row = "SELECT * FROM students where sClass=?";
PreparedStatement pst = con.prepareStatement(fetch_row);
pst.setString(1, (String) sClass.getSelectedItem());
ResultSet rs = pst.executeQuery();
while(rs.next()) {
Individualclass ic = new Individualclass(rs.getString("firstName"),rs.getString("surname"),rs.getString("otherNames"),rs.getInt("regNo"));
}
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_sClassActionPerformed
private void streamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_streamActionPerformed
try {
Connection con = getConnection();
String fetch_row = "SELECT * FROM students where stream=?";
PreparedStatement pst = con.prepareStatement(fetch_row);
pst.setString(1, (String)stream.getSelectedItem());
ResultSet rs = pst.executeQuery();
while(rs.next()) {
Individualclass ic = new Individualclass(rs.getString("firstName"),rs.getString("surname"),rs.getString("otherNames"),rs.getInt("regNo"));
}
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_streamActionPerformed
public void show_student() {
ArrayList<Individualclass> list = new ArrayList<Individualclass>();
DefaultTableModel model = (DefaultTableModel)jTable_Display_Student.getModel();
Object [] row = new Object[13];
for(int i = 0; i < list.size(); i++) {
row[0] = list.get(i).getFirstName();
row[1] = list.get(i).getsurname();
row[2] = list.get(i).getOtherNames();
row[3] = list.get(i).getregNo();
model.addRow(row);
}
}
I want to populate List of tables as a dynamic checkbox using Jframe/Swing in netbeans. The count of table is not known as i am giving USER to select DB as well. Please help, below is code which is for populating list of tables as combo box
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
String dbValue=(String)jComboBox2.getSelectedItem();
String Connection = jTextField1.getText();
String User = jTextField2.getText();
char[] pwd = jPasswordField1.getPassword();
// TODO Auto-generated method stub
//bt2.setEnabled(false);
Object ob=evt.getSource();
if (ob == jButton2)
{
/* String Connection = tf1.getText();
String User = tf2.getText();
char[] pwd = p1.getPassword();*/
System.out.println("**************");
try
{
String passwrd=String.valueOf(pwd);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(Connection,User,passwrd);
Statement st=con.createStatement();
ResultSet rs2= st.executeQuery("SELECT Count(*) FROM DBA_TABLES where owner='"+dbValue+"'");
if(rs2.next()){
count=rs2.getInt(1);
}
generateCheckboxesDynamically(count);
System.out.println("Count="+count);
ResultSet rs1=st.executeQuery("select table_name from dba_tables where owner='"+dbValue+"'");
while(rs1.next())
{
for(int i=1;i<=count;i++){
JCheckBox jCheckBoxMenu=new JCheckBox("check"+i);
jCheckBoxMenu.setText(rs1.getString(1));
add(jCheckBoxMenu);
checks.add(jCheckBoxMenu);
jCheckBoxMenu.setVisible(true);
}
pack();
//JCheckBox ma=new JCheckBox;
String name = rs1.getString(1);
if (name.equals("")) {
jComboBox1.removeAll();
jComboBox1.addItem("");
jComboBox1.setVisible(false);
}
else {
jComboBox1.addItem(rs1.getString(1));
System.out.println(rs1.getString(1));
jComboBox1.setVisible(true);
}
jTextField1.setEnabled(false);
jTextField2.setEnabled(false);
//tf3.setEnabled(false);
jButton1.setEnabled(false);
}
//String dbValue=(String)jComboBox1.getSelectedItem();
System.out.println("Selected DB=="+dbValue);
//bt2.setEnabled(true);
//bt1.removeActionListener(this);
}
catch (Exception ex)
{
System.out.println(ex);
}
}
}
I have a jComboBox that getting data from MySQL server database.
When I add new data to database, the jComboBox doesn't show it, and I must reopen my program to add the new data to jComboBox.
How can I refresh jComboBox data automatically?
This is my code :
private void dataComboBox(){
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop","root","");
Statement stat = con.createStatement();
String sql = "select id from perfume order by id asc";
ResultSet res = stat.executeQuery(sql);
while(res.next()){
Object[] ob = new Object[3];
ob[0] = res.getString(1);
jComboBox5.addItem(ob[0]);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
private void showCBdata(){
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop","root","");
Statement stat = con.createStatement();
String sql = "select name from perfume where id='"+jComboBox5.getSelectedItem()+"'";
ResultSet res = stat.executeQuery(sql);
while(res.next()){
Object[] ob = new Object[3];
ob[0]= res.getString(1);
jTextField8.setText((String) ob[0]);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
//call method
private void jComboBox5ActionPerformed(java.awt.event.ActionEvent evt) {
showCBdata();
}
can you help me?
thank you..
You can do it in this way it will automatically refresh the combobox
try {
comboBox.removeAllItems();
sql = "SELECT * FROM `table_name`";
rs = stmnt.executeQuery(sql);
while (rs.next()) {
String val = rs.getString("column_name");
comboBox.addItem(val);
}
} catch (SQLException ex) {
Logger.getLogger(DefineCustomer.class.getName()).log(Level.SEVERE, null, ex);
}
removeAllItems(); method will clean the combobox to insure that not to repeat values.
You do not need to create a separate Object to add in jComboBox instead you can add String too.
Inzimam Tariq IT's Code (above):
try {
comboBox.removeAllItems();
sql = "SELECT * FROM `table_name`";
rs = stmnt.executeQuery(sql);
while (rs.next()) {
String val = rs.getString("column_name");
comboBox.addItem(val);
}
} catch (SQLException ex) {
Logger.getLogger(DefineCustomer.class.getName()).log(Level.SEVERE, null, ex);
}
I suggest putting all of this code inside an ActionListener. So that each time there the mouse is entered over the comboBox the above code will run. You should do the following:
public void mouseEntered(MouseEvent e) {
//the above code goes here
}
I suggest using a mouseListener:
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
But if you want to look at other ActionListeners you can see them here:
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
Once you add a new registry in the DB, do a removeAllItems comboBox.removeAllItems(); and repopulate de combobox,
My example:
jComboLicorerias.removeAllItems();
try {
Conector = Conecta.getConexion();
Statement St = Conector.createStatement();
try (ResultSet Rs = St.executeQuery(Query)) {
while (Rs.next()) {
jComboLicorerias.addItem(Rs.getString("nombreLicoreria"));
}
St.close();
}
} catch (SQLException sqle) {
JOptionPane.showMessageDialog(null, "Error en la consulta.");
I am having problems inserting data into a postgres table created using java. The created table part of the code works fine, its only when I am inserting values into the table that nothing happens. The code I am using to populate the table tt is:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String txt1 = jTextField1.getText();
int number = Integer.parseInt(txt1);
String name= jTextField2.getText();
String txt3 = jTextField3.getText();
int mean = Integer.parseInt(txt3);
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/tst", "postgres", "21262050");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
String sql = "INSERT INTO tt(noun, max, nbr) VALUES(?, ?, ?)";
PreparedStatement pst = c.prepareStatement(sql);
pst.setString(1, name);
pst.setInt(2,mean );
pst.setInt(3, number);
pst.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(insrt.class.getName()).log(Level.SEVERE, null, ex);
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new insrt().setVisible(true);
}
});
}
You're establishing autocommit to false.
After the auto-commit mode is disabled, no SQL statements are
committed until you call the method commit explicitly.
https://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html#disable_auto_commit
Try executing c.commit() after pst.executeUpdate();
I confused with this if-else because I'm new in Java & MySQL and I tried to make it by myself.
public Menu() {
initComponents();
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/restaurant", "root", "");
System.out.println("ODBC Connection Successful");
showCategory();
} catch (ClassNotFoundException | SQLException e) {
System.out.println("ODBC Connection Failed" + e);
}
}
if - else
private void showCategory() {
try {
Statement stmt;
stmt = con.createStatement();
if (rbMFood.isSelected()) {
ResultSet rs = stmt.executeQuery("SELECT * FROM menu_cat WHERE type_id = 'TY02'");
while (rs.next()) {
cmbMCat.addItem(rs.getString("menu_cat"));
}
} else {
ResultSet rs = stmt.executeQuery("SELECT * FROM menu_cat WHERE type_id = 'TY01'");
while (rs.next()) {
cmbMCat.addItem(rs.getString("menu_cat"));
}
}
} catch (Exception e) {
}
}
Radio Button
private void rbMFoodActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
type = "Food";
}
private void rbMDrinkActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
type = "Drink";
}
And I declare the function in the end of the program
private String type;
When I click drink / food, the category still drink's category.
The database
Any help would be greatly appreciated!
You are using rs.getString("menu_cat") But the format is rs.getString(<Column Name>) But you are using rs.getString(<Table Name>) As "menu_cat" is name of the table and not the name of the column.
AFTER POSTING CONSTRUCTOR
What I see from the code you have posted, is that You have called showCategory() in the constructor. This method is responsible for populating the JComboBox cmbMCat. Now the cmbMCat is being populated when you are creating the new Menu. After that the items list of the cmbMCat does not change.
So, What I suggest is that you call the showCategory() from the rbMFoodActionPerformed and rbMDrinkActionPerformed methods. I hope this will solve your problem.
Also add cmbMCat.removeAllItems() before Statement stmt; to remove all the items that are there in the cmbMCat and reset it with a fresh list of items.
After comment regarding the if-else
Change the showCatagory() as below:
private void showCategory() {
cmbMCat.removeAllItems();
try {
PreparedStatement stmt; //Used Prepared statement
String sql = "SELECT * FROM menu_cat WHERE type_id = ?";
stmt = con.prepareStatement(sql);
if (type.equals("Drink")) {
stmt.setString("TY01");
} else {
stmt.setString("TY02");
}
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
cmbMCat.addItem(rs.getString("menu_cat"));
}
}
} catch (Exception e) {
}
}
Also note that you eventListener code should be:
private void rbMFoodActionPerformed(java.awt.event.ActionEvent evt){
type = "Food";
showCategory();
}
private void rbMDrinkActionPerformed(java.awt.event.ActionEvent evt){
type = "Drink";
showCategory();
}