小编典典

扩展AbstractTableModel中的自定义setValueAt方法

java

因此,我正在用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语句。我不确定如何执行它们。如果有人可以就任何这些问题或我可能错过的任何其他问题提供一些指导,我将不胜感激。


阅读 169

收藏
2020-11-26

共1个答案

小编典典

让我们忽略代码中所有“有趣的”问题,并专注于 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

2020-11-26