如何从一个ComboBox到java中的另一个ComboBox获取所选项目的相关数据

时间:2016-07-13 11:54:41

标签: java combobox jframe

我正在创建一个程序,其中我有两个组合框“ jComboBox1 ”& “的 jComboBox2 ”。 “jComboBox1”正在从数据库中检索所有库。 而“jComboBox2”应该带来所选银行的所有账户。现在,我设法检索“jComboBox1”中的所有库。但我不明白如何将它与第二个组合框连接 我的代码如下。

package frame;

import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.swing.*;
//import org.apache.pdfbox.pdmodel.*;
import java.io.*;

public class print_cheque extends javax.swing.JFrame  {
    public print_cheque() {
        initComponents();
        Connection con = null;
        //Statement st =  null;
        String query = "Select bnk_nm from d_bank_mst";
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ora10g", "payablek", "payablek");
            System.out.println("connection successful");

            java.sql.Statement st = con.createStatement();
            ResultSet rs = st.executeQuery(query);

            while (rs.next()) {
                String bank = rs.getString(1);
                jComboBox1.addItem(bank);
            }
            //con.close();
            st.close();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, e);
        }

    }

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

        jComboBox1 = new javax.swing.JComboBox<>();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jComboBox2 = new javax.swing.JComboBox<>();
        jLabel3 = new javax.swing.JLabel();
        jComboBox3 = new javax.swing.JComboBox<>();
        jLabel4 = new javax.swing.JLabel();
        jComboBox4 = new javax.swing.JComboBox<>();
        jRadioButton1 = new javax.swing.JRadioButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Bank Name");

        jLabel2.setText("Account No");

        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel3.setText("From Cheque No");

        jComboBox3.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel4.setText("To Cheque No");

        jComboBox4.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jRadioButton1.setText("Cash");
        jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton1ActionPerformed(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()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(33, 33, 33)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jComboBox2, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jComboBox3, 0, 253, Short.MAX_VALUE)
                        .addComponent(jComboBox4, 0, 253, Short.MAX_VALUE))
                    .addComponent(jRadioButton1))
                .addContainerGap(49, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(64, 64, 64)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addGap(18, 18, 18)
                .addComponent(jRadioButton1)
                .addContainerGap(82, Short.MAX_VALUE))
        );

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

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

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

    public static void main(String args[]) {
        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(print_cheque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(print_cheque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(print_cheque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(print_cheque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new print_cheque().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JComboBox<String> jComboBox1;
    private javax.swing.JComboBox<String> jComboBox2;
    private javax.swing.JComboBox<String> jComboBox3;
    private javax.swing.JComboBox<String> jComboBox4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JRadioButton jRadioButton1;
}

3 个答案:

答案 0 :(得分:2)

试试这个

package com.example.user.smgapp;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import java.util.HashMap;
import java.util.List;

public class Prd_grid_adapter extends BaseAdapter {


    List<HashMap<String, String>> Category_listData;
    HashMap<String, String> map;
    Context context;
    Typeface face;
    String wishList_url, remove_wishList_url;
    Cursor cursor;
    NavigationDrawer nav = new NavigationDrawer();

    private static LayoutInflater inflater = null;

    public Prd_grid_adapter(Activity context, List<HashMap<String, String>> aList) {
        // TODO Auto-generated constructor stub
        Category_listData = aList;
        /*/for(int i=1;i<aList.size();i++)
        {
            Category_listData.add(aList.get(i));
        }*/
        this.context = context;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);


    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return Category_listData.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public class Holder {
        TextView name, price, original_price;
        ImageView img, wish_list;
    }

    @Override
    public View getView(final int position, final View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        final Holder holder = new Holder();
        final View rowView;
        this.face = Typeface.createFromAsset(context.getAssets(), "fonts/OpenSans-Regular.ttf");
        rowView = inflater.inflate(R.layout.grid_item_view, null);
        holder.name = (TextView) rowView.findViewById(R.id.p_name);
        holder.img = (ImageView) rowView.findViewById(R.id.p_img);
        holder.wish_list = (ImageView) rowView.findViewById(R.id.wish_list);
        holder.price = (TextView) rowView.findViewById(R.id.p_price);
        holder.original_price = (TextView) rowView.findViewById(R.id.orginal_p);
        map = Category_listData.get(position);
        holder.name.setTypeface(face);
        holder.name.setText(map.get("product_name"));
        Log.e("wish list staus..", "wishlist status.." + map.get("is_wishlist"));
        if (map.get("is_wishlist").equals("0")) {
            holder.wish_list.setImageResource(R.drawable.empty_wishlist);
        } else {
            holder.wish_list.setImageResource(R.drawable.wishlist);
        }


        holder.wish_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SingletonActivity.custidstr.isEmpty()) {
                    Toast.makeText(context, "Ur not logged in,Please Login", Toast.LENGTH_SHORT).show();

                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setTitle("Alert!");
                    builder.setMessage("Ur not logged in")
                            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    Intent intent = new Intent(context, Login.class);
                                    context.startActivity(intent);
                                }


                            });
                    // Create the AlertDialog object and return it
                    builder.show();

                } else {
                    wishList_url = SingletonActivity.API_URL + "api/add_wishlist.php?customer_id=" + SingletonActivity.custidstr + "&product_id=" + Category_listData.get(position).get("product_id");
                    remove_wishList_url = SingletonActivity.API_URL + "api/remove_item_wishlist.php?customerid=" + SingletonActivity.custidstr + "&productid=" + Category_listData.get(position).get("product_id");
                    Log.e("wishlist api..", "wish list api.." + wishList_url);
                    Log.e("remove wishlist api..", "remove wish list api.." + remove_wishList_url);
                    v.setActivated(!v.isActivated());
                    String wish_status = map.get("is_wishlist");
                    Log.e("wish status..", "wish status.." + wish_status);
                    int stat = Integer.parseInt(wish_status);
                   // notifyDataSetChanged();

                    /*if (wish_status=="Product already exists in wishlist"){
                        Toast.makeText(context,"removed....",Toast.LENGTH_SHORT).show();
                        nav.removeFromwishList(remove_wishList_url);
                        holder.wish_list.setImageResource(R.drawable.empty_wishlist);

                    }
                    else
                    {
                        nav.addTowishList(wishList_url);
                        Toast.makeText(context,"addedd..",Toast.LENGTH_SHORT).show();
                        holder.wish_list.setImageResource(R.drawable.wishlist);
                    }*/
                    if (stat == 0) {
                        nav.addTowishList(wishList_url);
                        Toast.makeText(context, "addedd..", Toast.LENGTH_SHORT).show();
                        holder.wish_list.setImageResource(R.drawable.wishlist);
                 //       notifyDataSetChanged();
                    /*   ((Activity)context).finish();
                        Intent i=   ((Activity) context).getIntent();
                        context.startActivity(i);*/

                      //

                    } else {
                        nav.removeFromwishList(remove_wishList_url);
                        holder.wish_list.setImageResource(R.drawable.empty_wishlist);
                        Toast.makeText(context, "removed....", Toast.LENGTH_SHORT).show();
                      /* ((Activity)context).finish();
                        Intent i=   ((Activity) context).getIntent();
                        context.startActivity(i);*/
                  //      notifyDataSetChanged();
                    }
                   /* v.setActivated(!v.isActivated());
                    if (v.isActivated()){
                        Toast.makeText(context,"addedd..",Toast.LENGTH_SHORT).show();
                        holder.wish_list.setImageResource(R.drawable.wishlist);
                        nav.addTowishList(wishList_url);
                    }
                    else {
                        Toast.makeText(context,"removed....",Toast.LENGTH_SHORT).show();
                        nav.removeFromwishList(remove_wishList_url);
                        holder.wish_list.setImageResource(R.drawable.empty_wishlist);
                    }*/


                }


            }
        });


        if (map.get("special_price").equals("0.00")) {
            holder.price.setVisibility(View.INVISIBLE);
            // holder.o_price.setVisibility(View.INVISIBLE);
            holder.original_price.setText("Rs." + map.get("product_price"));
            holder.original_price.setTextAppearance(context, R.style.product_price_txt);

        } else {
            holder.price.setText("Rs." + map.get("special_price"));
            holder.original_price.setText("Rs." + map.get("product_price"));
            holder.original_price.setPaintFlags(holder.original_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        }
       /* holder.price.setText("Rs." + map.get("special_price"));
        holder.original_price.setText("Rs."+map.get("product_price"));
        holder.original_price.setPaintFlags(holder.original_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);*/
        Picasso.with(context).load(map.get("product_image")).placeholder(R.drawable.loading)
                .fit().into(holder.img);
        return rowView;
    }

}
import java.beans.Statement;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.swing.JComboBox;

import javax.swing.JOptionPane;

/**
 *
 * @author Sher Sodha
 */
public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    Connection con = null;
    java.sql.Statement stmt = null;

    public NewJFrame() throws ClassNotFoundException, SQLException {
        initComponents();
        Class.forName("oracle.jdbc.driver.OracleDriver");
        con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ora10g", "payablek", "payablek");
        System.out.println("connection successful");
        String query = "Select bnk_nm from d_bank_mst";
        java.sql.Statement st = con.createStatement();
        ResultSet rs = st.executeQuery(query);

        while (rs.next()) {
            String bank = rs.getString(1);
            jComboBox1.addItem(bank);
        }

        rs.close();
    }

    /**
     * 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() {

        jComboBox1 = new javax.swing.JComboBox<>();
        jComboBox2 = new javax.swing.JComboBox<>();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(null);

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item3", "Item 4" }));
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });
        getContentPane().add(jComboBox1);
        jComboBox1.setBounds(60, 32, 56, 20);

        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        getContentPane().add(jComboBox2);
        jComboBox2.setBounds(50, 100, 56, 20);

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

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           

        JOptionPane.showConfirmDialog(null, "ello");       // TODO add your handling code here:
        JComboBox cb = (JComboBox) evt.getSource();

        String banknm = (String) cb.getSelectedItem();
        JOptionPane.showMessageDialog(null, banknm);

        try {
            stmt = con.createStatement();
        } catch (SQLException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        ResultSet rs2 = null;

        String Query = "Select  colouumNafromme  from tablename where bnk_nm=" + banknm + " ";
        try {
            rs2 = stmt.executeQuery(Query);
        } catch (SQLException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            while (rs2.next()) {
                try {
                    jComboBox2.addItem(rs2.getString(1));
                } catch (SQLException ex) {
                    Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }


    }                                          

    /**
     * @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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

答案 1 :(得分:0)

PSEUDO-CODE 所有这些都发生在ActionListener

  • jComboBox1的ActionListener需要调用jComboBox1.getSelectedItem()
  • 字符串(或jComboBox1的任何对象类型)可用于从数据库中获取适用帐户的列表。
  • 调用jComboBox2.removeAllItems()清空jComboBox2
  • 对于列表中的每个帐户,请致电jComboBox2.addItem(Account)

答案 2 :(得分:0)

JComboBox中有几个方法,如getSelectedItem(), getSelectedIndex(),可用于从中获取和操作数据,也可以使用ActionListener注册JComboBox。

例如

jComboBox1.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent event) {
        JComboBox<String> jComboBox2 = (JComboBox<String>) event.getSource();
        String str = (String) jComboBox2.getSelectedItem();

        if (str.equals("A")) {
            System.out.println("AAA");
        } else if (str.equals("B")) {
            System.out.println("BBB!");
        }
    }
});