Edited: I'm editing my question because I found a different tutorial online, and I've progressed better than before,but I'm still having issues.
I'm trying to create an application where I can view, edit, create, or delete data from my MySQL Database table in NetBeans.
I was following this tutorial:
https://www.youtube.com/watch?v=6PvKTg9NXkU
The form comes up, when I click the View button the data from my database table comes up. When I click the Delete button it deletes a row from my database table, and when I click the Add button, an entry is added to my database table. But my Update button doesn't work. It's supposed to allow me to edit a preexisting entry in my database table. But all I get is a dialog window saying it's been updated, but it actually hasn't.
Does anyone know what I did wrong? I don't understand how I can follow tutorials and can have different results.
StoreDB.java code
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package storedatabase;
import javax.swing.JOptionPane;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.swing.table.DefaultTableModel;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Jade
*/
public class StoreDB extends javax.swing.JFrame {
private static final String username = "ctuonline";
private static final String password = "student";
private static final String database = "jdbc:mysql://localhost:3306/store";
Connection sqlCon = null;
PreparedStatement pst = null;
ResultSet rs = null;
int q, i, id, deleteItem;
public StoreDB() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
public void upDateDB()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
sqlCon = DriverManager.getConnection(database,username,password);
pst = sqlCon.prepareStatement("select * from customers");
rs = pst.executeQuery();
ResultSetMetaData stData = rs.getMetaData();
q = stData.getColumnCount();
DefaultTableModel RecordTable = (DefaultTableModel)customerTable.getModel();
RecordTable.setRowCount(0);
while(rs.next())
{
Vector columnData = new Vector();
for (i = 1; i <= q; i++)
{
columnData.add(rs.getString("customerID"));
columnData.add(rs.getString("customerName"));
columnData.add(rs.getString("customerAddress"));
columnData.add(rs.getString("customerCity"));
columnData.add(rs.getString("customerState"));
columnData.add(rs.getString("customerZip"));
}
RecordTable.addRow(columnData);
}
}catch (Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
zipLabel = new javax.swing.JLabel();
idLabel = new javax.swing.JLabel();
nameLabel = new javax.swing.JLabel();
addressLabel = new javax.swing.JLabel();
cityLabel = new javax.swing.JLabel();
stateLabel = new javax.swing.JLabel();
zipField = new javax.swing.JTextField();
idField = new javax.swing.JTextField();
nameField = new javax.swing.JTextField();
addressField = new javax.swing.JTextField();
cityField = new javax.swing.JTextField();
stateField = new javax.swing.JTextField();
deleteButton = new javax.swing.JButton();
updateButton = new javax.swing.JButton();
viewButton = new javax.swing.JButton();
addButton = new javax.swing.JButton();
jPanel4 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
customerTable = new javax.swing.JTable();
jPanel8 = new javax.swing.JPanel();
headerLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
zipLabel.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
zipLabel.setText("Zip:");
jPanel2.add(zipLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 170, 70, 20));
idLabel.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
idLabel.setText("ID:");
jPanel2.add(idLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, 70, 20));
nameLabel.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
nameLabel.setText("Name:");
jPanel2.add(nameLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(19, 50, 70, 20));
addressLabel.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
addressLabel.setText("Address:");
jPanel2.add(addressLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 80, 70, 20));
cityLabel.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
cityLabel.setText("City:");
jPanel2.add(cityLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 110, 70, 20));
stateLabel.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
stateLabel.setText("State:");
jPanel2.add(stateLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 140, 70, 20));
zipField.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
jPanel2.add(zipField, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 170, 120, -1));
idField.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
jPanel2.add(idField, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 20, 120, -1));
nameField.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
jPanel2.add(nameField, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 50, 120, -1));
addressField.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
jPanel2.add(addressField, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 80, 120, -1));
cityField.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
jPanel2.add(cityField, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 110, 120, -1));
stateField.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
jPanel2.add(stateField, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 140, 120, -1));
deleteButton.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
deleteButton.setText("Delete");
deleteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteButtonActionPerformed(evt);
}
});
jPanel2.add(deleteButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 260, 90, -1));
updateButton.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
updateButton.setText("Update");
updateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
updateButtonActionPerformed(evt);
}
});
jPanel2.add(updateButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 260, 90, -1));
viewButton.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
viewButton.setText("View");
viewButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewButtonActionPerformed(evt);
}
});
jPanel2.add(viewButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 220, 90, -1));
addButton.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
addButton.setText("Add");
addButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addButtonActionPerformed(evt);
}
});
jPanel2.add(addButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 220, 90, -1));
jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 100, 240, 320));
jPanel4.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
customerTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ID", "Name", "Address", "City", "State", "Zip"
}
));
customerTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
customerTableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(customerTable);
jPanel4.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 620, 300));
jPanel1.add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 100, 640, 320));
jPanel8.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jPanel8.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
headerLabel.setFont(new java.awt.Font("Verdana", 1, 36)); // NOI18N
headerLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
headerLabel.setText("Store Database Table Customers");
jPanel8.add(headerLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 10, 850, 50));
jPanel1.add(jPanel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, 890, 70));
getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 930, 440));
pack();
setLocationRelativeTo(null);
}// </editor-fold>
private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel RecordTable = (DefaultTableModel)customerTable.getModel();
int SelectedRows = customerTable.getSelectedRow();
try
{
id = Integer.parseInt(RecordTable.getValueAt(SelectedRows, 0).toString());
deleteItem = JOptionPane.showConfirmDialog(null, "Confirm Delete?", "Warning", JOptionPane.YES_NO_OPTION);
if (deleteItem == JOptionPane.YES_OPTION)
{
Class.forName("com.mysql.jdbc.Driver");
sqlCon = DriverManager.getConnection(database, username, password);
pst = sqlCon.prepareStatement("delete from customers where customerID = ?");
pst.setInt(1, id);
pst.executeUpdate();
JOptionPane.showMessageDialog(this, "Record Updated");
upDateDB();
idField.setText("");
idField.requestFocus();
nameField.setText("");
addressField.setText("");
cityField.setText("");
stateField.setText("");
zipField.setText("");
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(StoreDB.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(StoreDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel RecordTable = (DefaultTableModel)customerTable.getModel();
int SelectedRows = customerTable.getSelectedRow();
try
{
id = Integer.parseInt(RecordTable.getValueAt(SelectedRows, 0).toString());
Class.forName("com.mysql.jdbc.Driver");
sqlCon = DriverManager.getConnection(database, username, password);
pst = sqlCon.prepareStatement("update customers set customerName = ?, customerAddress = ?, customerCity = ?, customerState = ?, customerZip = ? where (customerID = ?)");
pst.setString(1, idField.getText());
pst.setString(2, nameField.getText());
pst.setString(3, addressField.getText());
pst.setString(4, cityField.getText());
pst.setString(5, stateField.getText());
pst.setString(6, zipField.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(this, "Record Updated");
upDateDB();
} catch (SQLException ex) {
Logger.getLogger(StoreDB.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(StoreDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void viewButtonActionPerformed(java.awt.event.ActionEvent evt) {
upDateDB();
}
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
try
{
Class.forName("com.mysql.jdbc.Driver");
sqlCon = DriverManager.getConnection(database, username, password);
pst = sqlCon.prepareStatement("insert into customers(customerID,customerName,customerAddress,customerCity,customerState,customerZip) value(?,?,?,?,?,?)");
pst.setString(1, idField.getText());
pst.setString(2, nameField.getText());
pst.setString(3, addressField.getText());
pst.setString(4, cityField.getText());
pst.setString(5, stateField.getText());
pst.setString(6, zipField.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(this, "Record Added");
upDateDB();
} catch (SQLException ex) {
Logger.getLogger(StoreDB.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(StoreDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void customerTableMouseClicked(java.awt.event.MouseEvent evt) {
DefaultTableModel RecordTable = (DefaultTableModel) customerTable.getModel();
int SelectedRows = customerTable.getSelectedRow();
idField.setText(RecordTable.getValueAt(SelectedRows, 0).toString());
nameField.setText(RecordTable.getValueAt(SelectedRows, 1).toString());
addressField.setText(RecordTable.getValueAt(SelectedRows, 2).toString());
cityField.setText(RecordTable.getValueAt(SelectedRows, 3).toString());
stateField.setText(RecordTable.getValueAt(SelectedRows, 4).toString());
zipField.setText(RecordTable.getValueAt(SelectedRows, 5).toString());
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(StoreDB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StoreDB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StoreDB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StoreDB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new StoreDB().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton addButton;
private javax.swing.JTextField addressField;
private javax.swing.JLabel addressLabel;
private javax.swing.JTextField cityField;
private javax.swing.JLabel cityLabel;
private javax.swing.JTable customerTable;
private javax.swing.JButton deleteButton;
private javax.swing.JLabel headerLabel;
private javax.swing.JTextField idField;
private javax.swing.JLabel idLabel;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel8;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField nameField;
private javax.swing.JLabel nameLabel;
private javax.swing.JTextField stateField;
private javax.swing.JLabel stateLabel;
private javax.swing.JButton updateButton;
private javax.swing.JButton viewButton;
private javax.swing.JTextField zipField;
private javax.swing.JLabel zipLabel;
// End of variables declaration
}
NetBeans Output
ant -f C:\\Users\\jades\\Desktop\\Java\\StoreDatabase -Dnb.internal.action.name=run.single -Djavac.includes=storedatabase/StoreDB.java -Drun.class=storedatabase.StoreDB run-single
init:
Deleting: C:\Users\jades\Desktop\Java\StoreDatabase\build\built-jar.properties
deps-jar:
Updating property file: C:\Users\jades\Desktop\Java\StoreDatabase\build\built-jar.properties
Compiling 1 source file to C:\Users\jades\Desktop\Java\StoreDatabase\build\classes
Note: C:\Users\jades\Desktop\Java\StoreDatabase\src\storedatabase\StoreDB.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
compile-single:
run-single:
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
BUILD SUCCESSFUL (total time: 23 seconds)
MySQL database table
You can try to change the String query in getCustomerList() method.
try this: String query = "SELECT * FROM customers";
its work, is because you call in you connection database mysql://localhost:3306/store and you duplicate Table 'store.store.customers'
Related
if i am developing hotel reservation project in netbeans...
if i am having list of rooms in jtable...
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
`enter code here`import javax.swing.table.*;
import net.proteanit.sql.DbUtils;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author ssn
*/
public class welcome extends javax.swing.JFrame {enter code here
/**
* Creates new form welcome
*/
public welcome() {
initComponents();
//fetch();
}
Reservation reservation = new Reservation();
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/loginform?";
String UN = "root";
String PWD = "root";
public void fetch() {
String sql = "select RoomNO,RoomType,BedType,RentPerDay from room";
try {
conn = DriverManager.getConnection("url", "UN", "PWD");
pst = conn.prepareCall(sql);
rs = pst.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
From = new com.toedter.calendar.JDateChooser();
jLabel3 = new javax.swing.JLabel();
To = new com.toedter.calendar.JDateChooser();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
BookDays = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel1.setText("FROM");
jPanel3.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 20, 70, 30));
From.setDateFormatString("yyyy-MM-dd");
jPanel3.add(From, new org.netbeans.lib.awtextra.AbsoluteConstraints(171, 20, 150, 30));
jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel3.setText("TO");
jPanel3.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 20, 50, 30));
To.setDateFormatString("yyyy-MM-dd");
jPanel3.add(To, new org.netbeans.lib.awtextra.AbsoluteConstraints(401, 20, 140, 30));
jButton1.setText("Bookingdays");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel3.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 20, -1, 30));
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"RoomNo", "RoomType", "BedType", "RentPerDay"
}
));
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTable1);
jPanel3.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 97, -1, 370));
jButton2.setText("Check");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jPanel3.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 260, 70, 30));
jButton3.setText("LogOut");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jPanel3.add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 313, -1, 30));
jPanel3.add(BookDays, new org.netbeans.lib.awtextra.AbsoluteConstraints(690, 20, 70, 30));
jLabel2.setIcon(new javax.swing.ImageIcon("C:\\Users\\ssn\\Desktop\\New folder\\diwan3.jpg")); // NOI18N
jPanel3.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 820, 470));
jPanel1.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 820, 470));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
UserLogin UL = new UserLogin();
UL.setVisible(true);
dispose();// TODO add your handling code here:
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
fetch(); // TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(format.format(From.getDate()));
d2 = format.parse(format.format(To.getDate()));
} catch (ParseException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
long diff = d2.getTime() - d1.getTime();
long hours = diff / (60 * 60 * 1000);
long days = hours / 24;
BookDays.setText(Long.toString(days)+" days");
// TODO add your handling code here:
}
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
int index = jTable1.getSelectedRow();
TableModel model = jTable1.getModel();
String RoomNo = model.getValueAt(index,0).toString();
String RoomType = model.getValueAt(index, 1).toString();
String BedType = model.getValueAt(index, 2).toString();
String RentPerDay =model.getValueAt(index,3).toString();
reservation.setVisible(true);
reservation.pack();
reservation.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
reservation.setLocationRelativeTo(null);
reservation.RoomNo.setText(RoomNo);
reservation.RoomType.setText(RoomType);
reservation.BedType.setText(BedType);
reservation.RentPerDay.setText(RentPerDay);
// TODO add your handling code here:
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new welcome().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField BookDays;
private com.toedter.calendar.JDateChooser From;
private com.toedter.calendar.JDateChooser To;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
if i clicked one row it goes to reservation ...if i booked that room for particular days then it again it does not show that room in jtable of welcome page.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the e*/
import javax.swing.*;
/**
*
* #author ssn
*/
public class Reservation extends javax.swing.JFrame {
/**
* Creates new form Reservation
*/
public Reservation() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel2 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
RentPerDay = new javax.swing.JTextField();
BedType = new javax.swing.JTextField();
RoomNo = new javax.swing.JTextField();
RoomType = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jTextField7 = new javax.swing.JTextField();
jTextField8 = new javax.swing.JTextField();
jTextField9 = new javax.swing.JTextField();
NoOfdays = new javax.swing.JTextField();
jTextField11 = new javax.swing.JTextField();
jComboBox2 = new javax.swing.JComboBox<>();
jComboBox3 = new javax.swing.JComboBox<>();
jTextField4 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel2.setText("RESERVATION OF ROOM");
jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 800, 20));
jLabel3.setText("RoomType");
jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 50, 60, 20));
jLabel4.setText("RoomNo");
jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 50, 50, 20));
jPanel1.add(RentPerDay, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 40, 90, 30));
jPanel1.add(BedType, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 40, 100, 30));
jPanel1.add(RoomNo, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 40, 80, 30));
jPanel1.add(RoomType, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 40, 100, 30));
jLabel5.setText("RentPerDay");
jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 50, -1, 20));
jLabel6.setText("BedType");
jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 50, -1, 20));
jLabel7.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jLabel7.setText("CustomerName");
jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 110, 100, 20));
jLabel8.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jLabel8.setText("CustomerID");
jPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 160, 90, 20));
jLabel9.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jLabel9.setText("IDProof");
jPanel1.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 100, 80, 30));
jLabel10.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jLabel10.setText("Proof_No");
jPanel1.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 160, 70, 20));
jLabel11.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jLabel11.setText("Address");
jPanel1.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 200, 50, 30));
jButton1.setText("Logout");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 20, -1, -1));
jLabel12.setFont(new java.awt.Font("Times New Roman", 1, 11)); // NOI18N
jLabel12.setText("City");
jPanel1.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 250, 50, 30));
jLabel13.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jLabel13.setText("State");
jPanel1.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 310, 50, 20));
jLabel14.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jLabel14.setText("NoOfPersons");
jPanel1.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 210, 90, 20));
jLabel15.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jLabel15.setText("Purpose");
jPanel1.add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 340, 80, 20));
jLabel16.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jLabel16.setText("MartialStatus");
jPanel1.add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 360, 110, 20));
jLabel17.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jLabel17.setText("NoOfDays");
jPanel1.add(jLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 280, 80, 20));
jButton2.setText("Book");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jPanel1.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 383, 70, 30));
jPanel1.add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 100, 130, 30));
jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});
jPanel1.add(jTextField2, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 150, 130, 30));
jPanel1.add(jTextField3, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 200, 130, 30));
jPanel1.add(jTextField7, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 90, 120, 30));
jPanel1.add(jTextField8, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 150, 120, 30));
jTextField9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField9ActionPerformed(evt);
}
});
jPanel1.add(jTextField9, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 200, 120, 30));
NoOfdays.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NoOfdaysActionPerformed(evt);
}
});
jPanel1.add(NoOfdays, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 270, 120, 30));
jPanel1.add(jTextField11, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 330, 120, 30));
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select", "Married", "Single", " " }));
jPanel1.add(jComboBox2, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 350, 130, 30));
jComboBox3.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select", "Andhra Pradesh ", "Arunachal Pradesh ", "Assam ", "Bihar", "Chhattisgarh ", "Goa ", "Gujarat ", "Haryana ", "Himachal Pradesh ", "Jammu & Kashmir ", "Jharkhand ", "Karnataka ", "Kerala ", "Madhya Pradesh ", "Maharashtra ", "Manipur ", "Meghalaya ", "Mizoram ", "Nagaland", "Odisha ", "Punjab ", "Rajasthan ", "Sikkim ", "Tamil Nadu ", "Telangana", "Tripura ", "Uttarakhand ", "Uttar Pradesh ", "West Bengal ", " " }));
jPanel1.add(jComboBox3, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 300, 130, 30));
jPanel1.add(jTextField4, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 250, 130, 30));
jLabel1.setBackground(new java.awt.Color(0, 0, 0));
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 51, 204));
jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\ssn\\Desktop\\New folder\\living_room_800.jpg")); // NOI18N
jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 800, 430));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
welcome wl = new welcome();
wl.setVisible(true);
dispose();// TODO add your handling code here:
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// JOptionPane.showInternalMessageDialog(null,"Rooom Booked Sucessfully"); // TODO add your handling code here:
}
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jTextField9ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void NoOfdaysActionPerformed(java.awt.event.ActionEvent evt) {
// String NOofdays = wel.g // TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Reservation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Reservation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Reservation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Reservation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Reservation().setVisible(true);
}
});
}
// Variables declaration - do not modify
public javax.swing.JTextField BedType;
private javax.swing.JTextField NoOfdays;
public javax.swing.JTextField RentPerDay;
public javax.swing.JTextField RoomNo;
public javax.swing.JTextField RoomType;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JComboBox<String> jComboBox2;
private javax.swing.JComboBox<String> jComboBox3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField11;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
private javax.swing.JTextField jTextField7;
private javax.swing.JTextField jTextField8;
private javax.swing.JTextField jTextField9;
// End of variables declaration
}
enter code here
The best way would be to add a Booking table or add a booking Boolean to your room database. When the room is booked skip over that row and do not add it to your table.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
when I try to INSERT RECORD(like username and password) in database on clicking register button it shows error through JOptionPane "java.lang.NullPointerException"...please tell me the solution how to INSERT RECORD**
import java.sql.*;
import javax.swing.*;
public class Newuser extends javax.swing.JInternalFrame {
Connection cn;
PreparedStatement st;
ResultSet rs;
String url,sql;
public Newuser() {
initComponents();
}
public void MyConnection()
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
url="jdbc:sqlserver://localhost;instance=LALLYDB;databaseName=Menu;user=kd;password=123";
cn=DriverManager.getConnection(url); //above instance ,i.e,LALLYDB is DatabaseServer Name
}
catch(Exception ee)
{
JOptionPane.showMessageDialog(this, ee);
}
}
public void Insert_Record(String username,String passwd)
{
try
{
MyConnection(); //calling MyConnection function
st=cn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs=st.executeQuery();
sql="Insert into Project values(?,?)";
st=cn.prepareStatement(sql);
st.setString(1,username);
st.setString(2,passwd);
st.executeUpdate();
JOptionPane.showMessageDialog(this,"Record successfully inserted");
cn.close();
}
catch(Exception ee)
{
JOptionPane.showMessageDialog(this, ee);
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
nlbl1 = new javax.swing.JLabel();
nlbl2 = new javax.swing.JLabel();
ntxt1 = new javax.swing.JTextField();
ntxt2 = new javax.swing.JTextField();
nlbl3 = new javax.swing.JLabel();
nlbl4 = new javax.swing.JLabel();
nlbl5 = new javax.swing.JLabel();
ntxt3 = new javax.swing.JTextField();
ntxt4 = new javax.swing.JTextField();
regitser = new javax.swing.JButton();
jcombo1 = new javax.swing.JComboBox<>();
setClosable(true);
setIconifiable(true);
setMaximizable(true);
setResizable(true);
setTitle("New User Registration");
setPreferredSize(new java.awt.Dimension(488, 425));
setVisible(true);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
nlbl1.setText("Username");
getContentPane().add(nlbl1, new org.netbeans.lib.awtextra.AbsoluteConstraints(84, 44, -1, -1));
nlbl2.setText("Password");
getContentPane().add(nlbl2, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 80, -1, -1));
getContentPane().add(ntxt1, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 40, 140, -1));
getContentPane().add(ntxt2, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 80, 140, -1));
nlbl3.setText("Email-id");
getContentPane().add(nlbl3, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 120, -1, -1));
nlbl4.setText("Hint Question");
getContentPane().add(nlbl4, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 160, -1, -1));
nlbl5.setText("Hint Answer");
getContentPane().add(nlbl5, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 200, -1, -1));
getContentPane().add(ntxt3, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 120, 140, -1));
getContentPane().add(ntxt4, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 200, 140, -1));
regitser.setText("Register");
regitser.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
regitserActionPerformed(evt);
}
});
getContentPane().add(regitser, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 200, -1, -1));
jcombo1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select", "What is your pet name ?", "What is your school name ?", "What is your favourite sport ?" }));
getContentPane().add(jcombo1, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 160, -1, -1));
pack();
}// </editor-fold>
private void regitserActionPerformed(java.awt.event.ActionEvent evt) {
Insert_Record(ntxt1.getText(),ntxt2.getText());
}
// Variables declaration - do not modify
private javax.swing.JComboBox<String> jcombo1;
private javax.swing.JLabel nlbl1;
private javax.swing.JLabel nlbl2;
private javax.swing.JLabel nlbl3;
private javax.swing.JLabel nlbl4;
private javax.swing.JLabel nlbl5;
private javax.swing.JTextField ntxt1;
private javax.swing.JTextField ntxt2;
private javax.swing.JTextField ntxt3;
private javax.swing.JTextField ntxt4;
private javax.swing.JButton regitser;
// End of variables declaration
}
The error you get through JOptionPane contains a linenumber, where the Exception occurs (you are catching it and showing it). Either look that linenumber in the MessageDialog up and see what line is the reason, or type ee.printStackTrace() inside the catch-blocks and you can then see the statement throwing the Exception. Also at st=cn.prepareStatement(sql,...); the variable sql has not been set, is this intentional ?
NullPointerException in general means, that you are trying to access a variable that hasn't been initialized before.
I have made a JFrame and I defined a background image using a JLabel. But, as soon as I enlarge the JFrame everything gets dislocated. How can I build my JFrame so it can be resizable?
public class First extends javax.swing.JFrame {
/**
* Creates new form First
*/
public First() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
t1 = new javax.swing.JTextField();
t2 = new javax.swing.JPasswordField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("WELCOME");
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jButton1.setFont(new java.awt.Font("Segoe Script", 3, 24)); // NOI18N
jButton1.setText("LOGIN");
jButton1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton1.setContentAreaFilled(false);
jButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 310, 140, 30));
jLabel1.setFont(new java.awt.Font("Viner Hand ITC", 3, 36)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Administrator of Library System");
getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 614, -1));
t1.setFont(new java.awt.Font("Segoe UI", 3, 20)); // NOI18N
t1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
t1.setOpaque(false);
t1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
t1ActionPerformed(evt);
}
});
getContentPane().add(t1, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 200, 180, 30));
t2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
t2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
t2.setOpaque(false);
getContentPane().add(t2, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 250, 180, 30));
jLabel2.setFont(new java.awt.Font("Segoe Script", 3, 24)); // NOI18N
jLabel2.setText("Username -");
getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 200, 200, 30));
jLabel3.setFont(new java.awt.Font("Segoe Script", 3, 24)); // NOI18N
jLabel3.setText("Password -");
getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 250, 230, 30));
jButton2.setFont(new java.awt.Font("Segoe Script", 3, 24)); // NOI18N
jButton2.setText("Forgot Password ??");
jButton2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton2.setContentAreaFilled(false);
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 410, 250, 40));
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/librarymanagementsystem/library_book.jpg"))); // NOI18N
jLabel4.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED));
getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(-10, -10, 880, 500));
pack();
setLocationRelativeTo(null);
}// </editor-fold>
private void t1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try
{
Class.forName("java.sql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "parin");
Statement stmt=con.createStatement();
String username="";
String password="";
String query="Select * from Liblogin;";
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
username=rs.getString("username");
password=rs.getString("password");
}
rs.close();
stmt.close();
con.close();
String enteredUsername=t1.getText().toString();
String enteredPassword = new String(t2.getText());
if(enteredUsername.contentEquals(username)&&enteredPassword.contentEquals(password))
{
Homepage a=new Homepage();
a.setVisible(true);
this.dispose();
}
else
{
JOptionPane.showMessageDialog(this,"INVALID USER");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, "ERROR IN CORRECTION");
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
this.dispose();
Security a=new Security();
a.setVisible(true);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(First.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(First.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(First.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(First.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new First().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JTextField t1;
private javax.swing.JPasswordField t2;
// End of variables declaration
}
Use GridBagLayout as your layout manager and take time to look at the preferredSize, minimumSize and maximumSize properties of components.You can also use Box.Filler class to create Invisible components and add them between the components in your JPanel when the window is resized.I can't help you any further since I don't know what do you exactly want the components to behave like.I recommend you reading the book Swing , chapter 4 is for you
I'm currently working on a invoice generation/bill printing system for a industry.
I need a code which print the text as well as the image logo of company.
Here I'm giving a code of JFrame I have created and I need a print code which print both the text and images by fetching data from SQL 2008 server as backend.
here its is a code of netbeans frame
here i need action implementation on Print Button below:
plz help me soon providing a appropriate way to print text and image.
package invoice2;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.HeadlessException;
import java.awt.image.BufferedImage;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import java.awt.print.*;
import java.awt.print.PageFormat;
import javax.swing.JTextPane;
import java.awt.print.PrinterException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.Sides;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
*
* #author Admin Param
*/
public class generate extends javax.swing.JInternalFrame {
/**
* Creates new form generate
*/
public generate() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jSeparator1 = new javax.swing.JSeparator();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
t7 = new javax.swing.JTextField();
t1 = new javax.swing.JTextField();
t2 = new javax.swing.JTextField();
t3 = new javax.swing.JTextField();
t5 = new javax.swing.JTextField();
t6 = new javax.swing.JTextField();
t4 = new javax.swing.JScrollPane();
t9 = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
d1 = new com.toedter.calendar.JDateChooser();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
logo = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
print = new javax.swing.JButton();
jSeparator2 = new javax.swing.JSeparator();
jLabel10 = new javax.swing.JLabel();
setClosable(true);
setIconifiable(true);
setMaximizable(true);
setResizable(true);
setTitle("Generate Bill/Print Invoice");
setToolTipText("");
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel1.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, -18, 490, 20));
jLabel1.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
jLabel1.setText("No. Of Item :");
jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(35, 20, 90, -1));
jLabel2.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
jLabel2.setText("Price of Item :");
jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(35, 60, 90, -1));
jLabel3.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
jLabel3.setText(" Tex :");
jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 280, -1, 30));
jLabel4.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
jLabel4.setText("Invoice No :");
jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(41, 90, 80, 21));
jLabel5.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
jLabel5.setText(" Billing Address :");
jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 130, -1, 21));
jLabel6.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
jLabel6.setText(" Sub Total :");
jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 240, 80, 30));
jLabel8.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
jLabel8.setText(" Total :");
jPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 330, -1, -1));
jLabel9.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
jLabel9.setText(" Date :");
jPanel1.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 210, -1, -1));
t7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
t7ActionPerformed(evt);
}
});
jPanel1.add(t7, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 320, 140, 30));
t1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
t1ActionPerformed(evt);
}
});
jPanel1.add(t1, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 10, 140, 30));
t2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
t2ActionPerformed(evt);
}
});
jPanel1.add(t2, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 50, 140, 30));
t3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
t3ActionPerformed(evt);
}
});
jPanel1.add(t3, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 90, 140, 30));
t5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
t5ActionPerformed(evt);
}
});
jPanel1.add(t5, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 240, 140, 30));
t6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
t6ActionPerformed(evt);
}
});
jPanel1.add(t6, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 280, 140, 30));
t9.setColumns(20);
t9.setRows(5);
t4.setViewportView(t9);
jPanel1.add(t4, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 130, 180, 60));
jButton1.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
jButton1.setText("Generate Total");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 310, 150, 40));
jPanel1.add(d1, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 200, 160, 30));
jButton4.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
jButton4.setText("Generate SubTotal");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jPanel1.add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 230, 150, 40));
jButton5.setText("image ");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jPanel1.add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 10, 100, 40));
logo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/invoice2/big.jpg"))); // NOI18N
jPanel1.add(logo, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 70, 130, 130));
getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 510, 360));
jLabel7.setText(" Tex :");
getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 180, -1, 21));
jButton2.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jButton2.setText("Exit");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 410, 120, 40));
jButton3.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jButton3.setText("Save ");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
getContentPane().add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 410, 120, 40));
print.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
print.setText("Print ");
print.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
printActionPerformed(evt);
}
});
getContentPane().add(print, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 410, 130, 40));
getContentPane().add(jSeparator2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 18, 480, 10));
jLabel10.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jLabel10.setText(" Welcome To Invoice Print/Bill Generator Software By ArtSheoran");
getContentPane().add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 0, 510, 20));
pack();
}// </editor-fold>
private void t7ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void t1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void t2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void t3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void t5ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void t6ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
dispose(); // TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
#SuppressWarnings("empty-statement")
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=invoice;integratedSecurity=true";
Connection con = DriverManager.getConnection(connectionUrl);
PreparedStatement pstmt=con.prepareStatement("insert into record values(?,?,?,?,?,?,?,?)");
int f1=Integer.parseInt(t1.getText());
pstmt.setInt(1,f1);
int f2=Integer.parseInt(t2.getText());
pstmt.setInt(2,f2);
int f3=Integer.parseInt(t3.getText());
pstmt.setInt(3,f3);
pstmt.setString(4,t9.getText());
java.util.Date date=d1.getDate();
String d=String.format("%1$tm-%1$td-%1$ty",date);
pstmt.setString(5,d);
int f4=Integer.parseInt(t5.getText());
pstmt.setInt(6,f4);
int f5=Integer.parseInt(t6.getText());
pstmt.setInt(7,f5);
int f6=Integer.parseInt(t7.getText());
pstmt.setInt(8,f6);
pstmt.executeUpdate();
JOptionPane.showMessageDialog(null,"record saved successfully");
}
catch(ClassNotFoundException | SQLException | NumberFormatException | HeadlessException ob)
{
JOptionPane.showMessageDialog(null, ob.toString());
} // TODO add your handling code here:
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
int nitem=Integer.parseInt(t1.getText());
int price=Integer.parseInt(t2.getText());
int s=nitem*price;
t5.setText(Integer.toString(s));// TODO add your handling code here:
}
private void printActionPerformed(java.awt.event.ActionEvent evt) {
// here need a action under print button for text and image printing.
}
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=invoice;integratedSecurity=true";
Connection con = DriverManager.getConnection(connectionUrl);
PreparedStatement pstmt=con.prepareStatement("insert into saveimage values(?,?,?,?)");
pstmt.setString(1,"mahendra");
pstmt.setString(2,"Delhi");
pstmt.setString(4,"123456");
JFileChooser chooser = new JFileChooser();
String str="";
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File ob=chooser.getSelectedFile();
str=ob.getPath();
Icon img = new ImageIcon(str);
logo.setIcon(img);
pstmt.setString(3, str);
//executeUpdate() method execute specified sql query. Here this query
//insert data and image from specified address.
int s = pstmt.executeUpdate();
if(s>0) {
JOptionPane.showMessageDialog(null, "File Uploaded Sucessfully");;
}
else {
JOptionPane.showMessageDialog(null, "File Not uploaded a error has been occured");
}
}
}
catch (ClassNotFoundException | SQLException | HeadlessException ex) {
System.out.println("Found some error : "+ex);
} // TODO add your handling code here:
}
// Variables declaration - do not modify
private com.toedter.calendar.JDateChooser d1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JLabel logo;
private javax.swing.JButton print;
private javax.swing.JTextField t1;
private javax.swing.JTextField t2;
private javax.swing.JTextField t3;
private javax.swing.JScrollPane t4;
private javax.swing.JTextField t5;
private javax.swing.JTextField t6;
private javax.swing.JTextField t7;
private javax.swing.JTextArea t9;
// End of variables declaration
private static class OutputPrinter implements Printable {
public OutputPrinter(String printData) {
}
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
Plz help me soon and write appropriate guide.to implement action of printing text and image from a JInternal Frame and using SQL Server 2008.
a good answer is awaited.
You can define HTML and set it to JTextPane. Then print the JTextPane's content.
If you need multi page printing see http://java-sl.com/JEditorPanePrinter.html
this is the class who i use to load the images, i use the constructor to call the metod load who load the images in the array percorso.
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
class Track extends Component {
Image[] percorso;
String path;
int n;
int x;
int y;
public Track(String path, int n) {
int i;
this.path = path;
this.n = n;
this.percorso = new Image[n];
for (i = 0; i < n; i++) {
this.percorso[i] = load(path, n, i);
repaint();
}
}
public final Image load(String path, int n, int i) {
Toolkit tool = Toolkit.getDefaultToolkit();
String dot = ".jpg";
path = this.path;
path = path + Integer.toString(i) + dot;
Image img = tool.getImage(path);
try {
MediaTracker track = new MediaTracker(this);
track.addImage(img, 0);
track.waitForID(0);
} catch (InterruptedException e) {
System.out.println("Image not loaded");
}
return (img);
}
#Override
public void paint(Graphics g) {
int i;
g.drawImage(percorso[1], x, y, this);
}
}
This is the class where i create the gui, and i try to add the images to the jlayeredpane, but it's didn't work.
public class Gui extends javax.swing.JFrame {
/** Creates new form GUI */
public Gui() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
background = new javax.swing.JLayeredPane();
testata = new javax.swing.JLabel();
nuova = new javax.swing.JLabel();
selectrack = new javax.swing.JLabel();
track1 = new javax.swing.JLabel();
track2 = new javax.swing.JLabel();
track3 = new javax.swing.JLabel();
track4 = new javax.swing.JLabel();
track5 = new javax.swing.JLabel();
track5.setVisible(false);
track6 = new javax.swing.JLabel();
track6.setVisible(false);
track7 = new javax.swing.JLabel();
track7.setVisible(false);
track8 = new javax.swing.JLabel();
track8.setVisible(false);
track9 = new javax.swing.JLabel();
track9.setVisible(false);
track10 = new javax.swing.JLabel();
track10.setVisible(false);
behind = new javax.swing.JLabel();
behind.setVisible(false);
traccy = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
testata.setFont(new java.awt.Font("Tahoma", 0, 36));
testata.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
testata.setText("Thosa Racing");
testata.setBounds(90, 0, 220, 44);
background.add(testata, javax.swing.JLayeredPane.DEFAULT_LAYER);
nuova.setFont(new java.awt.Font("Tahoma", 0, 18));
nuova.setText("Nuova");
nuova.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
nuovaMouseClicked(evt);
}
});
nuova.setBounds(160, 140, 50, 22);
background.add(nuova, javax.swing.JLayeredPane.DEFAULT_LAYER);
selectrack.setVisible(false);
selectrack.setFont(new java.awt.Font("Tahoma", 0, 24));
selectrack.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
selectrack.setText("Scegli il tracciato");
selectrack.setBounds(110, 10, 177, 29);
background.add(selectrack, javax.swing.JLayeredPane.DEFAULT_LAYER);
track1.setVisible(false);
track1.setFont(new java.awt.Font("Tahoma", 0, 24));
track1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
track1.setText("1");
track1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
track1MouseClicked(evt);
}
});
track1.setBounds(50, 50, 13, 29);
background.add(track1, javax.swing.JLayeredPane.DEFAULT_LAYER);
track2.setVisible(false);
track2.setFont(new java.awt.Font("Tahoma", 0, 24));
track2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
track2.setText("2");
track2.setBounds(120, 50, 13, 29);
background.add(track2, javax.swing.JLayeredPane.DEFAULT_LAYER);
track3.setVisible(false);
track3.setFont(new java.awt.Font("Tahoma", 0, 24));
track3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
track3.setText("3");
track3.setBounds(190, 50, 13, 29);
background.add(track3, javax.swing.JLayeredPane.DEFAULT_LAYER);
track4.setVisible(false);
track4.setFont(new java.awt.Font("Tahoma", 0, 24));
track4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
track4.setText("4");
track4.setBounds(250, 50, 13, 29);
background.add(track4, javax.swing.JLayeredPane.DEFAULT_LAYER);
track5.setFont(new java.awt.Font("Tahoma", 0, 24));
track5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
track5.setText("5");
track5.setBounds(320, 50, 13, 29);
background.add(track5, javax.swing.JLayeredPane.DEFAULT_LAYER);
track6.setFont(new java.awt.Font("Tahoma", 0, 24));
track6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
track6.setText("6");
track6.setBounds(50, 110, 13, 29);
background.add(track6, javax.swing.JLayeredPane.DEFAULT_LAYER);
track7.setFont(new java.awt.Font("Tahoma", 0, 24));
track7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
track7.setText("7");
track7.setBounds(120, 110, 13, 29);
background.add(track7, javax.swing.JLayeredPane.DEFAULT_LAYER);
track8.setFont(new java.awt.Font("Tahoma", 0, 24));
track8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
track8.setText("8");
track8.setBounds(190, 110, 13, 29);
background.add(track8, javax.swing.JLayeredPane.DEFAULT_LAYER);
track9.setFont(new java.awt.Font("Tahoma", 0, 24));
track9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
track9.setText("9");
track9.setBounds(250, 110, 13, 29);
background.add(track9, javax.swing.JLayeredPane.DEFAULT_LAYER);
track10.setFont(new java.awt.Font("Tahoma", 0, 24));
track10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
track10.setText("10");
track10.setBounds(320, 110, 26, 29);
background.add(track10, javax.swing.JLayeredPane.DEFAULT_LAYER);
behind.setFont(new java.awt.Font("Tahoma", 0, 18));
behind.setText("Behind");
behind.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
behindMouseClicked(evt);
}
});
behind.setBounds(10, 260, 54, 22);
background.add(behind, javax.swing.JLayeredPane.DEFAULT_LAYER);
traccy.setBounds(0, 0, 400, 300);
background.add(traccy, javax.swing.JLayeredPane.DEFAULT_LAYER);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING).addComponent(background,
javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE));
layout.setVerticalGroup(layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING).addComponent(background,
javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE));
pack();
}// </editor-fold>
private void nuovaMouseClicked(java.awt.event.MouseEvent evt) {
// Disabilita menu principale
byte d = 1;
disable(d);
}
private void behindMouseClicked(java.awt.event.MouseEvent evt) {
// Torna al menu principale
byte d = 2;
disable(d);
}
private void track1MouseClicked(java.awt.event.MouseEvent evt) {
trackMDisable(false);
Track tracciato1 = new Track("src/track/m", 5);
background.add(tracciato1);
}
// Metodo dis/able menu
public void disable(byte i) {
boolean d = false;
switch (i) {
case 1: {
// Dal menu principale alla lista tracciati
d = true;
principalMDisable(d);
trackMDisable(d);
}
case 2: {
// Dalla lista tracciati al menu principale
trackMDisable(d);
principalMDisable(d);
}
}
}
public void principalMDisable(Boolean b) {
if (b == true) {
// se vero disable il menu principale
testata.setVisible(false);
nuova.setVisible(false);
} else {
// se falso able il menu principale
testata.setVisible(true);
nuova.setVisible(true);
}
}
public void trackMDisable(Boolean b) {
if (b == true) {
// se vero able la lista dei tracciati
selectrack.setVisible(true);
track1.setVisible(true);
track2.setVisible(true);
track3.setVisible(true);
track4.setVisible(true);
track5.setVisible(true);
track6.setVisible(true);
track7.setVisible(true);
track8.setVisible(true);
track9.setVisible(true);
track10.setVisible(true);
behind.setVisible(true);
} else {
// se falso disable la lista dei tracciati
selectrack.setVisible(false);
track1.setVisible(false);
track2.setVisible(false);
track3.setVisible(false);
track4.setVisible(false);
track5.setVisible(false);
track6.setVisible(false);
track7.setVisible(false);
track8.setVisible(false);
track9.setVisible(false);
track10.setVisible(false);
behind.setVisible(false);
}
}
// Variables declaration - do not modify
private javax.swing.JLayeredPane background;
private javax.swing.JLabel behind;
private javax.swing.JLabel nuova;
private javax.swing.JLabel selectrack;
private javax.swing.JLabel testata;
private javax.swing.JLabel traccy;
private javax.swing.JLabel track1;
private javax.swing.JLabel track10;
private javax.swing.JLabel track2;
private javax.swing.JLabel track3;
private javax.swing.JLabel track4;
private javax.swing.JLabel track5;
private javax.swing.JLabel track6;
private javax.swing.JLabel track7;
private javax.swing.JLabel track8;
private javax.swing.JLabel track9;
// End of variables declaration}
}
i don't receive any compiler error, i think the error is in the Gui class where i add the images, in the metod track1MouseClicked, i use the JFrom plugin of NetBeans 7.01 for create the frame and company.
I haven't gone through all of your code, but this will cause problems:
public final Image load(String path, int n, int i) {
Toolkit tool = Toolkit.getDefaultToolkit();
String dot = ".jpg";
path = this.path; // *****
Since you don't really set the path field here. You'll want to reverse that line.
More importantly, you'll want to try to solve your problem in a much smaller simpler program first, a test program that does nothing but read in a bunch of images and displays them, but does nothing else. Then once you have that solved use the code in your larger program. The other benefit is that if your smaller program doesn't work, you can then post it here as a more reasonably sized program that more folks will be willing to read, analyze, test and correct.
Also, don't mix AWT components such as Component with Swing components unless absolutely necessary -- which isn't the case with your program.