Home Answers Viewqa Java-Beginners my table should be reseted to new value upon the selection of the combo box..

 
 


sunnychadha
my table should be reseted to new value upon the selection of the combo box..
6 Answer(s)      7 months ago
Posted in : Java Beginners

import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.swing.JOptionPane;

import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.DefaultTableModel;

/* * To change this template, choose Tools | Templates * and open the template in the editor. */

/**

* * @author GB15 */ public class purchase extends javax.swing.JFrame { JTable table; DefaultTableModel model; JScrollPane sc1; ResultSet rs; Connection con; Statement st;

/**
 * Creates new form purchase
 */
public purchase() {



    try
   {   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        con=DriverManager.getConnection("jdbc:odbc:dsn4");
        System.out.println("Connected");
        st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);


   }
   catch(Exception e)
   {
       e.printStackTrace();
   }

//table creation

Container cp = getContentPane(); cp.setLayout(new FlowLayout()); model = new DefaultTableModel(); table = new JTable(model); model.addColumn(" INVO "); //1 model.addColumn(" INV DATE "); //2 model.addColumn("DESCRIPTION"); //3 model.addColumn(" BILL TYPE "); //4 model.addColumn(" TRN TYPE "); //5 model.addColumn(" AMOUNT "); //6
model.addRow(new Object[]{"","","","","",""});

table.addKeyListener( new KeyListener() { public void keyPressed(KeyEvent e)
{ try{ if (e.getKeyCode()==KeyEvent.VK_ENTER) { model.addRow(new Object[]{"", "","","","",""}); }

     if (e.getKeyCode()==KeyEvent.VK_DELETE) 
       {

      ListSelectionModel list = table.getSelectionModel();  
    int row = list.getLeadSelectionIndex(); 


        if(row>0)
        {

     model.removeRow(row);

       }
        else
        {
          JOptionPane.showMessageDialog(null, "Table must Contain atleast one Row...so You can't DELETE");

        }

   }

       }catch(ArrayIndexOutOfBoundsException ai ){
       }
 }

public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { }}); sc1 = new JScrollPane(table,JScrollPane.VERTICALSCROLLBARALWAYS, JScrollPane.HORIZONTALSCROLLBARALWAYS); cp.add(sc1); setDefaultCloseOperation(DISPOSEONCLOSE); setSize(1300,400); setVisible(true);
initComponents(); try { rs= st.executeQuery("SELECT cname FROM pur");

while(rs.next()) { cb1.addItem(rs.getString(1));
System.out.println(rs.getString(1)); } } catch(Exception e) { } getContentPane().add(sc1); sc1.setBounds(20, 160, 620, 380); }

/** * 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. */

// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    l2 = new javax.swing.JLabel();
    cb1 = new javax.swing.JComboBox();
    l3 = new javax.swing.JLabel();
    l4 = new javax.swing.JLabel();
    l5 = new javax.swing.JLabel();
    l6 = new javax.swing.JLabel();
    l7 = new javax.swing.JLabel();
    l8 = new javax.swing.JLabel();
    l1 = new javax.swing.JLabel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setMinimumSize(new java.awt.Dimension(700, 700));
    getContentPane().setLayout(null);

    l2.setText("    Customer name");
    l2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
    getContentPane().add(l2);
    l2.setBounds(20, 80, 220, 30);

    cb1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select" }));
    cb1.addItemListener(new java.awt.event.ItemListener() {
        public void itemStateChanged(java.awt.event.ItemEvent evt) {
            cb1ItemStateChanged(evt);
        }
    });
    cb1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cb1ActionPerformed(evt);
        }
    });
    getContentPane().add(cb1);
    cb1.setBounds(20, 120, 220, 20);

    l3.setText("A/C CODE");
    l3.setBorder(javax.swing.BorderFactory.createEtchedBorder());
    getContentPane().add(l3);
    l3.setBounds(300, 50, 70, 18);

    l4.setText("TOWN/CITY");
    l4.setBorder(javax.swing.BorderFactory.createEtchedBorder());
    getContentPane().add(l4);
    l4.setBounds(300, 80, 70, 18);

    l5.setText("CURRENT BALANCE");
    l5.setBorder(javax.swing.BorderFactory.createEtchedBorder());
    getContentPane().add(l5);
    l5.setBounds(300, 120, 130, 18);

    l6.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
    getContentPane().add(l6);
    l6.setBounds(450, 46, 80, 20);

    l7.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
    getContentPane().add(l7);
    l7.setBounds(450, 80, 80, 20);

    l8.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
    getContentPane().add(l8);
    l8.setBounds(450, 120, 80, 20);

    l1.setForeground(new java.awt.Color(204, 0, 0));
    l1.setText("    Please select the customer name");
    l1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
    getContentPane().add(l1);
    l1.setBounds(20, 30, 220, 40);

    jButton1.setText("ADD");
    getContentPane().add(jButton1);
    jButton1.setBounds(40, 560, 53, 23);

    jButton2.setText("DELETE");
    getContentPane().add(jButton2);
    jButton2.setBounds(180, 560, 80, 23);

    jButton3.setText("EXIT");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });
    getContentPane().add(jButton3);
    jButton3.setBounds(350, 560, 80, 23);

    pack();
}// </editor-fold>                        

private void cb1ActionPerformed(java.awt.event.ActionEvent evt) {                                    
    // TODO add your handling code here:

}                                   

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    System.exit(0);
}                                        

private void cb1ItemStateChanged(java.awt.event.ItemEvent evt) {                                     
    // TODO add your handling code here:
     try{
       String s="%"; 

       if(cb1.getSelectedIndex()>=0)
         s=cb1.getSelectedItem().toString();
       String query="select * from pur where cname like '"+s+"' ";
       Statement de=con.createStatement();
       ResultSet demo=de.executeQuery(query);
       while(demo.next()){
           l6.setText(""+demo.getString(1));
           l7.setText(demo.getString(3));
           l8.setText(""+demo.getDouble(4));
      model.addRow(new Object[]{demo.getString(5),demo.getString(6),demo.getString(7),demo.getString(8),demo.getString(9),demo.getString(10)});

       }
    }
    catch(Exception e){
        e.printStackTrace();
        //System.out.println("Error : "+e.getMessage());
    }
}                                    

/**
 * @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(purchase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(purchase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(purchase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(purchase.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 purchase().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private javax.swing.JComboBox cb1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel l1;
private javax.swing.JLabel l2;
private javax.swing.JLabel l3;
private javax.swing.JLabel l4;
private javax.swing.JLabel l5;
private javax.swing.JLabel l6;
private javax.swing.JLabel l7;
private javax.swing.JLabel l8;
// End of variables declaration

}

View Answers

November 9, 2012 at 4:54 PM


Here is a simple example of resetting the table content on selecting the value from the combobox.

import java.awt.*;
import java.sql.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

class SearchFromCombo{
    public static void main(String[] args) {
        final Vector columnNames = new Vector();
        final Vector data = new Vector();

        JLabel lab=new JLabel("Select:");
        final JComboBox t=new JComboBox();
        try{
           Class.forName("com.mysql.jdbc.Driver");
           Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
           Statement st=con.createStatement();
           ResultSet rs=st.executeQuery("select name from data");
           while(rs.next()){
               t.addItem(rs.getString("name"));
           }
        }
        catch(Exception e){}


        JButton b = new JButton("Search");
        final JTable table=new JTable();
        final JScrollPane pane=new JScrollPane(table);

        JFrame f = new JFrame();
        f.setLayout(null);
        lab.setBounds(10,10,100,20);
        t.setBounds(120,10,100,20);
        b.setBounds(120,40,80,20);
        pane.setBounds(10,70,480,170);
        pane.setVisible(false);
        f.add(lab);
        f.add(t);
        f.add(b);
        f.add(pane);
        pane.setVisible(false);
        f.setSize(500,300);
        f.setVisible(true);


        b.addActionListener(new ActionListener(){
           public void actionPerformed(ActionEvent e){
            String name = String.valueOf(t.getSelectedItem());
            try{
           Class.forName("com.mysql.jdbc.Driver");
           Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
           Statement st=con.createStatement();
           ResultSet rs=st.executeQuery("select * from data where name='"+name+"'");
           ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();
            for (int i = 1; i <= columns; i++){
            columnNames.addElement(md.getColumnName(i) );
            }
            while(rs.next()){
            Vector row = new Vector(columns);
            for (int i = 1; i <= columns; i++){
            row.addElement( rs.getObject(i) );
            }
            data.addElement(row);
           }
           DefaultTableModel model=new DefaultTableModel(data, columnNames);
           table.setModel(model);
           pane.setVisible(true);
            }
            catch(Exception ex){
            System.out.println(e);
            }
          }
        });
    }
}

November 10, 2012 at 10:27 AM


what are the values you included in the database?could you please mention it!!!!


November 15, 2012 at 11:39 AM


i got the solution of the above code its just writing the model code in for loop and the table gets reset.... thanks for the above advice


November 15, 2012 at 11:39 AM


i got the solution of the above code its just writing the model code in for loop and the table gets reset.... thanks for the above advice


November 15, 2012 at 11:39 AM


i got the solution of the above code its just writing the model code in for loop and the table gets reset.... thanks for the above advice


November 15, 2012 at 11:41 AM


now i am facing another problem of the above code..every time i insert a value in data base with the help of the table,values gets duplicated i mean the values are inserted with the new as well as the old ones are again repeated.... Please somebody help me on this.... Thanks in advance....









Related Pages:
my table should be reseted to new value upon the selection of the combo box..
my table should be reseted to new value upon the selection of the combo box... DefaultTableModel(); table = new JTable(model); model.addColumn(" INVO... e) { } public void keyTyped(KeyEvent e) { }}); sc1 = new JScrollPane(table
combo box
a screen like this using jsp-servlet(or DAO,DTO),in that drop down box i should get usernames from the database & upon selection of particular user i should get...combo box  Hi, [_|] dropdown box
combo box value
combo box value   i want to populate one combo box value based on another combo box value using ajax   1)country.jsp: <%@page...){ if (typeof XMLHttpRequest != "undefined"){ xmlHttp= new XMLHttpRequest
combo box value
combo box value   i want to populate one combo box value based on another combo box value using ajax   1)country.jsp: <%@page import..."){ xmlHttp= new XMLHttpRequest(); } else if (window.ActiveXObject
Store combo box value - Development process
Store combo box value  Hi , this is my code. Here wen i click submit button combo values are stored like 1,2,3... but i want to store value . plz... message the data entered in first field should not be erased .i think the page get
combo box code problem
combo box code problem  in this my problem related to : when i... stores the option value no like MP at option value 10 then it will stores the 10... <html> <head> <script language="javascript"> var arr = new
loading value into combo box by selecting value from other combo box - JSP-Servlet
loading value into combo box by selecting value from other combo box  ... and code; each district table contain constituency and code. MY problem is that as i select state from state_combo_box,then the next combo box is dynamically
How to retrieve data by using combo box value in jsp? - JSP-Servlet
How to retrieve data by using combo box value in jsp?  Hi Friends...... For Example, in Student.jsp... when i click student id in combo box... in combo box from database.. by using select*from studentinformation; But when i
populating the combo box - Struts
populating the combo box  Hi I am having problem populating the combo box with a table in MS SQL Server 2005 Management Studio Express. Belo...; } ========================================================================== My problem is populating the combobox table
How to pass the value of Selected Value of combo box into sql ??
How to pass the value of Selected Value of combo box into sql ??  My SQL Database Name is MHS, user=root, password=admin,table name is sub_comb(regno,sname,sgen). Now i want to select one "regno" from Combobox and then after
Populate a combo box using data from a database
Populate a combo box using data from a database  Hi Guys, In need... combo box which will then load the next combo box values, now i know how... to the client using ajax, and then populate the combo box, I must'nt reload
base the value of first combo box, how i display the second combox - JSP-Servlet
base the value of first combo box, how i display the second combox    i have a combo box for classes. my requirement is when i select the class, if class is 11 or 12 the second combo box of subject should be appear. please
Re: base the value of first combo box, how i display the second combox - JSP-Servlet
Re: base the value of first combo box, how i display the second combox    thanks for your reply. i want to know suppose the second combo box...: ComboBox var arr = new Array(); arr[11] = new Array("Art","Commerce
selection box linked with textarea
selection box linked with textarea    function get_val(tot_val1) { document.getElementById('TextBox1').value = tot_val1; alert(tot_val1... detals i have in db with all fields .. like wise i have names in selection box sham
combo box connection
combo box connection  how to provide connection between three combo boxes,if my 1st combo box is course and 2nd combo box is semester and 3rd combo box is my subjects.what's the coding to provide the connection between this three
how to get combo box value - JSP-Servlet
in combo box in jsp page: (small part of my code) "> now i want the id in servlet page, that i have associated with value i.e "> bcoz i hav...how to get combo box value  i have created 1 servlet & 1 jsp page
Helps with combo box and frame
Helps with combo box and frame  Hi i have a combobox and when i click... on the second window and click confirm i would have the information on the combo box. i...[] = {"", "", "", "", ""}; combo = new JComboBox(items); JButton button1 = new JButton("Add new
JavaScript Dynamic Combo Box
JavaScript Dynamic Combo Box Here we are going to create dynamic combo box... in respective arrays. As the user selects a country from the first combo box, the cities...: On selecting the value from the first combo, related values will get displayed
Re: base the value of first combo box, how i display the second combox - JSP-Servlet
value of combo box should be sent. but when i clicked to submit button, it do...Re: base the value of first combo box, how i display the second combox  ...')){ document.getElementById('combo').style.visibility = 'visible'; var arr = new
retrieve the data to text fields from database on clicking the value of combo box
retrieve the data to text fields from database on clicking the value of combo box   retrieve the data to text fields from database on clicking the value of combo box . I am not getting it plz help me out .   hi
Combo box value Error - WebSevices
Combo box value Error   if($_SERVER['REQUEST_METHOD'] == 'POST...']); } document.frmProposal.hdVisa.value = document.getElementById('cmbVisa').value; Error: The "cmbVisa" Value is Null,This error will displayed for these coding.So tell me
fetch database value to text box based on selected value my code given below pls correct my code
fetch database value to text box based on selected value my code given below pls correct my code  my Code Given below Pls... help me send correct... action="/dedit" > <center><table border="1"> <tbody>
fetch database value to text box based on selected value my code given below pls correct my code
fetch database value to text box based on selected value my code given below pls correct my code  my Code Given below Pls... help me send correct... action="/dedit" > <center><table border="1"> <
how to get selected name from combo box
how to get selected name from combo box   i have fetched all records of worker i.e worker name. on a test.jsp and dispayed it into combo box ...my... of worker name within d combo box and display that id into a text box. plz
how to get selected name from combo box
how to get selected name from combo box   i have fetched all records of worker i.e worker name. on a test.jsp and dispayed it into combo box ...my... of worker name within d combo box and display that id into a text box. plz
how to get selected name from combo box
how to get selected name from combo box  i have fetched all records of worker i.e worker name. on a test.jsp and dispayed it into combo box ...my... of worker name within d combo box and display that id into a text box. plz answer
how to get selected name from combo box
how to get selected name from combo box  i have fetched all records of worker i.e worker name. on a test.jsp and dispayed it into combo box ...my... of worker name within d combo box and display that id into a text box. plz answer
how to get selected name from combo box
how to get selected name from combo box  i have fetched all records of worker i.e worker name. on a test.jsp and dispayed it into combo box ...my... of worker name within d combo box and display that id into a text box. plz answer
How to retrieve data by using combo box value in jsp? - JSP-Servlet
How to retrieve data by using combo box value in jsp?  I am using a single jsp form.. i did not get from another form.. i do not use 2 jsp form.. all are satisfaction in this form.. What will i do. My code is following
How to retreive data by using combo box value - JSP-Servlet
How to retreive data by using combo box value  Hello friend... I can print combo box values... with html .. So i cannot use request.getParameter. If i am using null value
How to get the values from the Combo Box - JSP-Servlet
, Actually i am getting the values in the combo box from table.I want what ever the value i select in combo box its corresponding records will display in their respective text box. e.g suppose i select ram values from the combo box and its
How to retrieve data from database by using combo box value in jsp? - JSP-Servlet
How to retrieve data from database by using combo box value in jsp?  .... Your code here.. CREATE TABLE "user" ( "name" character varying(100...; } function showEmp(emp_value) { if(document.getElementById("emp_id").value
How to create textbox on combo value selection using javacsript in jsp?
How to create textbox on combo value selection using javacsript in jsp?  dynamically create textbox on combo value selection. when select multiple values then create multiple textboxes
interrelated two selection box
interrelated two selection box  hi i need two selection box .in 1 box all designation like manager, ceo etc , onclick on manager i should get list of managers names in second selection box.. like wise so on. from database
How to retreive data by using combo box value - JSP-Servlet
How to retreive data by using combo box value  I am using a single jsp form.. i did not get from another form.. i do not use 2 jsp form.. all are satisfaction in this form.. What will i do. My code is following
Combo Box operation in Java Swing
holds the integer value for the position number of he of the item in combo box... Combo Box operation in Java Swing   ... the Combo Box component, you will learn how to add items to the combo box
radio button selection should move the control to a text box that needs to be complete
radio button selection should move the control to a text box that needs to be complete  on selection of a radio button mouse should move to a particular text box that needs to be filled. How
Code to store sub combo box value - Development process
Code to store sub combo box value  Hi Deepak, In the following code i want to store subcombo box value instead of number. Already "Dkn/Tmz...,advertisement ( numbers are stored like 1 2 3 ) Add Data var arr = new Array
How to write a select box and id should be stored in database?
How to write a select box and id should be stored in database?  Hi...); JLabel lab=new JLabel("Select Name:"); final JComboBox combo... combo=new JComboBox(); combo.addItem("George"); combo.addItem("Maria
Combo Box - Struts
Combo Box  I hava acombo box cnnected to my database via html collections. When selecting an option, i want to display specific parts (sectons) on my web page....am trying to use logic:present and logic:empty but its not working
jtable combo - Java Beginners
click on a particular cell of jtable i want to display the combo box...); JTable table = new JTable(model); TableColumnModel tcm = table.getColumnModel...); tc.setCellEditor(new ComboEditor()); } JScrollPane jsp = new JScrollPane(table
retrieving from oracle database using jsp combo box
retrieving from oracle database using jsp combo box  hi this is my... error = ""; if (!(document.getElementById("startpath").value... = ""; if (!(document.getElementById("stoppath").value)) { fld.style.background = '#F0F0F0
combo box - JSP-Servlet
combo box  I am using a JSP form in which a combobox is given and I want to populate data in it from database and on the basis of yhe selected item... table country(country_id,country) in database and try the following code
JComboBox Insert Edited Value Into Table
will be inserted to the table and the combo box will made editable and then if you...JComboBox Insert Edited Value Into Table In this section we will read about how to make JComboBox an editable and then how to insert the new edited value
Loading combo box from oracle
Loading combo box from oracle  how can i load values into a combobox from oracle database when a value is selected in another combo box
Problem With Combo Box Editable Property
Problem With Combo Box Editable Property  Hi I am new To Flex i had set Combo Box Editable Property as true. But I didn't get the property filtering in the combo box like when you enter text "S" in the combo box then the names
How to show autocomplete textbox values on combo box option selection using database?
How to show autocomplete textbox values on combo box option selection using database?  When I select option(i.e First Year) then it will show list of student names in auto-complete text box
retrieving data from database to the textbox depending upon the id in jsp
depending upon another textbox value which is productid.First the id entered by us...retrieving data from database to the textbox depending upon the id in jsp ... the corresponding producttype and product_price should populate into textbox,which a user
How to retrieve data by using combo box value in jsp? - JSP-Servlet
How to retrieve data by using combo box value in jsp?  For example, In Employee.jsp form, When i click employee id value in combo box...... i already stored combo box values from database. pl
Selection Sort
- Move every value only once This more efficient variation of selection sort... Java NotesSelection Sort NOTE: You should never really write your own...(...). Like all simple sorts, selection sort is implemented with two