Custom JtextField proprety [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I've created a custom JtextField but any proprety defined method don't working like getText or SetText when I call it in the main JFrame.
import javax.swing.JTextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class JTextFieldDecimal extends JTextField {
private static final long serialVersionUID = 1L;
public JTextFieldDecimal()
{
super();
addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
char c =e.getKeyChar();
if(!((c>='0') && (c<='9') ||
(c==KeyEvent.VK_BACK_SPACE) ||
(c==KeyEvent.VK_DELETE)))
{
getToolkit().beep();
e.consume();
}
}
});
}
}
when I click in validation button in jframe Produit the compiler give me an error and point to line 98 wich content my statement parameter of Custom JtextField named txtPrixHT.
btnValider.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Connection cn=null;
PreparedStatement pst =null;
ResultSet rs=null;
try {
Class.forName("com.mysql.jdbc.Driver");
cn=DriverManager.getConnection("jdbc:mysql://localhost/gesticom", "root","");
//String sqlAdd ="insert into produit (PrCodeBarre,PrDesignation,PrPrixHT,PrRemise,PrPrixAchat,PrStockAlerte,PrStockReel) values (?,?,?,?,?,?,?)";
String sqlAdd ="insert into produit (PrCodeBarre,PrDesignation,PrPrixHT) values (?,?,?)";
pst=cn.prepareStatement(sqlAdd,Statement.RETURN_GENERATED_KEYS);
pst.setString(1, txtCodebarre.getText());
pst.setString(2, txtDesignation.getText());
pst.setString(3,txtPrixHT.getText());
pst.execute();
rs=pst.getGeneratedKeys();
if(rs.next())
{
txtIdprod.setText(rs.getString(1));
JOptionPane.showMessageDialog(null, "Nouveau Produit créé", "Fournisseur",JOptionPane.INFORMATION_MESSAGE);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try
{
cn.close();
pst.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
});

For an alternative to your formatted text field, I would propose you don't try to validate the input yourself. You can use a JFormattedTextField that allow you to do it for you when the focus is lost. Here is a quick sample
JFormattedTextField decimalTxt = new JFormattedTextField(
new NumberFormatter()
);
This will use the Locale of the JVM to format the number like expected (simpler for Decimal values). If you want only to take integers, provide an integer format
JFormattedTextField decimalTxt = new JFormattedTextField(
new NumberFormatter(
NumberFormat.getIntegerInstance()
)
);
You want to always have two decimal digit like 5.00, define it in the NumberFormat :
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits(2);
JFormattedTextField decimalTxt = new JFormattedTextField(
new NumberFormatter(nf)
);
You can find more information about this on How to Use Formatted Text Fields

Related

How to destroy a frame by clicking on a button?

I want to destroy the frame by clicking on a button. I searched everywhere and it seems that I'm doing this right. but it is not working.
public class LoginWindow {
public void CreateLoginWindow () {
/** Set Style to Main Frame **/
JFrame main_window = new JFrame();
main_window.setUndecorated(true);
main_window.setLocationRelativeTo(null);
main_window.setLayout(new BorderLayout());
main_window.setLayout(new FlowLayout());
main_window.setVisible(false);
main_window.setContentPane(new JLabel(new ImageIcon("images/MainWindow-bg.jpg")));
main_window.setExtendedState(JFrame.MAXIMIZED_BOTH);
main_window.setSize(1920,1080);
main_window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/** Some Codes **/
JButton login_button = new JButton("Click to Exit");
login_button.setBounds(920,480,120,45);
/** Login Button Action **/
login_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ValidateLogin validateLogin = new ValidateLogin();
Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText());
main_window.dispose();
}
});
main_window.add(login_button);
main_window.setVisible(true);
}
}
It seems ValidateLogin validateLogin = new ValidateLogin(); Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText()); make some problems.
And this is my ValidateLogin Class :
public class ValidateLogin {
public Boolean ValidateLoginAction (String username, String password){
ConnectToDB validate_login = new ConnectToDB();
String right_password = validate_login.GetPassOfAnUsername(username);
if ( right_password.equals(password) ){
return true;
} else {
return false;
}
}
}
And this is my ConnectToDB Class :
public class ConnectToDB {
/** Connect to Database **/
private Connection connect() {
String url = "jdbc:sqlite:E://Resturant Project/db/Resturant.db";
Connection connection = null;
try {
connection = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return connection;
}
/** Get Password of an Username **/
public String GetPassOfAnUsername(String username){
String password = "SELECT Password FROM Person WHERE UserName = '" + username +"'";
try (Connection connection = this.connect();
PreparedStatement statement= connection.prepareStatement(password);
ResultSet results = statement.executeQuery()) {
return results.getString("Password");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return null;
}
}
And this is my MainWindow Class :
public class MainWindow {
public static void main(String[] args) {
LoginWindow loginWindow = new LoginWindow();
loginWindow.CreateLoginWindow();
}
}
I have tried and I am able to close the window and jvm exits also. I provide below the button action code snippet.
login_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
ValidateLogin validateLogin = new ValidateLogin();
Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText());
}
catch(Exception ex) {
//handle exception
}
finally {
main_window.dispose();
}
}
});
Have the username_field and password_field variables been instantiated somewhere? Perhaps the line where you are accessing the getText() method is throwing a NullPointerException when the actionPerformed method is being called and so the program never reaches the main_window.dispose() line.
Try checking if both of those variables are null when the actionPerformed method is being executed before you try to access the getText() method from them.
On a further note, check if the connection the database is being established successfully.
ConnectToDB validate_login = new ConnectToDB();
String right_password = validate_login.GetPassOfAnUsername(username);
The second line might also throw a NullPointerException in case validate_login is null because your code will return null from your ConnectToDB() constructor in case the connection fails.

Object creation for two different classes throws StackOverflow in java

I have been struggling with this problem for a while where I have two classes namely OrderSearch.java(main class) and CreateOrder.java. I have a JTable on my main class and when a row is doubleclicked it opens a new frame i.e CreateOrder.java with values from jTablein different textfields. I have a SaveButton in CreateOrder.java that saves the changes made in the class and shows it JTable again.
However the problem is I cannot perform refresh table operation i.e some sql queries when the SaveButton is clicked. I want the table in frame OrderSearch is refreshed when the savebutton on CreateOrder is clicked
Problems: Creating an object for class OrderSearch.java in CreateOrder.java gives me a stackoverflow error. Creating an object in the Savebutton opens a whole new frame again.
OrderSearch.java
public class OrderSearch extends CreateOrder{
//declarations for label,text, and buttons
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
OrderSearch window = new OrderSearch();
window.frmXraymanager.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public OrderSearch () { *Stack overflow error here*
initialize();
}
private void initialize() {
table = new JTable();
scrollPane.setViewportView(table);
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e2) {
if (e2.getClickCount() == 2 && !e2.isConsumed()) {
e2.consume();
try{
int index = table.getSelectedRow();
String table_Click = table.getModel().getValueAt(table.convertRowIndexToModel(index), 0).toString();
String sql = "SELECT ID, Date, Place, UserName FROM TEST.dbo.Intern WHERE ID = '"+table_Click+"'";
PreparedStatement pst = connection.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
if(rs.next()){
String id = rs.getString("ID");
String date = rs.getString("Date").toString();
String place = rs.getString("Place");
String uname = rs.getString("UserName");
frameCreate.setVisible(true); //Frame from CreateOrder.java
Number.setText(id); // textfields from CreateOrder.java
String date1 = startDate;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date date2 = df.parse(date1);
dateChooser.setDate(date2);
jobSite.setText(place);
uName.setText(uname);
Component.setText(component);
Remarks.setText(remarks);
rs.close();
pst.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
}
});
}
public void refresh()
{
query1 = "SELECT * FROM Test.dbo.Intern;
try(PreparedStatement pst = connection.prepareStatement(query1);
ResultSet rs = pst.executeQuery();){
table.setModel(DbUtils.resultSetToTableModel(rs));
table.setRowHeight(40);
}
catch(Exception e){
e.printStackTrace();
}
}
}
CreateOrder.java
public class CreateOrder {
public CreateOrder () {
initialize();
}
OrderSearch one = new OrderSearch(); *Stack overflow error here*
private void initialize() {
button_Save = new JButton("Save");
button_Save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
*would like to add refresh() here*
}
});
}
}
How should I create an object of OrderSearch in CreateOrder to acces the method refresh() without opening the frame again?
Thanks in advance!
-Ajay
EDIT:
Actually the error is in
OrderSearch one = new OrderSearch();
and public OrderSearch () I totally understand it makes sense because it goes into infinite loop when I call an Object in CreateOrder.java. But is there any way to access the contents of OrderSearch.java in CreateOrder.java without getting the stackoverflow error or opening the whole new frame OrderSearch.java again?
No, there is no way to do it assuming your current setup. This leads us to the conclusion that you need to refactor the code. The main problem is that your code has no way to execute the required db command without creating a frame. You will need to separate the engine from the ui. You will need to be able to execute business logic without being tied to a UI event. The UI should be a user of the business logic, not its wrapper. You will need to move all your business logic into separate class(es) and call the relevant methods from the ui at the appropriate places and events.

Error getting value from jdatechooser and adding it to database java

How can I show jcalender?
How to get the selected value from it and add it to database?
From google I found a file called jcalender-1.4. I've added it to the jframe but when I try to get selected value from it and add it to the database it shows error. Table is created but error shows while inserting values. The exception in insertion method is shown. I've tried to print the value the value of db9 by commenting the insertData method and it shows null. Below is the link of JCalender jar file that i've used.
https://www.dropbox.com/s/yxe86ylfm4u6be8/jcalendar-1.4.jar?dl=0
JButton btnNewButton = new JButton("New Reservation");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
db1=textField.getText();
db2=textField_1.getText();
db3=textField_2.getText();
db4=textField_3.getText();
db5=textField_4.getText();
db6=textField_5.getText();
db7=textField_6.getText();
db8=(String)comboBox.getSelectedItem();
db9=dateChooser.getDate();
db10=textField_7.getText();
db11=(String)comboBox_1.getSelectedItem();
db12=(String)comboBox_2.getSelectedItem();
db13=dateChooser_1.getDate();
db14=dateChooser_2.getDate();
try {
insertData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public static void createTable() throws Exception{
try{
Connection con=getConnection();
PreparedStatement create =con.prepareStatement("CREATE TABLE IF NOT EXISTS hotelDetails(_id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,name varchar(65),"
+ "surname varchar(65),address varchar(65),cnic varchar(65),mobileNo varchar(65),email varchar(65),city varchar(65),gender varchar(65),dob Date,country varchar(65),roomType varchar(65),"
+ "roomNo varchar(65),checkin Date,checkout Date)");
create.executeUpdate();
System.out.println("Table Created");
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Table Not Created.Try Again","Error", JOptionPane.ERROR_MESSAGE);
}
} public static void insertData() throws Exception{
try{
Connection con=getConnection();
PreparedStatement posted=con.prepareStatement("INSERT INTO hotelDetails(name,surname,address,cnic,mobileNo,email,city,gender,dob,country,roomType,roomNo,checkin,checkout)VALUES('"+db1+"','"+db2+"','"+db3+"','"+db4+"','"+db5+"','"+db6+"','"+db7+"','"+db8+"','"+db9+"','"+db10+"','"+db11+"','"+db12+"','"+db13+"','"+db14+"')");
posted.executeUpdate();
System.out.println("Values Inserted");
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Can't Insert Data","Error", JOptionPane.ERROR_MESSAGE);
}
}

Issue implementing embedded Derby database in eclipse project?

I'm trying to create a table, insert into the table and print the contents of the table using Derby (as shown below).
TestProject class:
package com.user.DerbyTest;
public class TestProject {
public static void main(String[] args) {
DBConnection db = new DBConnection();
db.createTable();
db.insertIntoTable("todd", 23, 'M');
db.insertIntoTable("wayne", 54, 'M');
db.printAll();
}
}
DBConnection class:
package com.user.DerbyTest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBConnection {
private static final String DRIVER = "org.apache.derby.jdbc.*";
private static final String JDBC_URL = "jdbc:derby:derbytest;create=true";
Connection conn;
public DBConnection(){
try {
this.conn = DriverManager.getConnection(JDBC_URL);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (this.conn != null){
System.out.println("Connected to database.");
}
}
public void createTable(){
try {
conn.createStatement().execute("Create TABLE MyDerbytable(Name varchar(50), Age INT, Gender char(1))");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void insertIntoTable(String name, int age, char gender){
try {
conn.createStatement().execute("INSERT INTO MyDerbytable Values ("+name+","+age+","+gender+")");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void printAll(){
try {
Statement statement = this.conn.createStatement();
ResultSet res = statement.executeQuery("Select * FROM MyDerbytable");
while(res.next()){
System.out.println(res.getString("Name") + res.getString("Age") + res.getString("Gender"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm getting a whole plethra of errors when trying to to run this:
Any ideas?
EDIT: Changing to DROP errors:
Your table already exits. Try DROP TABLE myderbytable;
Your first INSERT statement will end up being:
INSERT INTO MyDerbytable Values (todd,23,M)
You have no quotes around the todd and M values so there are treated as references to column names giving you the error you see. You must enclose literal values like this in single quotes:
INSERT INTO MyDerbytable Values ('todd',23,'M')
So your insert code might be:
"INSERT INTO MyDerbytable Values ('"+name+"','"+age+"','"+gender+"')"
(Note extra ' characters).
But concatenating strings like you are doing leaves you wide open to SQL Injection Attacks. It will also give you problems if any of your input contains a quote character. Learn about using PreparedStatement.

Getting NullpointerException in JDBC code

The following code is throwing a NullPointerException - I don't know where the problem is. I am using an Excel spreadsheet as a backend.
//actionlistener for btnfetch
btnfetch.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
try
{
String name="";
d1 = (java.util.Date)formatter.parse(textdate.getText());
java.sql.Date sqlDate = new java.sql.Date(d1.getTime());
java.sql.Date sqld=null;
ResultSet rs=st.executeQuery("select * from [ARNUM$]");
String getname=null;
while(rs.next())
{
getname=rs.getString(1);
sqld=rs.getDate(2);
System.out.println(getname+" "+sqld+" "+sqlDate);
if(sqlDate.compareTo(sqld)==0)
{
name=name+" "+getname;
name=name.toUpperCase();
}
System.out.println(name);
}
if(name.length()==0)
{
JOptionPane.showMessageDialog(
pnlp4,
"No Name having "+textdate.getText(),
"Warning",
JOptionPane.WARNING_MESSAGE
);
}
else
{
textname.setText(name);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}//end actionPerformed
}); //end addActionListener
The field value of sqld might be null. Now unfortunately sqlDate.compareTo(null) will throw a NullPointerException. (Other compareTo's behave better.)

Categories