i m trying to make a combobox that user can choose a value from a table this value then it is saved
i have the code really i m stucked on combobox..

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

//The API for accessing and processing data stored in a database

import java.sql.*;
import java.text.ParseException;

// Allows you to convert from string to date or vice versa

import java.text.SimpleDateFormat;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
public class Lesson37 extends JFrame{

static JLabel lfridge_num, lacn,luln,lshop_id,lreq_id,ldatefr ;

    static JTextField tfridge_num, tacn,tuln,treq_id,tdatefr ;
    JComboBox tshop_id = new JComboBox();

    //static JComboBox tshop_id;
    //static JComboBox tshop_id,sshop; 

    static java.util.Date daterequest, sqldaterequest;

    // Holds row values for the table

    static Object[][] databaseResults;

    // Holds column names for the table

    static Object[] columns = {"Fridge No", "A/C", "UL", "SHOP", "LOCATION", "REQUEST", "DATE"};

    // DefaultTableModel defines the methods JTable will use
    // I'm overriding the getColumnClass

    static DefaultTableModel dTableModel = new DefaultTableModel(databaseResults, columns){
        public Class getColumnClass(int column) {
            Class returnValue;

            // Verifying that the column exists (index > 0 && index < number of columns

            if ((column >= 0) && (column < getColumnCount())) {
              returnValue = getValueAt(0, column).getClass();
            } else {

              // Returns the class for the item in the column   

              returnValue = Object.class;
            return returnValue;

        // Create a JTable using the custom DefaultTableModel

        static JTable table = new JTable(dTableModel);

    public static void main(String[] args) throws SQLException{

        JFrame frame = new JFrame();

        // A connection object is used to provide access to a database

        Connection conn = null;

        try {
            // The driver allows you to query the database with Java
            // forName dynamically loads the class for you


            // DriverManager is used to handle a set of JDBC drivers
            // getConnection establishes a connection to the database
            // You must also pass the userid and password for the database

            conn = DriverManager.getConnection("jdbc:mysql://localhost/fridge","root","root");

            // Statement objects executes a SQL query
            // createStatement returns a Statement object

            Statement sqlState = conn.createStatement();

            // This is the query I'm sending to the database

            String selectStuff = "select b.fridge_num ,b.acn," + 
            "e.req_by,b.datefr " +
            "FROM fridge b,shop c,"+
            "location d,requested e WHERE b.shop_id=c.shop_id "+
            "AND c.location_id=d.location_id AND b.req_id=e.req_id;";

            // A ResultSet contains a table of data representing the
            // results of the query. It can not be changed and can 
            // only be read in one direction

            ResultSet rows = sqlState.executeQuery(selectStuff);

            // Temporarily holds the row results

            Object[] tempRow;

            // next is used to iterate through the results of a query


                tempRow = new Object[]{rows.getString(1), rows.getString(2), rows.getString(3),
                        rows.getString(4), rows.getString(5), rows.getString(6), rows.getDate(7)};

                /* You can also get other types
                 * int getInt()
                 * boolean getBoolean()
                 * double getDouble()
                 * float getFloat()
                 * long getLong()
                 * short getShort()


        catch (SQLException ex) {

            // String describing the error

            System.out.println("SQLException: " + ex.getMessage());

            // Vendor specific error code

            System.out.println("VendorError: " + ex.getErrorCode());

        catch (ClassNotFoundException e) {
            // Executes if the driver can't be found

        // Increase the font size for the cells in the table

        table.setFont(new Font("A", Font.PLAIN, 12));

        // Increase the size of the cells to allow for bigger fonts


        // Allows the user to sort the data


        // Adds the table to a scrollpane

        JScrollPane scrollPane = new JScrollPane(table);

        // Adds the scrollpane to the frame

        frame.add(scrollPane, BorderLayout.CENTER);

        // Creates a button that when pressed executes the code
        // in the method actionPerformed

        JButton addPres = new JButton("Add");

        addPres.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e){

                String sfridge = "", sacn = "",suln = "", sreq = "", 
                sdate = "",sshop="";

                // getText returns the value in the text field

                sfridge = tfridge_num.getText();
                sacn = tacn.getText();
                suln = tuln.getText();
                //sshop = combobox.getSelectedIndex();
                sreq = treq_id.getText();
                sdate = tdatefr.getText();

                // Will convert from string to date

                SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy");

                try {
                    daterequest = dateFormatter.parse(sdate);
                    sqldaterequest = new java.sql.Date(daterequest.getTime());
                } catch (ParseException e1) {


                Object[] fridge = {sfridge, sacn,suln,sshop,sreq,sqldaterequest};



        JButton removePres = new JButton("Remove");

        removePres.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e){

                // Will remove which ever row that is selected




        // Define values for my labels

        lfridge_num = new JLabel("Fridge No");
        lacn = new JLabel("AC/No");
        luln = new JLabel("ULN");
        lshop_id = new JLabel("Shop");
        lreq_id = new JLabel("Request By");
        ldatefr = new JLabel("Date Request");

        // Define the size of text fields

        tfridge_num = new JTextField(10);
        tacn = new JTextField(10);
        tuln =new JTextField(10);

     ** Statement sqlState = conn.createStatement();
        String selectStuff="select shop_id,detail from shop";
        ResultSet rows = sqlState.executeQuery(selectStuff);

          //string tshop_id.addItem("shop_id");
            String s=request.getParameter(tshop_id);


        treq_id=new JTextField(3);

        // Set default text and size for text field

        tdatefr = new JTextField("dd-MM-yyyy", 10);

        // Create a panel to hold editing buttons and fields

        JPanel inputPanel = new JPanel();
        inputPanel.setBounds(0, 0, 400, 200);
       // inputPanel.setLayout(null);

        // Put components in the panel


        // Add the component panel to the frame

        frame.add(inputPanel, BorderLayout.SOUTH);
        frame.setSize(1200, 500);


3 Years
Discussion Span
Last Post by asaidi

a few remarks:
1. put your code in separate methods. the main method is just to initiate the application, nothing more
2. never allow your main method to throw exceptions
3. be more clear as to what it is. you want to 'store' the value from the combobox... in the memory? in the db?
4. be more specific as to what it is you are having trouble with. putting the values in the combobox? getting the selected value? inserting that value in the db?


thank you very much for your remarks..
i m just learning then i put all in main..
the value selected will be stored in db table..
please check the image attachement of my frame
for example requested by looks in another table called requested and the reference is saved to the fridge table


your question is too broad, not clear anything, where is JComboBox, or where will be, etc..., must agree with @stultuske

and don't to use static variables, move everything from main class to standard constructor

public class Lesson37 extends JFrame {

   public Lesson37 () {
      //here to create a GUI

   public static void main(String[] args) {
       SwingUtilities.invokeLater(new Runnable() {
          public void run() {
              new Lesson37();
i have this 
 1st i have this in my frame

JComboBox tshop_id = new JComboBox();
     lshop_id = new JLabel("Shop");

     Statement sqlState = conn.createStatement();
    String selectStuff="select shop_id,detail from shop";
    ResultSet rows = sqlState.executeQuery(selectStuff);
       string tshop_id.addItem("shop_id");
       String s=request.getParameter(tshop_id);
       tshop_id.setVisible(true); `
    to show result in combobox and let the user choose from combobox then the value is saved to the db
    then add the combobox to the panel
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.