First of all sorry for my poor English. I'll try my best to understand you my problem.
All I want is to save the new data whichever user has entered in the JTable whenever Save button will clicked.
I am retrieving Student ID, Name in first two columns from database and also i have added current date in third column and Absent/Present as fourth column which is editable. I have following code to retrieve data from database.
**Attendance.java** :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package shreesai;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Vector;
/**
*
* #author Admin
*/
public class Attendance{
Connection con = Connectdatabase.ConnecrDb();
java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
String d1 = fromUser.format(sqlDate);
String d = d1.toString();
public Vector getEmployee()throws Exception
{
Vector<Vector<String>> employeeVector = new Vector<Vector<String>>();
PreparedStatement pre = con.prepareStatement("select studentid,name from student");
ResultSet rs = pre.executeQuery();
while(rs.next())
{
Vector<String> employee = new Vector<String>();
employee.add(rs.getString(1)); //Empid
employee.add(rs.getString(2));//name
employee.add(d);
employeeVector.add(employee);
}
if(con!=null)
con.close();
rs.close();
pre.close();
return employeeVector;
}
}
**AttendanceGUI.java : **
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package shreesai;
import static java.awt.Frame.MAXIMIZED_BOTH;
import java.sql.Connection;
import java.util.Vector;
import javax.swing.JOptionPane;
/**
*
* #author Admin
*/
public class AttendanceGUI extends javax.swing.JFrame {
/**
* Creates new form AttendanceGUI
*/
Connection con = Connectdatabase.ConnecrDb();
private Vector<Vector<String>> data;
private Vector<String> header;
public AttendanceGUI() throws Exception {
this.setLocationRelativeTo(null);
setExtendedState(MAXIMIZED_BOTH);
Attendance att = new Attendance();
data = att.getEmployee();
header = new Vector<String>();
header.add("Student ID");
header.add("Student Name");
header.add("Date");
header.add("Absent/Present");
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() {
jScrollPane1 = new javax.swing.JScrollPane();
AttendanceT = new javax.swing.JTable();
SaveAtt = new javax.swing.JButton();
Exit = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
AttendanceT.setModel(new javax.swing.table.DefaultTableModel(
data,header
)
{public boolean isCellEditable(int row, int column){return true;}}
);
AttendanceT.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
TableColumnAdjuster tca = new TableColumnAdjuster(AttendanceT);
tca.adjustColumns();
AttendanceT.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jScrollPane1.setViewportView(AttendanceT);
SaveAtt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/save.png"))); // NOI18N
SaveAtt.setText("Save Attendance");
SaveAtt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SaveAttActionPerformed(evt);
}
});
Exit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/exit.png"))); // NOI18N
Exit.setText("Exit");
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(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(SaveAtt, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(176, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SaveAtt, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void SaveAttActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* #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(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.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() {
try{
new AttendanceGUI().setVisible(true);
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}
});
}
// Variables declaration - do not modify
private javax.swing.JTable AttendanceT;
private javax.swing.JButton Exit;
private javax.swing.JButton SaveAtt;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
This output I get when I run JFrame :
Now, What I want actually is whenever user will edit data into JTable just like in the following Image :
****After clicking Save Attendance button the current JTable values should entered into the database. I am using Sqlite database which is addon in Firefox. I have created attendance table in my database which is having studentid integer, name varchar, date DATETIME, and preab VARCHAR(This to store whether particular student was present or absent) ****
I hope that you get what my problem is. Thanks in advance.
As you are using DefaultTableModel you have to register a listener to that model a TableModelListener listening for changes. How to use TableModelListener
Example:
myTable.getModel().addTableModelListener(new TableModelListener(){
#Override
public void tableChanged(TableModelEvent evt){
//code here
}
});
public void happi(String name, String age, String id){
//this method should be located on a class, then you just instantiate the class in the main form
String query=null;
try{
query = "update tbltest set name = '"+name+"',age = '"+age+"' where id = '"+id+"'";
stmt.executeUpdate(query);
}
catch(Exception ex){JOptionPane.showMessageDialog(null,""+ex);}
finally{
super.closeConnection(connect);
super.closeStatement(stmt);
}
}//end of happi
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//a button with event ActionPerformed (save button)
table.updateUI();
}//end
private void tablePropertyChange(java.beans.PropertyChangeEvent evt) {
// a JTablenamed"table"
try{
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
int c = table.getColumnCount();
DBHandler dbh = new DBHandler();
dbh.happi((table.getModel().getValueAt(row, 0).toString()), (table.getModel().getValueAt(row, 1).toString()), (table.getModel().getValueAt(row, 2).toString()));
}catch(Exception e){}
} '
Related
I have a table called "user" from which I want to display the user types in a combo box. I have created a separate class for the connection.
package testdb;
import java.sql.*;
import javax.swing.*;
public class MySqlConnect {
Connection conn = null;
public static Connection ConnectDB(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
JOptionPane.showMessageDialog(null, "Connected to database");
return conn;
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
The form on which I've created the combo box has the following code.
package testdb;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
public class Combo extends javax.swing.JFrame {
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
public Combo() {
initComponents();
}
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
combo1 = new javax.swing.JComboBox<>();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("User Type");
combo1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
combo1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
combo1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(41, 41, 41)
.addComponent(jLabel1)
.addGap(73, 73, 73)
.addComponent(combo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(181, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(43, 43, 43)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(combo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(237, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void combo1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
conn = MySqlConnect.ConnectDB();
String s = "Select * from user";
pst = conn.prepareStatement(s);
rs = pst.executeQuery();
while(rs.next()){
String cb = rs.getString("username");
combo1.addItem(cb);
}
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
/**
* #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(Combo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Combo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Combo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Combo.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 Combo().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JComboBox<String> combo1;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
The combo box still doesn't display any values from the database. Could someone please tell me what's wrong in my code?
I kept trying and finally got it! I used a function called fillCombo an then called it! It worked. This is what I love about coding, you just got to keep trying an when you finally solve it, it feels just amazing.
Now I have to solve the next problem I encountered, removing duplicate values. I'm going to keep trying!
I've got a little problem with JFormattedTextField:
I want to set the formatted text fields to numbers only. I've created one with Swing interface on NetBeans.
My code is as follows:
package SerasApp;
import static java.lang.System.*;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFormattedTextField;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;
import javax.swing.text.NumberFormatter;
/**
* #author adam
*/
public class Main extends javax.swing.JFrame {
/**
* Creates new form Main
*/
public Main() {
initComponents();
}
//set position of label to be the center of the frame
public void PositionHiSera()
{
//find position of jpanel
int FrameHeight = this.Intro.getHeight();
int FrameWidth = this.Intro.getWidth();
int LabelSize[] = new int[2];
LabelSize[0] = HiSera.getWidth();
LabelSize[1] = HiSera.getHeight();
out.println(LabelSize[0]);
out.println(LabelSize[1]);
int Origin[] = new int[2];
Origin[1] = (FrameHeight/2)-(LabelSize[0]/2);
Origin[0] = (FrameWidth/2)-(LabelSize[1]/2);
//set label origin
HiSera.setLocation(Origin[1], Origin[0]);
}
public void HumidityLevel()
{
NumberFormat a = NumberFormat.getNumberInstance();
NumberFormatter b = new NumberFormatter(a);
DefaultFormatterFactory c = new DefaultFormatterFactory(b);
humidityLevel.setFormatterFactory(c);
}
/**
* 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() {
MainDisplayFrame = new javax.swing.JPanel();
Intro = new javax.swing.JPanel();
HiSera = new javax.swing.JLabel();
MainMenu = new javax.swing.JPanel();
WeatherOptions = new javax.swing.JPanel();
sunny = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
humidityLevel = new javax.swing.JFormattedTextField();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowFocusListener(new java.awt.event.WindowFocusListener() {
public void windowGainedFocus(java.awt.event.WindowEvent evt) {
formWindowGainedFocus(evt);
}
public void windowLostFocus(java.awt.event.WindowEvent evt) {
}
});
MainDisplayFrame.setLayout(new java.awt.CardLayout());
Intro.setMaximumSize(new java.awt.Dimension(30000, 30000));
HiSera.setText("Hi Sera");
javax.swing.GroupLayout IntroLayout = new javax.swing.GroupLayout(Intro);
Intro.setLayout(IntroLayout);
IntroLayout.setHorizontalGroup(
IntroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(IntroLayout.createSequentialGroup()
.addGap(209, 209, 209)
.addComponent(HiSera)
.addContainerGap(243, Short.MAX_VALUE))
);
IntroLayout.setVerticalGroup(
IntroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(IntroLayout.createSequentialGroup()
.addGap(225, 225, 225)
.addComponent(HiSera)
.addContainerGap(258, Short.MAX_VALUE))
);
MainDisplayFrame.add(Intro, "card2");
javax.swing.GroupLayout MainMenuLayout = new javax.swing.GroupLayout(MainMenu);
MainMenu.setLayout(MainMenuLayout);
MainMenuLayout.setHorizontalGroup(
MainMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, Short.MAX_VALUE, Short.MAX_VALUE)
);
MainMenuLayout.setVerticalGroup(
MainMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 500, Short.MAX_VALUE)
);
MainDisplayFrame.add(MainMenu, "card2");
WeatherOptions.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
WeatherOptionsFocusGained(evt);
}
});
sunny.setText("Sunny");
sunny.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sunnyActionPerformed(evt);
}
});
jButton2.setText("Overcast");
jButton3.setText("Rainy");
jLabel1.setText("Humidity Level");
javax.swing.GroupLayout WeatherOptionsLayout = new javax.swing.GroupLayout(WeatherOptions);
WeatherOptions.setLayout(WeatherOptionsLayout);
WeatherOptionsLayout.setHorizontalGroup(
WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(WeatherOptionsLayout.createSequentialGroup()
.addGroup(WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(WeatherOptionsLayout.createSequentialGroup()
.addGap(81, 81, 81)
.addComponent(sunny)
.addGap(75, 75, 75))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, WeatherOptionsLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(36, 36, 36)))
.addGroup(WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(humidityLevel, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(WeatherOptionsLayout.createSequentialGroup()
.addComponent(jButton2)
.addGap(69, 69, 69)
.addComponent(jButton3)))
.addContainerGap(99, Short.MAX_VALUE))
);
WeatherOptionsLayout.setVerticalGroup(
WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(WeatherOptionsLayout.createSequentialGroup()
.addGap(225, 225, 225)
.addGroup(WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(sunny)
.addComponent(jButton2)
.addComponent(jButton3))
.addGap(87, 87, 87)
.addGroup(WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(humidityLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(132, Short.MAX_VALUE))
);
MainDisplayFrame.add(WeatherOptions, "card2");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 500, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(MainDisplayFrame, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 500, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(MainDisplayFrame, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
PositionHiSera();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
//make Intro Disappear and make Weather Options Appear
WeatherOptions.setVisible(true);
Intro.setVisible(false);
HumidityLevel();
out.println("tests");
}
private void sunnyActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void WeatherOptionsFocusGained(java.awt.event.FocusEvent evt) {
// 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(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main.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 Main().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel HiSera;
private javax.swing.JPanel Intro;
private javax.swing.JPanel MainDisplayFrame;
private javax.swing.JPanel MainMenu;
private javax.swing.JPanel WeatherOptions;
private javax.swing.JFormattedTextField humidityLevel;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JButton sunny;
// End of variables declaration
}
I've tried also to set a humidityLevel to new formatted text field to no avail.
Mainly it's this bit of code:
public void HumidityLevel()
{
NumberFormat a = NumberFormat.getNumberInstance();
NumberFormatter b = new NumberFormatter(a);
DefaultFormatterFactory c = new DefaultFormatterFactory(b);
humidityLevel.setFormatterFactory(c);
}
and this bit:
private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
PositionHiSera();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
//make Intro Disappear and make Weather Options Appear
WeatherOptions.setVisible(true);
Intro.setVisible(false);
HumidityLevel();
out.println("tests");
}
I also don't want to use a JTextField because I want to learn how to use JFormattedTextField.
I want to set the formatted text fields to numbers only.
Using the Design view, right click over the formatted text field and choose Properties option. Then look for formatterFactory property:
If you try to edit this property, the following dialog will show up. Choose integer default option under number category:
That's it, your text field will be initialized using NumberFormat.getIntegerInstance(). If you inspect the generated source code you'll see something like this:
jFormattedTextField1 = new javax.swing.JFormattedTextField();
jFormattedTextField1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(java.text.NumberFormat.getIntegerInstance())));
Off-topic
As #mKorbel pointed out, using Thread.sleep() is a bad idea and will block the Event Dispatch Thread (EDT) which is a single and special thread where Swing components creation / update should be performed and event handling is processed. If this thread is blocked then your GUI won't be able to repaint itself and will "freeze". In this case you should consider use a Swing Timer instead. See Concurrency in Swing for further details.
so, i'm working on a project where I have to use a search button to find user information from a jdbc database, and so far I've got some of the code to work and added fields and data to the database, but once i hit search in the jtextfield it doesn't display any data in the table. So, i'm wondering if someone can take a look at this code and tell me where the mistake is, the jbutton is supposed to connect to the mainframe where the database connection information is stored.
this is the main frame code:
package guestbook;
import java.sql.Connection;
import java.sql.DriverManager;
public class MainFrame extends javax.swing.JFrame {
public static String dbURL = "jdbc:derby://localhost:1527/Coolkidsclub;create=true;user=Vic";
public static Connection conn = null;
/**
* Creates new form MainFrame
*/
public MainFrame() {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();//"org.apache.derby.jdbc.ClientDriver" to use derby driver
conn = DriverManager.getConnection(dbURL);
initComponents();
}
catch (Exception e){
}
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() {
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/guestbook/ckc.PNG"))); // NOI18N
jButton1.setText("Add Kid");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Update Kid");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Remove Kid");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("Find Kid");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(106, 106, 106)
.addComponent(jLabel1)
.addContainerGap(109, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(126, 126, 126)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton4)
.addGap(130, 130, 130))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3)
.addComponent(jButton4))
.addContainerGap(44, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
AddFrame add = new AddFrame();
add.setVisible(true);
this.dispose();
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
UpdateFrame update = new UpdateFrame();
update.setVisible(true);
this.dispose();
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
RemoveFrame remove = new RemoveFrame();
remove.setVisible(true);
this.dispose();
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
SearchFrame search = new SearchFrame();
search.setVisible(true);
this.dispose();
}
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(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.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 MainFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
and this is the searchframe code:
package guestbook;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
public class SearchFrame extends javax.swing.JFrame {
public SearchFrame() {
initComponents();
}
public static DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
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 [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/guestbook/fckc.PNG"))); // NOI18N
jTextField1.setText("Type Name Here...");
jButton5.setText("Find Kid");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jButton6.setText("Go back to Start");
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
jTable2.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 [] {
"", "", "", ""
}
));
jTable2.getTableHeader().setReorderingAllowed(false);
jScrollPane2.setViewportView(jTable2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(113, 113, 113)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 518, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 383, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton5)))))
.addGroup(layout.createSequentialGroup()
.addGap(294, 294, 294)
.addComponent(jButton6)))
.addContainerGap(146, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton6)
.addContainerGap(58, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Statement stmt = MainFrame.conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from COOLKIDS " + jTextField1.getText().toString());
jTable2.setModel(buildTableModel(rs));//to display the table
} catch (Exception except) {
}
}
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
MainFrame main = new MainFrame();
main.setVisible(true);
this.dispose();
}
/**
* #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(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SearchFrame.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 SearchFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
private javax.swing.JTable jTable2;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
any help would be greatly appreciated as I'm relatively new to java.
EDIT: After a day or two I did a stackTrace exception printout and it says something about the statement stmt code being wrong do i just need to add a line in the searchframe to connect to the database and forget the mainframe connection?
So, i'm wondering if someone can take a look at this code and tell me where the mistake is, the jbutton is supposed to connect to the
mainframe where the database connection information is stored.
Well the first thing I can say is it's a lot of code. Now, there are several conceptual mistakes in your code that may lead to the stated problem.
Don't mix View (user interface) with Database connections
Beware that applications are tipically designed using layers or levels to isolate and separate responsibilities. In this case having a static Connection object within a JFrame simply breaks this principle. The first thing to do is separate database connection and logic from the user interface.
Don't ignore exceptions, always give them a correct treatment
This one of the worse things we can do:
try {
...
} catch (Exception e) {}
If an exception has been thrown it means that something unexpected happened. Just ignoring the exception in an empty catch block won't make it be solved but will hide this fact to us. Consequently we won't be able to solve the problem because we don't actually know that something wrong is heppening.
Avoid using static references
If you need to use a static to access a class member then it's probably there's a design problem in our code. While static fields are possible and sometimes useful (i.e.: define constants) from an OOP point of view they are not a good choice because break the encapsulation principle. We can just give access to a class member to the outside by providing getters and setters.
EDIT: After a day or two I did a stackTrace exception printout and it says something about the statement stmt code being wrong do i just
need to add a line in the searchframe to connect to the database and
forget the mainframe connection?
You would have to include the stack trace in your question, but let's take a look to the SQL query sent to the database:
ResultSet rs = stmt.executeQuery("select * from COOLKIDS " + jTextField1.getText().toString());
Most likely there is a WHERE clause missing in your SQL statmement (I don't know the text obtained from jTextField1 so it's just a guess). SQL statments tipically have this minimal structure:
SELECT fields list
FROM tables
WHERE conditions
On the other hand you might consider use PreparedStatement like this:
String sql = "SELECT * FROM coolkids WHERE name = ?";
PreparedStatement pst = connection.prepareStatement(sql);
pst.setString(1, jTextField1.getText());
ResultSet rs = pst.executeQuery();
Once again, this code should be isolated from the UI and jTextField1 text should be passed as an argument to an appropriate Controller/Persistence layer class.
On Selecting Country Field,
State Field is shown,
AND on Selecting State Feild,
City Field is shown
But in the below code when i select for the first time it works fine but when i select another country
then its States gets added to the previous country's States and similar is the case with City.
I read about JComboBox.RemoveAll() and DefaultComboBoxModel class but don't know how to use it in current case.So,Basically how to reset JComboBox Items?
Have a look on public countryCode{ } class, private void stateBoxActionPerformed,
private void countryBoxActionPerformed Functions
ANSWER:Here what worked For ME use stateBox.removeAllItems() before the code where we r adding states in the list from database .
Here is code of NetBeans --->
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author System
*/
public class countryCode extends javax.swing.JFrame {
DefaultComboBoxModel d1=new DefaultComboBoxModel();
Connection con;
String code,q;
PreparedStatement ps;
ResultSet rs;
/**
* Creates new form countryCode
*/
public countryCode() {
initComponents();
createConnection();
}
void createConnection()
{
try
{
Class.forName("oracle.jdbc.OracleDriver");//Connection String
String r1="jdbc:oracle:thin:#localhost:1521:";//Open Connection
con=DriverManager.getConnection(r1,"system","password");
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this,ex);
ex.printStackTrace();
}
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
countryBox = new javax.swing.JComboBox();
country = new javax.swing.JLabel();
stateBox = new javax.swing.JComboBox();
cityBox = new javax.swing.JComboBox();
state = new javax.swing.JLabel();
city = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
countryBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "America", "India", "Nepal", "Pakistan", "Sri Lanka", " ", " " }));
countryBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
countryBoxActionPerformed(evt);
}
});
country.setText("Country");
stateBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " " }));
stateBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stateBoxActionPerformed(evt);
}
});
state.setText("State");
city.setText("City");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(country, javax.swing.GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE)
.addComponent(state, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(city, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(cityBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(stateBox, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(countryBox, javax.swing.GroupLayout.Alignment.TRAILING, 0, 198, Short.MAX_VALUE))
.addGap(95, 95, 95))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(50, 50, 50)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(countryBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(country))
.addGap(18, 18, 18)
.addComponent(stateBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(state))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cityBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(city))
.addContainerGap(154, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void countryBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_countryBoxActionPerformed
try {
//GET STRING
String coname;
coname = (String)countryBox.getSelectedItem();
//STRING QUERY
q="select * from country where cname=? ";
//PREPARE STATEMENT
ps=con.prepareStatement(q);
//SET STRING
ps.setString(1,coname);
rs=ps.executeQuery();//RESULTSET
while(rs.next())
{d1.getClass();
code=rs.getString("cocode");
break;
}
/* ******************* <!------ANOTHER QUERY------> ****************************** */
//STRING QUERY
q="select * from state where cocode=? ";
//PREPARE STATEMENT
ps=con.prepareStatement(q);
//SET STRING
ps.setString(1,code);
ResultSet rs=ps.executeQuery();
while(rs.next())
{
String code=rs.getString("stname");
stateBox.addItem(code);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}//GEN-LAST:event_countryBoxActionPerformed
private void stateBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stateBoxActionPerformed
try {
/*---------NOW QUERY TO GET STCODE I.E STATECODE REPEAT HERE STEPS WHAT WE DID IN COUNTRY -----------*/
//GET STRING
String stname;
stname = (String)stateBox.getSelectedItem();
//STRING QUERY
q="select * from state where stname=? ";
//PREPARE STATEMENT
ps=con.prepareStatement(q);
//SET STRING
ps.setString(1,stname);
rs=ps.executeQuery();//RESULTSET
while(rs.next())
{
code=rs.getString("stcode");
break;
}
/* ******************* <!------ANOTHER QUERY------> ****************************** */
//STRING QUERY
q="select * from city where stcode=? ";
//PREPARE STATEMENT
ps=con.prepareStatement(q);
//SET STRING
ps.setString(1,code);
rs=ps.executeQuery();
while(rs.next())
{
code=rs.getString("ciname");
cityBox.addItem(code);
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}//GEN-LAST:event_stateBoxActionPerformed
/**
* #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(countryCode.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(countryCode.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(countryCode.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(countryCode.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 countryCode().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel city;
private javax.swing.JComboBox cityBox;
private javax.swing.JLabel country;
private javax.swing.JComboBox countryBox;
private javax.swing.JLabel state;
private javax.swing.JComboBox stateBox;
// End of variables declaration//GEN-END:variables
}
Try using removeAllItems() method. You should call this function before you start adding items to your combo box. so your code should look like this
/**
*do something here
**/
jComboBox.removeAllItems();
/**
*do something else here
**/
You can use RemoveAll method befor adding new items to your combobox just befor while loop.
You can also use array list.
i've some problem with my list selection listener that i show you below
1.the result of the listener printing twice that i don't have an idea about it...!??!why it's printing twice?
2.when i pressing the searchBt and the result shows,and i choose one of the result i want to return ChooseIndex from the valueChanged(ListSelectionEvent e) but it can't has a return statement and the selected index of thge j list is useless...what's the problem?
public class SearchPage extends javax.swing.JFrame {
public SearchPage() {
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() {
SearchBox = new javax.swing.JTextField();
SearchBt = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
SearchBt.setText("Search");
SearchBt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SearchBtActionPerformed(evt);
}
});
jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
jList1.setToolTipText("");
jList1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jList1.setSelectionBackground(new java.awt.Color(102, 0, 102));
jList1.setValueIsAdjusting(true);
jList1.setVerifyInputWhenFocusTarget(false);
jScrollPane1.setViewportView(jList1);
jList1.getAccessibleContext().setAccessibleName("");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 543, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(SearchBox, javax.swing.GroupLayout.PREFERRED_SIZE, 244, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(SearchBt, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(281, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(125, 125, 125)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SearchBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SearchBt))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void SearchBtActionPerformed(java.awt.event.ActionEvent evt) {
String tag = SearchBox.getText().trim();
Vector<String> vector = new Vector<String>();
for (int i = 0; i <Code.CodeSearch(tag).size(); i++) {
String string = Code.FNameExtractor(Code.CodeSearch(tag).get(i).getFileName())+" Uploaded By "+Code.CodeSearch(tag).get(i).getUserdetails().getUsername();
vector.add(string);
}
jList1 = new JList<String>(vector);
ListSelectionModel listSelectionModel = jList1.getSelectionModel();
listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());
listSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jScrollPane1.setViewportView(jList1);
}
/**
* #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(SearchPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SearchPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SearchPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SearchPage.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 SearchPage().setVisible(true);
}
});
}
class SharedListSelectionHandler implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
int ChooseIndex =lsm.getMaxSelectionIndex();
System.out.println(ChooseIndex);
}
}
// Variables declaration - do not modify
private javax.swing.JTextField SearchBox;
private javax.swing.JButton SearchBt;
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
The selection listener only tells us the index of the selected item. That's normal. The list doesn't care about the content. You have to store the list model (iaw, a list of strings that you actually display) somewhere and use the index value from the listener to lookup the content at the index in your model. That's the common pattern.
For the first question - I'd set a breakpoint on the print statement, debug and look at the stacktrace. Then I'd see why the method was called twice.