当前位置: 首页 > 面试题库 >

扩展AbstractTableModel中的自定义setValueAt方法

尉迟正平
2023-03-14
问题内容

因此,我正在用Java开发DVD租赁系统,并且遇到了视图问题。这是我的代码:

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.*;
public class RentalSystem extends JFrame {

JMenuBar menuBar;
JMenuItem insertMember;
JMenuItem deleteMember;
JMenuItem editMember;
JMenuItem retrieveMember;
JMenuItem insertRelease;
JMenuItem deleteRelease;
JMenuItem editRelease;
JMenuItem retrieveRelease;
JMenu menu;
JMenu menu2;
JComboBox searchMember;
JComboBox searchRelease;
JButton adminButton;
JButton userButton;
JButton existingUser;
JButton newUser;
JTable memberTable; 
JTable releaseTable; 
int existingUserCheck = 1; //0 = existing user, 1 = new user
int adminCheck = 1; //0 = admin, 1 = customer


public RentalSystem()
{
    super("Tape/DVD/Game Rental System");
    setBounds(0,0,1000,500);
    //while(adminCheck == 0)
    {
        display2();
        while(existingUserCheck == 0) {

        }
    }

}
private class MenuActionListener implements ActionListener {

      public void actionPerformed(ActionEvent e) {

        if(e.getSource() == "insertMember");
        {
            String name = JOptionPane.showInputDialog("Enter Last Name:");
            String name2 = JOptionPane.showInputDialog("Enter First Name:");
            String ss = JOptionPane.showInputDialog("Enter Social Security Number:");
            int a = Integer.parseInt(ss);
            String email = JOptionPane.showInputDialog("Enter Email Address:");
            String phoneNumber = JOptionPane.showInputDialog("Enter Phone Number:");
            int b = Integer.parseInt(phoneNumber);
            String address = JOptionPane.showInputDialog("Enter Address:");

            Member member = new Member(name, name2, a, email, b, address);
            //add member to table

        }
        if(e.getSource() == "deleteMember");
        {

        }
        if(e.getSource() == "editMember");
        {

        }
        if(e.getSource() == "retrieveMember");
        {

        }
        if(e.getSource() == "insertRelease");
        {
            String title = JOptionPane.showInputDialog(this  ,"Enter Title:");
            String type = JOptionPane.showInputDialog(this  ,"Enter Type(Tape/DVD/Game):");
            String releaseYear = JOptionPane.showInputDialog(this  ,"Enter Year of Release:");
            int a = Integer.parseInt(releaseYear);
            String price = JOptionPane.showInputDialog(this  ,"Enter Price:");
            int b = Integer.parseInt(price);


            Item item = new Item(title, type, a, b);
            //add item to table

        }
        if(e.getSource() == "deleteRelease");
        {

        }
        if(e.getSource() == "editRelease");
        {

        }
        if(e.getSource() == "retrieveRelease");
        {

        }
      }
    }

private class ComboBoxActionListener implements ActionListener {


    public void actionPerformed(ActionEvent e) {

        String s = (String) searchMember.getSelectedItem();
        String f = (String) searchRelease.getSelectedItem();


            if(s.equals("Last Name")){

            }
            else if(s.equals("First Name")){
            }
            else if(s.equals("Phone Number")){
            }
            else if(s.equals("Member ID")){
            }

            if(f.equals("Title")){

            }
            else if(f.equals("Category")){
            }
            else if(f.equals("Type")){
            }
            else if(f.equals("Rental ID")){

            }


            if(e.getSource() == "Existing User")
            {

            }


    }

}

private class ButtonListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {

        if(e.getSource() == adminButton)
        {
            menuBar = new JMenuBar();
            menu = new JMenu("Members");
            menuBar.add(menu);
            menu2 = new JMenu("Releases");
            menuBar.add(menu2);

            insertMember = new JMenuItem("Insert New Member");
            deleteMember = new JMenuItem("Delete Member");
            editMember = new JMenuItem("Edit Member");
            retrieveMember = new JMenuItem("Retrieve Member");
            menu.add(insertMember);
            menu.add(deleteMember);
            menu.add(editMember);
            menu.add(retrieveMember);
            insertRelease = new JMenuItem("Insert New Release");
            deleteRelease = new JMenuItem("Delete Release");
            editRelease = new JMenuItem("Edit Release");
            retrieveRelease = new JMenuItem("Retrieve Release");
            menu2.add(insertRelease);
            menu2.add(deleteRelease);
            menu2.add(editRelease);
            menu2.add(retrieveRelease);

            JScrollPane c  = new JScrollPane();
            JScrollPane b = new JScrollPane();


            TableModel memberModel = new MemberTableModel();
            TableModel itemModel = new ItemTableModel();
            memberTable = new JTable(memberModel);
            releaseTable = new JTable(itemModel);

            c.add(memberTable);
            c.add(releaseTable);

            String[] searchMemberChoices = {"Search Members By:", "Last Name", "First Name","Phone Number", "Member ID"};
            String[] searchReleaseChoices = {"Search Releases By:", "Title" , "Category", "Type", "Release ID" };
            searchMember = new JComboBox(searchMemberChoices);
            searchRelease = new JComboBox(searchReleaseChoices);


            //add(c, BorderLayout.CENTER);
            //add(b, BorderLayout.SOUTH);
            add(searchMember, BorderLayout.WEST);
            add(searchRelease, BorderLayout.EAST);
            add(menuBar, BorderLayout.NORTH);

            setVisible(true);
            setResizable(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);

            insertMember.addActionListener(new MenuActionListener());
            deleteMember.addActionListener(new MenuActionListener());
            editMember.addActionListener(new MenuActionListener());
            retrieveMember.addActionListener(new MenuActionListener());
            insertRelease.addActionListener(new MenuActionListener());
            deleteRelease.addActionListener(new MenuActionListener());
            editRelease.addActionListener(new MenuActionListener());
            retrieveRelease.addActionListener(new MenuActionListener());
            searchMember.addActionListener(new ComboBoxActionListener());
            searchRelease.addActionListener(new ComboBoxActionListener());
        }
        if(e.getSource() == userButton)
        {
            adminCheck = 1;

            menuBar = new JMenuBar();
            menu = new JMenu("Members");
            menuBar.add(menu);
            menu2 = new JMenu("Releases");
            menuBar.add(menu2);


            retrieveMember = new JMenuItem("Retrieve Member");
            menu.add(retrieveMember);
            retrieveRelease = new JMenuItem("Retrieve Release");
            menu2.add(retrieveRelease);

            JScrollPane c  = new JScrollPane();
            JScrollPane b = new JScrollPane();


            TableModel memberModel = new MemberTableModel();
            TableModel itemModel = new ItemTableModel();
            memberTable = new JTable(memberModel);
            releaseTable = new JTable(itemModel);



            c.add(memberTable);
            c.add(releaseTable);


            String[] searchMemberChoices = {"Search Members By:", "Last Name", "First Name","Phone Number", "Member ID"};
            String[] searchReleaseChoices = {"Search Releases By:", "Title" , "Category", "Type", "Release ID" };
            searchMember = new JComboBox(searchMemberChoices);
            searchRelease = new JComboBox(searchReleaseChoices);


            //add(c, BorderLayout.CENTER);
            //add(b, BorderLayout.SOUTH);
            add(searchMember, BorderLayout.WEST);
            add(searchRelease, BorderLayout.EAST);
            add(menuBar, BorderLayout.NORTH);


            setVisible(true);
            setResizable(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);


            insertMember.addActionListener(new MenuActionListener());
            deleteMember.addActionListener(new MenuActionListener());
            editMember.addActionListener(new MenuActionListener());
            retrieveMember.addActionListener(new MenuActionListener());
            insertRelease.addActionListener(new MenuActionListener());
            deleteRelease.addActionListener(new MenuActionListener());
            editRelease.addActionListener(new MenuActionListener());
            retrieveRelease.addActionListener(new MenuActionListener());
            searchMember.addActionListener(new ComboBoxActionListener());
            searchRelease.addActionListener(new ComboBoxActionListener());

        }



        if(e.getSource() == existingUser);
        {

        }
         if(e.getSource() == newUser)
            {
                existingUserCheck = 1;
                JTextField field1 = new JTextField("");
                JTextField field2 = new JTextField("");
                JTextField field3 = new JTextField("");
                JTextField field4 = new JTextField("");
                JTextField field5 = new JTextField("");
                JTextField field6 = new JTextField("");

                JPanel panel = new JPanel(new GridLayout(0, 1));
                panel.add(new JLabel("Last Name:"));
                panel.add(field1);
                panel.add(new JLabel("First Name:"));
                panel.add(field2);
                panel.add(new JLabel("Social Security #:"));
                panel.add(field3);
                panel.add(new JLabel("Email:"));
                panel.add(field4);
                panel.add(new JLabel("Phone Number:"));
                panel.add(field5);
                panel.add(new JLabel("Address"));
                panel.add(field6);
                add(panel);
                int result = JOptionPane.showConfirmDialog(null, panel, "Registration",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
                if (result == JOptionPane.OK_OPTION) {

                    int ss = Integer.parseInt(field3.getText());
                    int phoneNumber = Integer.parseInt(field5.getText());

                      //memberTable.addMember(field1.getText(),field2.getText(), ss, field4.getText(), phoneNumber, field6.getText());

                }
            }
    }
}
class MemberTableModel extends AbstractTableModel {

    private String[]  headers = {"Last Name", "First Name", "SS#", "Email", "Phone Number", "Address"};


    @Override
    public int getColumnCount() {

        return headers.length;
    }

    @Override
    public int getRowCount() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public Object getValueAt(int arg0, int arg1) {
        // TODO Auto-generated method stub
        return null;
    }
    public void setValueAt(Member a, int rowIndex, int colIndex)
    {

    }

}
class ItemTableModel extends AbstractTableModel {

    @Override
    public int getColumnCount() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public int getRowCount() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public Object getValueAt(int arg0, int arg1) {
        // TODO Auto-generated method stub
        return null;
    }
    public void setValueAt()
    {

    }

}
public void display()//displays first screen:admin/user log-in
{
     userButton = new JButton("User");
     adminButton = new JButton("Admin");

    JPanel panel = new JPanel(new GridLayout(0, 1));
    panel.add(userButton);
    panel.add(adminButton);
    add(panel);

    userButton.addActionListener(new ButtonListener());
    adminButton.addActionListener(new ButtonListener());


    setVisible(true);
    setResizable(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

}

public void display2()//displays second screen:user log-in / register
{
     existingUser = new JButton("Existing User");
     newUser = new JButton("New User");

    JPanel panel = new JPanel(new GridLayout(0, 1));
    panel.add(newUser);
    panel.add(existingUser);
    add(panel);

    existingUser.addActionListener(new ButtonListener());
    newUser.addActionListener(new ButtonListener());


    setVisible(true);
    setResizable(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

}
public void display3() //displays user screen/functionality
{

}
public static void main(String[] args) {

    JFrame frame = new RentalSystem();

}
}

现在,Member和Item只是我制作的代表用户(成员)和电影/游戏(Item)的对象类。

public class Member {
 int status;
 String firstName;
 String lastName;
 int ss;
 String email;
 int phoneNumber;
 String address;
 int memberID;

 public Member()
 {

 }
 public Member(String firstName, String lastName, int ss, String email, int phoneNumber, String address)
 {
     this.firstName = firstName;
     this.lastName = lastName;
     this.ss = ss;
     this.email = email;
     this.phoneNumber = phoneNumber;
     this.address = address;
 }

public void setName(String firstName, String lastName)
 {
     this.firstName = firstName;
     this.lastName = lastName;
 }
 public String getName()
 {
     return firstName + " " + lastName;
 }
 public void setSS(int ss)
 {
     this.ss = ss;
 }
 public int getSS()
 {
     return ss;
 }
 public void setEmail(String email)
 {
     this.email = email;
 }
 public String getEmail()
 {
     return email;
 }
 public void setPhoneNumber(int phoneNumber)
 {
     this.phoneNumber = phoneNumber;
 }
 public int getPhoneNumber()
 {
     return phoneNumber;
 }
 public void setAddress(String address)
 {
     this.address = address;
 }
 public String getAddress()
 {
     return address;
 }
 public void setMemberID(int memberID)
 {
     this.memberID = memberID;
 }
 public int getMemberID()
 {
     return memberID;
 }
 public void setStatus(int status)
 {
     this.status = status;
 }
 public int getStatus()
 {
     return status;
 }
}

public class Item {

String title;
String type;
int releaseYear;
int rentalID;
int price;
boolean inStock;

public Item()
{

}
public Item(String title, String type, int releaseYear, int price)
{
    this.title = title;
    this.type = type;
    this.releaseYear = releaseYear;
    this.price = price;

}
public void setTitle(String title)
{
    this.title = title;
}
public String getTitle()
{
    return title;
}
public void setReleaseYear(int releaseYear)
{
    this.releaseYear = releaseYear;
}
public int getReleaseYear()
{
    return releaseYear;
}
public void setRentalID(int rentalID)
{
    this.rentalID = rentalID;
}
public int getRentalID()
{
    return rentalID;
}
public void setPrice(int price)
{
    this.price = price;
}
public int getPrice()
{
    return price;
}

}

我的问题是,我对如何创建自定义的,覆盖的“
SetValueAt()”方法以用“成员/项”中的信息填充JTables感到困惑。另一个问题是侦听器类中的所有空if语句。我不确定如何执行它们。如果有人可以就任何这些问题或我可能错过的任何其他问题提供一些指导,我将不胜感激。


问题答案:

让我们忽略代码中所有“有趣的”问题,并专注于 TableModel

表格是数据的二维矩阵,分布在一系列行和列上

TableModel提供,通过该合同JTable(视图)可以与由表示的数据进行交互TableModel

public interface TableModel
{
    public int getRowCount();
    public int getColumnCount();
    public String getColumnName(int columnIndex);
    public Class<?> getColumnClass(int columnIndex);
    public boolean isCellEditable(int rowIndex, int columnIndex);
    public Object getValueAt(int rowIndex, int columnIndex);
    public void setValueAt(Object aValue, int rowIndex, int columnIndex);
    public void addTableModelListener(TableModelListener l);
    public void removeTableModelListener(TableModelListener l);
}

这很重要,因为您的数据需要符合此合同。

您有一个Member具有一系列已定义属性的类,每个属性代表一个可能的列值,这使每个实例都成为Member一个“行”数据。

您需要决定的第一件事是如何管理所有Members。既然您已经声明需要“动态”(或可变)模型,ArrayList则可以使用更好的数据结构之一,因为它可以增长以满足您的需求并且具有快速的非顺序访问(您可以从中获取值)在随机点处快速)。

public class MemberTableModel extends AbstractTableModel {

    private String[] headers = {"Last Name", "First Name", "SS#", "Email", "Phone Number", "Address"};
    private List<Member> members;

    public MemberTableModel() {
        members = new ArrayList<>(25);
    }

    public MemberTableModel(List<Member> members) {
        this();
        this.members.addAll(members);
    }

    public MemberTableModel(Member... members) {
        this(Arrays.asList(members));
    }

    @Override
    public int getRowCount() {
        return members.size();
    }

    @Override
    public int getColumnCount() {
        return headers.length;
    }

    @Override
    public String getColumnName(int column) {
        return headers[column];
    }

Okay, now we need some we to get the column for a particular row…

    protected Member getMemberAt(int row) {
        return members.get(row);
    }

    @Override
    public Object getValueAt(int row, int col) {
        Object value = null;
        Member member = getMemberAt(row);
        switch (col) {
            case 0:
                // Need getter for last name
                break;
            case 1:
                // Need getter for first name
                break;
            case 2:
                value = member.getSS();
                break;
            case 3:
                value = member.getEmail();
            case 4:
                value = member.getPhoneNumber();
            case 5:
                value = member.getAddress();
        }
        return value;
    }

Setting the value is pretty much the same process…

    @Override
    public void setValueAt(Object value, int rowIndex, int colIndex) {
        Member member = getMemberAt(rowIndex);
        switch (colIndex) {
            case 0:
                member.setName(value.toString(), member.getLastName());
                break;
            case 1:
                member.setName(member.getFirstName(), value.toString());
                break;
            case 2:
                if (value instanceof Integer) {
                    member.setSS((Integer) value);
                }
                break;
            case 3:
                member.setEmail(value.toString());
                break;
            case 4:
                if (value instanceof Integer) {
                    member.setPhoneNumber((Integer)value);
                }
                break;
            case 5:
                member.setAddress(value.toString());
                break;
        }
        fireTableRowsUpdated(rowIndex, colIndex);
    }
}

Note, there is no validation in this method, you should be checking to see if
the values meet your basic requirements for the data…

But, to make a table editable, you need to override the isCellEdtiable
method of the model…

@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
    return true;
}

Take add or remove members from the model, you need to supply the
functionality in your model, for example…

public void add(Member member) {
    int size = members.size();
    members.add(member);
    fireTableRowsInserted(size, size);
}

public void remove(Member member) {
    int index = members.indexOf(member);
    if (index > -1) {
        members.remove(member);
        fireTableRowsDeleted(index, index);
    }
}

Take a closer look at How to Use
Tables
and Collections Trail
for more details



 类似资料:
  • 本文向大家介绍Laravel框架中扩展函数、扩展自定义类的方法,包括了Laravel框架中扩展函数、扩展自定义类的方法的使用技巧和注意事项,需要的朋友参考一下 一、扩展自己的类 在app/ 下建立目录 libraries\class  然后myTest.php 类名格式 驼峰 myTest 在 app/start/global.php 用 make 载入 二、扩展自己的函数 在app/ 下建立目录

  • 目前 Mars 支持自定义 xlog 的加密部分和长短连协议加解包部分。需要强调的是想要自定义这些扩展,需要在本地编译 Mars 才可以,编译方法见 Mars Android 接入指南 和 Mars iOS/OS X 接入指南 中的编译部分。切记,在自定义实现时,可以增加函数,但是不能删除头文件中已有的函数,也不能修改头文件中的函数原型。 自定义 xlog 加密 xlog 的具体实现可以参考微信终

  • 问题内容: 我正在阅读另一个SO问题,即Swift do-try-catch语法。在他的回答中, rickster 为OP的自定义类创建了扩展。 Konrad77 评论说,这是“保持代码整洁的好方法。” 我尊重他们的知识,这使我相信我在自己的代码中遗漏了一点。 除了为我创建的类创建扩展之外,还有其他好处(除了整洁)还是原因?我可以将相同的功能直接放入类中。如果我是唯一使用该类的人,或者其他人将使用

  • 当我们在开发某些东西时,经常会需要我们自己的 error 类来反映在我们的任务中可能出错的特定任务。对于网络操作中的 error,我们需要 HttpError,对于数据库操作中的 error,我们需要 DbError,对于搜索操作中的 error,我们需要 NotFoundError,等等。 我们自定义的 error 应该支持基本的 error 的属性,例如 message,name,并且最好还有

  • 通过Envoy架构很容易扩展网络过滤器和HTTP过滤器。 有关如何添加网络过滤器和构建库并建立依赖关系的示例,请参见envoy-filter-example。 返回

  • 用户自定义扩展是用户自己创建的 JavaScript 文件,对 Selenium IDE 现有的功能进行定制以及功能扩展。通常这种定制和扩展是以自定义命令的形式来体现的,当然也不仅限于命令。 这里可以找到很多有用的扩展。 注意:这部分信息已经过时,我们将很快修改。 也许最受欢迎的 Selenium IDE 扩展就是流程控制,流程控制扩展将提供 while 循环和条件判断。这个扩展是 goto_se