java 如何根据从数据库中获取的值设置单选按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31555980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:46:49  来源:igfitidea点击:

How to set the Radio Button based on the value fetched from the database

javaswingjtablejradiobutton

提问by STEPHEN YAO

I have a JTablefilled with data about students (student id, name...), and when I select a row from a table, the form opens and its field need to be filled with same values (eg. if Johny Bravo was selected from the table.

JTable填充了关于 的数据students (student id, name...),当我从表中选择一行时,表单将打开并且其字段需要填充相同的值(例如,如果从表中选择了 Johny Bravo。

Then his name should be shown in text filed Name on the form, I did like this txtfieldName.setText(student.getName).

然后他的名字应该显示在表单上的文本字段 Name 中,我喜欢这个txtfieldName.setText(student.getName)

My question is how do I set my Radio buttonautomatically (my radio button is Male or Female) when I clicked the field.

我的问题是如何Radio button在单击该字段时自动设置我的(我的单选按钮是男性或女性)。

enter code here

tableGuest.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
    try{
        int row = tableGuest.getSelectedRow();
        String guestEdit=(tableGuest.getModel().getValueAt(row,     0).toString());


        String query = "Select guest_id,guest_fname,guest_lname,guest_contact,guest_age,guest_gender,guest_address,guest_email from guest_tbl where guest_id= '"+guestEdit+"'";

    PreparedStatement pst = con.prepareStatement(query);
    ResultSet rs = pst.executeQuery();

    buttonGroupEdit.add(rdbtnMaleEdit);
    buttonGroupEdit.add(rdbtnFemaleEdit);


                while(rs.next())
                {
                    String genderEdit=rs.getString("guest_gender"); 

                    if(genderEdit.equals("Male"))
                    {
                         rdbtnMaleEdit.setSelected(true); 
                    }
                    else if(genderEdit.equals("Female"))
                    {
                         rdbtnFemaleEdit.setSelected(true);
                    }
                    else
                    {
                    JOptionPane.showMessageDialog(null, "error !");
                    }


                    tfEditFname.setText(rs.getString("guest_fname"));
                    tfEditLname.setText(rs.getString("guest_lname"));
                    tfEditEmail.setText(rs.getString("guest_email"));

                    tfEditContact.setText(rs.getString("guest_contact"))
                }
                pst.close();


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

        }
    });

回答by dly

    String gender = "male" 
    // this comes from db - since we don't know the structure this is a plain guess.

    if (gender.equals("male") {
        rbtMale.setSelected(true); 
    } else {
        rbtFemale.setSelected(true); 
    } 

And like MadProgrammer said, you will need a ButtonGroupand addall relevant buttons to it.

就像 MadProgrammer 说的,你需要一个ButtonGroupadd所有相关的按钮。

private final ButtonGroup genderButtons = new ButtonGroup();
genderButtons.add(rbtMale);
genderButtons.add(rbtFemale);

回答by A.Aleem11

I've worked with same kinda solution in my work I am generating radiobutton with database values and showing them in java dialog.

我在我的工作中使用了相同的解决方案,我正在生成带有数据库值的单选按钮并在 java 对话框中显示它们。

We have a values from database stored in list like below:

我们有一个来自数据库的值存储在列表中,如下所示:

List Titles; //This is a list containing your database values

列表标题;//这是一个包含您的数据库值的列表

First count the values of this list elements:

首先计算这个列表元素的值:

int list_count=Titles.size();

int list_count=Titles.size();

Now to proceed with radio function first we need to convert list elements into array like below:

现在首先继续使用无线电功能,我们需要将列表元素转换为数组,如下所示:

String[] col = new String[list_count]; //created an array with limit of list count values
for(int i=0; i < list_count; i++){ 
col[i]=Titles.get(i).toString(); // add values of list into array with loop
}

Below is the function that is creating radio buttons with database array we created above:

下面是使用我们上面创建的数据库数组创建单选按钮的函数:

 public String get_key(int list_count, String[] col){

   JRadioButton jb[] = new JRadioButton[col.length]; //Create Radion button array

   ButtonGroup rb = new ButtonGroup(); //Group Radio Button

   JPanel panel = new JPanel( new GridLayout(0, 1) ); //Set layout of radion button to display each after other

   JScrollPane sp = new JScrollPane(panel); // Create a scrollpane to put all these radio button on that

   GridBagLayout gridbag = new GridBagLayout(); //Layout for scrollpane

sp.setViewportBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); //bordre for scrollpane

    List<Component> q = new ArrayList<>(); // q is a component to store and display each radio button

    JLabel h1=new JLabel("Select a value"); //put a heading on top of jpanel before radio button

    h1.setFont(new Font("Serif", Font.BOLD, 18)); // set heading text

    panel.add(h1); //add heading on top of jpanel

    panel.setBorder(new EmptyBorder(10, 10, 10, 10)); //set panel border to padding each radio button

    for(int i=0; i < list_count; i++){ 

     jb[i]=new JRadioButton(col[i]); //create radion button dynamacially "col[i]" is the value of each radio

     rb.add(jb[i]); //it is important also to put all radio in a group we created so only one element should be selected

     panel.add(jb[i]); // add all radio on jpanel

        }

sp.setPreferredSize( new Dimension( 350, 300 ) ); //set size of scrollpane

int act=JOptionPane.showConfirmDialog(null, sp, "Select Primary Key",JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE); //add and show scrollpane in dialog

}

Calling this function with parameter values we created first "list_count" & "col":

使用我们首先创建的“list_count”和“col”参数值调用此函数:

get_key(list_count, col);

回答by Karshanguna R

Create a Student.javaclass to get particular table value from database. In the current form AddStudentcreate a function call as getStudentListto fill the GUI form with database data to particular id.

创建一个Student.java类以从数据库中获取特定的表值。在当前表单中AddStudent创建一个函数调用,getStudentList以将数据库数据填充到 GUI 表单到特定的 id。

    public ArrayList<Student> getStudentList() {
    ArrayList<Student> studentList = new ArrayList<>();
    conn = DbConnection.ConnectDb();
    String selectQuery = "SELECT * FROM student";

    try {
        PreparedStatement pst = conn.prepareStatement();
        ResultSet rs = pst.executeQuery();
        Donor donor;

        while(rs.next()) {
            student = new Student(rs.getString("id"),
            rs.getString("gender"));
            studentList.add(student);
        }

    } catch (SQLException ex) {
        Logger.getLogger(Student.class.getName()).log(Level.SEVERE, null, ex);
    }
    return studentList; 
}

After create a function called showStudentto show the particular data value to called id.(In below code male,femaleare the checkbox values)

创建一个被调用的函数showStudent以向被调用的 id 显示特定数据值之后。(在下面的代码male,female中是复选框值)

    public void showStudent(int index) throws ParseException {
    if(getStudentList().get(index).getGender().equals("male")) {
                male.setSelected(true);
                female.setSelected(false);
                gender = "male";
            }
            else {
                female.setSelected(true);
                male.setSelected(false);
                gender = "female";
            }
    }

Set action to the jbutton, When get value id from jtextfieldthen fill the checkbox in particular gender value.

将操作设置为jbutton,当从中获取值 id 时,jtextfield然后填写特定性别值的复选框。