JComboBox 帮助从数据库中删除数据

发布于 2024-11-07 19:57:39 字数 364 浏览 0 评论 0原文

我在数据库 employee 中有一个表,由两列 IDNameLastName 组成。

我到达将第二列中的数据添加到 JComboBox,就像下面的快照中一样!

在此处输入图像描述

现在如何从数据库中删除 JComboBox 中选定的员工?

我想添加名称类似于 I122-Name 的 ID 并使用 split 方法提取 ID,但我不想显示 ID。

有什么方法可以将 JComboBox 中的每个名称与包含员工 ID 的隐藏值关联起来吗?

I have a table in database employee composed by two columns ID and NameLastName.

I arrived to add data in the second column to a JComboBox like in the snapshot down!

enter image description here

Now how can I do to delete the selected employee in the JComboBox from DB?

I thought to add the ID with name like this I122-Name and use split method to extract the ID but I don't want to show the ID.

Is there any way to associate with each name in the JComboBox a hidden value that contains the employee ID?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

始终不够 2024-11-14 19:57:39
  • 创建一个具有这两个字段的 Employee 对象。
  • 重写 toString() 方法以输出员工姓名。
  • 将 Employee 对象放入 JComboBox 中,名称将显示,但您可以将所选对象转换为 Employee 并提取 id。
  • Create an Employee object that has both fields.
  • Override the toString() method to output the employee name.
  • Put the Employee objects in the JComboBox and the name will be displayed but you can cast the selected object to an Employee and pull out the id.
节枝 2024-11-14 19:57:39

您可以尝试这样做:

创建一个包含字段名称和 id 的 Employee 类,然后创建一个实现 ListCellRenderer 并扩展 JLabel 的类。将此类作为渲染器添加到 JComboBox。现在您可以在 JLabel 中将名称设置为文本。 现在,当您访问comboBox的元素时,它会返回您JLabel,您可以从您在JLabel中设置的位置获取名称作为可见值和id作为隐藏值。

JComboBox 的方法 getSelectedItem() 返回一个对象,该对象可以转换为放置在组合框中的任何对象。要获取用于渲染项目的组件,请调用 getRenderer()。

注意:- 您可以使用 JLabel 以外的其他组件。


演示:-

public class ComboRenderer extends JLabel implements ListCellRenderer{
    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index,
            boolean isSelected, boolean cellHasFocus) {

        if(value != null){
            Employee emp = (Employee) value;
            setText(emp.getName());
            return this;
        }
        return null;
    }

}

现在,您想要将项目添加到组合框的地方,请使用 combo.addItem(empObject);。它将在组合框中显示员工的姓名,当您执行 getSelectedItem() 时,它将返回员工对象,您将获得属于该 emp 对象的姓名和 ID。

You can try this:

Make an Employee class with field name and id then make a class which implements ListCellRenderer and extends JLabel. Add this class as a Renderer to your JComboBox. Now you can set Name as a text in JLabel. Now when ever you access comboBox's element it will return you JLabel and you can get name as visible value and id as hidden value from where you have set in JLabel.

JComboBox's method getSelectedItem() returns an Object that can be cast to whatever Object was placed in the combobox. To get the component used to render the items, call getRenderer().

Note:- You can use other component then JLabel.


A demo:-

public class ComboRenderer extends JLabel implements ListCellRenderer{
    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index,
            boolean isSelected, boolean cellHasFocus) {

        if(value != null){
            Employee emp = (Employee) value;
            setText(emp.getName());
            return this;
        }
        return null;
    }

}

Now where you want to add item to comboBox use combo.addItem(empObject);. It will display name of employee in comboBox and when you do getSelectedItem() it will return you the employee object and you will get name and id both belongs to that emp object.

御弟哥哥 2024-11-14 19:57:39

我不想显示 ID。

这个问题已经收到了 2 个很好的答案,但我想添加第三个答案,如果只是为了解决是否显示 ID 的问题(这不是问题的一部分,但应该是)。

屏幕截图

您要解雇哪个约翰·史密斯

SackEmployee.java

import java.awt.*;
import javax.swing.*;

class SackEmployee {
    public static void main(String[] args) {
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                Employee[] workforce = {
                    new Employee("Ali Ben Messaoud", 9823),
                    new Employee("Jane Brewer", 6348),
                    new Employee("John Smith", 1247),
                    new Employee("John Smith", 4385)
                };

                JComboBox employeeCombo = new JComboBox(workforce);

                EmployeeCellRenderer employeeCellRenderer = new EmployeeCellRenderer();
                employeeCombo.setRenderer(employeeCellRenderer);

                int result = JOptionPane.showConfirmDialog(
                    null,
                    employeeCombo,
                    "Fire Employee?",
                    JOptionPane.OK_CANCEL_OPTION);
                // cast selected item back to Employee.
                Employee employee = (Employee)employeeCombo.getSelectedItem();
                System.out.println( "Fire '" + employee + "' now?" );
                System.out.println( "Proceed: " + (result==JOptionPane.OK_OPTION) );
            }
        });
    }
}

class Employee {

    int id;
    String name;

    Employee(String name, int id) {
        this.id = id;
        this.name = name;
    }

    public String getIdString() {
        return "ID-" + id;
    }

    public String toString() {
        return getIdString() + ": " + name;
    }
}

class EmployeeCellRenderer implements ListCellRenderer {

    JLabel label = new JLabel();

    public Component getListCellRendererComponent(
        JList list,
        Object value,
        int index,
        boolean isSelected,
        boolean cellHasFocus) {

        Employee employee = (Employee)value;
        // distinguish between people of same name by adding ID.
        label.setText(employee.name + " (" + employee.getIdString() + ")");

        return label;
    }
}

> 输入/输出

prompt>java SackEmployee
Fire 'ID-9823: Ali Ben Messaoud' now?
Proceed: false

prompt>java SackEmployee
Fire 'ID-1247: John Smith' now?
Proceed: true

prompt>java SackEmployee
Fire 'ID-4385: John Smith' now?
Proceed: false

prompt>

I don't want to show the ID.

This question has already received 2 good answers, but I wanted to add this 3rd one if only to address the question of whether to show the ID (which was not part of the question, but should have been).

Screen Shot

Which John Smith are you going to fire?

enter image description here

SackEmployee.java

import java.awt.*;
import javax.swing.*;

class SackEmployee {
    public static void main(String[] args) {
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                Employee[] workforce = {
                    new Employee("Ali Ben Messaoud", 9823),
                    new Employee("Jane Brewer", 6348),
                    new Employee("John Smith", 1247),
                    new Employee("John Smith", 4385)
                };

                JComboBox employeeCombo = new JComboBox(workforce);

                EmployeeCellRenderer employeeCellRenderer = new EmployeeCellRenderer();
                employeeCombo.setRenderer(employeeCellRenderer);

                int result = JOptionPane.showConfirmDialog(
                    null,
                    employeeCombo,
                    "Fire Employee?",
                    JOptionPane.OK_CANCEL_OPTION);
                // cast selected item back to Employee.
                Employee employee = (Employee)employeeCombo.getSelectedItem();
                System.out.println( "Fire '" + employee + "' now?" );
                System.out.println( "Proceed: " + (result==JOptionPane.OK_OPTION) );
            }
        });
    }
}

class Employee {

    int id;
    String name;

    Employee(String name, int id) {
        this.id = id;
        this.name = name;
    }

    public String getIdString() {
        return "ID-" + id;
    }

    public String toString() {
        return getIdString() + ": " + name;
    }
}

class EmployeeCellRenderer implements ListCellRenderer {

    JLabel label = new JLabel();

    public Component getListCellRendererComponent(
        JList list,
        Object value,
        int index,
        boolean isSelected,
        boolean cellHasFocus) {

        Employee employee = (Employee)value;
        // distinguish between people of same name by adding ID.
        label.setText(employee.name + " (" + employee.getIdString() + ")");

        return label;
    }
}

E.G. I/O

prompt>java SackEmployee
Fire 'ID-9823: Ali Ben Messaoud' now?
Proceed: false

prompt>java SackEmployee
Fire 'ID-1247: John Smith' now?
Proceed: true

prompt>java SackEmployee
Fire 'ID-4385: John Smith' now?
Proceed: false

prompt>
梦情居士 2024-11-14 19:57:39

这是删除数据库中整行的简单代码。

    try{
      String str;
      con = DriverManager.getConnection("jdbc:mysql://:3306/database","user","password");
      stat = con.createStatement();
      ResultSet rs = stat.executeQuery("SELECT column_name FROM table_name where column_name = '"+jComboBox1.getSelectedItem().toString()+"';");
      while(rs.next()){
         Str = rs.getString(column_name);
      }
      stat.executeUpdate("DELETE FROM table_name where column_name = +"str"+");
    }
    rs.close();
    stat.close();
    con.close();
    catch(Exception e){
      System.out.println(e);
    }

here is simple code that will delete entire row in database.

    try{
      String str;
      con = DriverManager.getConnection("jdbc:mysql://:3306/database","user","password");
      stat = con.createStatement();
      ResultSet rs = stat.executeQuery("SELECT column_name FROM table_name where column_name = '"+jComboBox1.getSelectedItem().toString()+"';");
      while(rs.next()){
         Str = rs.getString(column_name);
      }
      stat.executeUpdate("DELETE FROM table_name where column_name = +"str"+");
    }
    rs.close();
    stat.close();
    con.close();
    catch(Exception e){
      System.out.println(e);
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文