我的GUI显示了我的停车场中的车辆,以及我想在两个不同的VehicleTable(扩展JTable的类)中设置可用的车辆。对于可用的车辆,我希望可以通过代理(第三方软件)观察这些车辆。这两个表都显示了行中车辆的描述…为此,我创建了VehicleTableModel和Vehicle类。Vehicle类是一个抽象类,其子类是:Car、Truck、Trailer等。
我的问题是:在我当前的实现中,我认为不能很好地管理行的更新。您可以在车桌模型中看到(火...()方法)和托运代理GUI(协调员和听众)。我认为我已经通过使用Condor内部类在表之间进行更新部分解决了这个问题,但我不知道如何优化它们。例如,在删除或更新行的情况下,我使xxx表重新绘制();...整张桌子...
…另一种方式?
ShipperAgentGUI.java
public class ShipperAgentGUI extends JFrame implements ActionListener {
// Graphics variables..
// bla bla...
// Headers, TableModels, JTables for the tables
private COLUMNS[] parkModelHeader = {COLUMNS.IMAGE_COLUMN, COLUMNS.TARGA_COLUMN,
COLUMNS.CAR_TYPE_COLUMN, COLUMNS.MARCA_COLUMN, COLUMNS.STATE_COLUMN, COLUMNS.PTT_COLUMN };
private COLUMNS[] availablesModelHeader = {COLUMNS.IMAGE_COLUMN, COLUMNS.TARGA_COLUMN,
COLUMNS.CAR_TYPE_COLUMN, COLUMNS.MARCA_COLUMN };
private VehicleTableModel parkModel = new VehicleTableModel(parkModelHeader);
private VehicleTableModel availablesModel = new VehicleTableModel(availablesModelHeader);
private VehicleTable parkTable;
private VehicleTable availablesTable;
// My third-part software, a JADE agent:
protected ShipperAgent shipperAgent;
// --------------------------------------------------------------------------
// CONSTRUCTOR
ShipperAgentGUI(ShipperAgent agent) {
shipperAgent = agent; // valorizes the agent
setTitle("Shipper Agent: "+agent.getLocalName()+" GUI");
// graphic bla bla...
// Park Table and Available Table:
parkTable = new VehicleTable(parkModel);
// bla bla...
availablesTable = new VehicleTable(availablesModel);
// bla bla...
// JButtons: add/remove vehicle in Park Table and Available Table
btnPM_plus = new JButton();
btnPM_plus.setToolTipText("Add vehicle");
btnPM_plus.setIcon(...);
btnPM_plus.setActionCommand("+park");
btnPM_plus.addActionListener(this);
// similar things for other three buttons:
// remove from parkTable, add and remove from availablesTable
//bla bla...
// Data from agent:
Vector<Vehicle> veicoli = shipperAgent.getVehicles();
Iterator<Vehicle> I = veicoli.iterator();
while (I.hasNext()){
addVehicle(parkCoordinator, I.next());
}
showGui();
}
///////////////////////////////////////////////////////////////////////
// Methods:
public void showGui() {
// bla bla
}
//////////////////////////////////////////////
// actionPerformed method
@Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case "+park": {
new InsertVehicleJDialog(this, parkCoordinator);
} break;
case "-park": {
int selectedRow = parkTable.getSelectedRow();
if (selectedRow != -1)
removeVehicle(parkCoordinator, selectedRow);
} break;
case "+available": {
int selectedRow = parkTable.getSelectedRow();
if (selectedRow != -1){
addVehicle(availablesCoordinator, parkModel.getVehicleAt(selectedRow));
}
} break;
case "-available": {
int selectedRow = availablesTable.getSelectedRow();
if (selectedRow != -1)
removeVehicle(availablesCoordinator, selectedRow);
} break;
}
}
///////////////////////////////////////
// Add/Remove vehicle methods:
void addVehicle(Coordinator coordinator, Vehicle v) {
coordinator.notifyAndAddRow(v);
}
// mhm...
void removeVehicle(Coordinator coordinator, Vehicle v) {
int row = coordinator.indexOf(v);
if (row!=-1)
coordinator.notifyAndDeleteRow(row);
}
void removeVehicle(Coordinator coordinator, int index) {
coordinator.notifyAndDeleteRow(index);
}
// on dispose, delete the agent
public void dispose() {
super.dispose();
shipperAgent.doDelete();
}
///////////////////////////////////////
// INNER CLASS COORDINATOR:
protected abstract class Coordinator {
private VehicleTableModel tableModel;
public Coordinator(VehicleTableModel tm) {
tableModel = tm;
notifyRowUpdated();
}
public abstract void notifyAndAddRow(Vehicle vehicle);
public abstract void notifyAndDeleteRow(int rowIndex);
public abstract void notifyRowUpdated();
public int indexOf(Vehicle v) {
return tableModel.indexOf(v);
}
boolean vehicleExists(Vehicle vehicle){
int bool = indexOf(vehicle);
if (bool==-1) return false;
else return true;
}
}
// Coordinator for parkTable
Coordinator parkCoordinator = new Coordinator(parkModel) {
@Override
public void notifyAndAddRow(final Vehicle vehicle) {
if (!vehicleExists(vehicle)){ // is this the right control? Or in VehicleTableModel ?
shipperAgent.newTruck(vehicle.getPlate());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
parkModel.addRow(vehicle);
if (vehicle.getState().equals(Stato.DISPONIBILE))
availablesModel.addRow(vehicle);
// or with availablesCoordinator.notifyAndAddRow(vehicle) ?
// or with addVehicle(availablesCoordinator, vehicle) ?
// or with a kind of listener on vehicle's state ?
}
});
}
}
@Override
public void notifyAndDeleteRow(final int rowIndex) {
final Vehicle v = parkModel.getVehicleAt(rowIndex);
removeVehicle(availablesCoordinator, v); // Remove also from the "availables"
shipperAgent.removeTruck(v.getPlate());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
parkModel.removeRow(rowIndex);
}
});
}
@Override
public void notifyRowUpdated() {
parkModel.addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
switch (e.getType()) {
case (TableModelEvent.DELETE):
parkTable.repaint();
break;
case (TableModelEvent.UPDATE):
int row = e.getLastRow();
Vehicle v = parkModel.getVehicleAt(row);
if (v.getState().equals(Stato.DISPONIBILE)){
addVehicle(availablesCoordinator, v);
availablesTable.repaint();
} else
removeVehicle(availablesCoordinator, v);
parkTable.repaint();
break;
}
}
});
}
};
// Coordinator for availablesTable
Coordinator availablesCoordinator = new Coordinator(availablesModel) {
@Override
public void notifyAndAddRow(final Vehicle vehicle) {
if (!vehicleExists(vehicle)){ // is this the right control? Or in VehicleTableModel ?
vehicle.setStato(Stato.DISPONIBILE);
parkTable.repaint();
shipperAgent.activateTruck(vehicle.getPlate());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
availablesModel.addRow(vehicle);
}
});
}
}
@Override
public void notifyAndDeleteRow(final int rowIndex) {
Vehicle v = availablesModel.getVehicleAt(rowIndex);
if (v!=null){
v.setStato(Stato.NON_DISPONIBILE); // mhm
shipperAgent.deactivateTruck(v.getPlate());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
availablesModel.removeRow(rowIndex);
}
});
}
}
@Override
public void notifyRowUpdated() {
availablesModel.addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
switch (e.getType()) {
case (TableModelEvent.DELETE):
parkTable.repaint();
break;
case (TableModelEvent.UPDATE):
parkTable.repaint();
break;
}
}
});
}
};
}
VehicleTableModel.java
public class VehicleTableModel extends AbstractTableModel {
private ArrayList<Vehicle> vehicles ;
private COLUMNS[] header;
// possible column names:
public enum COLUMNS {
IMAGE_COLUMN,
TARGA_COLUMN,
CAR_TYPE_COLUMN,
MARCA_COLUMN,
STATE_COLUMN,
PTT_COLUMN,
};
///////////////////////////////////////////////////////
// Constructor:
public VehicleTableModel(COLUMNS[] headerTable) {
this.vehicles = new ArrayList<Vehicle>();
this.header = headerTable;
}
///////////////////////////////////////////////////////
// obligatory override methods (from AbstractTableModel):
@Override
public int getColumnCount() {
return header.length;
}
@Override
public int getRowCount() {
return vehicles.size();
}
@Override
public Object getValueAt(int row, int col) {
Object value = "?";
Vehicle v = vehicles.get(row);
if (v!=null) {
COLUMNS column = header[col];
switch (column) {
case IMAGE_COLUMN:
value = VehicleUtils.findImageByColumnCarType(v.getType());
break;
case TARGA_COLUMN:
value = v.getPlate();
break;
case CAR_TYPE_COLUMN:
value = VehicleUtils.findStringByColumnCarType(v.getType());
break;
// other cases... bla bla...
}
}
return value;
}
///////////////////////////////////////////////////////
// My methods:
public void addRow(Vehicle vehicle) {
vehicles.add(vehicle);
fireTableRowsInserted(0, getRowCount()); // is right?
}
/*public boolean removeRow(Vehicle vehicle) {
boolean flag = vehicles.remove(vehicle);
fireTableRowsDeleted(0, getRowCount()); // is right?
return flag;
}*/
public void removeRow(int row) {
vehicles.remove(row);
fireTableRowsDeleted(row, row); // is right?
}
public Vehicle getVehicleAt(int row) {
return vehicles.get(row);
}
public int indexOf(Vehicle v){
return vehicles.indexOf(v);
}
// found the corresponding column index
public int findColumn(COLUMNS columnName) {
for (int i=0; i<getColumnCount(); i++)
if (columnName.equals(header[i]))
return i;
return -1;
}
// a value in that column exist in the table?
private boolean controllIfExist(Object value, int col) {
boolean bool = false;
for (int i=0; i<getRowCount();i++){
if (value.equals(getValueAt(i, col))){
bool=true;
break;
}
}
return bool;
}
public int getColumnIndex(COLUMNS column){
for(int i=0;i<header.length;i++){
if (column.equals(header[i])){
return i;
}
}
return -1;
}
///////////////////////////////////////////////////////
// other methods (from AbstractTableModel) to override:
@Override
public Class<?> getColumnClass(int col) {
Class<?> c;
COLUMNS column = header[col];
if (column.equals(COLUMNS.IMAGE_COLUMN))
c = ImageIcon.class;
else if (column.equals(COLUMNS.STATE_COLUMN))
c = JComboBox.class;
else c = super.getColumnClass(col);
return c;
}
@Override
public String getColumnName(int col) {
COLUMNS column = header[col];
if (column.equals(COLUMNS.IMAGE_COLUMN))
return " ";
else if (column.equals(COLUMNS.TARGA_COLUMN))
return "Targa";
// others... bla bla...
return super.getColumnName(col);
};
@Override
public boolean isCellEditable(int row, int col) {
return true;
}
@Override
public void setValueAt(Object value, int row, int col) {
Vehicle v = vehicles.get(row);
boolean flag = false;
if (v!=null) {
COLUMNS column = header[col];
switch (column) {
case TARGA_COLUMN:
if (!v.getPlate().equals(value)){
if (!controllIfExist(value, col)){ // mhm...
v.setPlate((String) value);
flag = true;
}
}
break;
case MARCA_COLUMN:
if (!v.getMark().equals(value)){
v.setMark((String) value);
flag = true;
}
break;
// others ... bla bla...
}
// update ONLY if necessary:
if (flag) fireTableRowsUpdated(row, row); // is right?
}
}
}
整个事情从TableModel
实现开始,所以让我们看一下:
public class VehicleTableModel extends AbstractTableModel {
private ArrayList<Vehicle> vehicles;
// Most of your code here, didn't examine it closer though
public void addRow(Vehicle vehicle) {
int rowIndex = vehicles.size();
vehicles.add(vehicle);
fireTableRowsInserted(rowIndex, rowIndex); // just notify last row == vehicles.size() == getRowCount()
}
public void removeRow(int row) {
vehicles.remove(row);
fireTableRowsDeleted(row, row); // is right? yes, it looks ok.
}
@Override
public void setValueAt(Object value, int row, int col) {
Vehicle v = vehicles.get(row);
if (v != null) {
COLUMNS column = header[col];
switch (column) {
case TARGA_COLUMN:...; break;
case MARCA_COLUMN:...; break;
// others...
}
fireTableCellUpdated(row, column); // this is the appropriate fire method.
}
}
/**
* Convenience method to notify if a vehicle was updated in
* the outside, not through setValueAt(...).
*/
public void notifyVehicleUpdated(Vehicle vehicle) {
Vehicle[] elements = (Vehicles[])vehicles.toArray();
for (int i = 0; i < elements.length; i++) {
if (elements[i] == vehicle) {
fireTableRowsUpdated(i, i);
}
}
}
}
其他一些提示:
>
切勿使用重绘 ()
或更新 UI()
来刷新表的数据。表模型负责通知视图有关正确事件的信息。
永远不要使用< code > fireTableDataChanged()(正如有人建议的那样),除非整个表模型数据都发生了变化。对于行、列和单元格的更改,有适当的< code>fireXxxx()方法。
据我所知,这两个表共享车辆列表,因此必须保持它们同步。如果是的话,我想知道你为什么需要两种不同的桌子模型?如果唯一的原因是可用/停车状态(互斥),那么您可以在两个表中共享一个表模型,并根据车辆的状态应用不同的过滤器。在状态字段更新时,将通知两个表,并将车辆从一个表转移到另一个表。
不久前,在对这个答案的评论中,向< code>Coordinator抽象类添加一个方法(如< code>notifyRowUpdated())的想法似乎适合于解决两个表之间的同步问题。
但是现在我认为最好的方法是与两个表共享同一个表模型,并根据车辆的状态过滤第二个表:如果可用(DISPONIBILE ),则显示它,如果不可用,则隐藏它。
这样,在行更新和行删除时,两个表都将收到通知,并将采取相应的操作。在单元格更新时,我们可以向模型添加一个TableModelListener,该模型对第二个表应用过滤器,显示可用的车辆并隐藏不可用的车辆。更不用说协调员
抽象类将保持简单并保持其原始目的:在行更新/删除时通知第三方代理。
所以请看看下面的代码示例(抱歉扩展名)。一些注意事项:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.Arrays;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultRowSorter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.SwingUtilities;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableColumnModel;
public class DemoSharedTableModel {
private DataObjectTableModel<Vehicle> model;
private JTable table1, table2;
private Action addAction, removeAction;
private void createAndShowGui() {
String[] columnIdentifiers = new String[] {
"Plates",
"Description",
"Available"
};
model = new DataObjectTableModel<Vehicle>(Arrays.asList(columnIdentifiers)) {
@Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
case 1: return String.class;
case 2: return Boolean.class;
}
return super.getColumnClass(columnIndex);
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 2;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Vehicle vehicle = getDataObject(rowIndex);
switch (columnIndex) {
case 0 : return vehicle.getPlates();
case 1: return vehicle.getDescription();
case 2: return vehicle.isAvailable();
default: throw new ArrayIndexOutOfBoundsException(columnIndex);
}
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (columnIndex == 2) {
Vehicle vehicle = getDataObject(rowIndex);
vehicle.setAvailable((Boolean)aValue);
fireTableCellUpdated(rowIndex, columnIndex);
} else {
throw new UnsupportedOperationException("Unsupported for column " + columnIndex);
}
}
};
model.addRow(new Vehicle("AAA1", "Car - Peugeot", true));
model.addRow(new Vehicle("AAA2", "Truck - Volvo", true));
model.addRow(new Vehicle("AAA3", "Car - Ford", false));
model.addRow(new Vehicle("AAA4", "Car - Mercedes-Benz", false));
model.addRow(new Vehicle("AAA5", "Car - Ferrari", true));
model.addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
if (e.getType() == TableModelEvent.UPDATE) {
DemoSharedTableModel.this.applyFilterOnSecondTable();
}
}
});
table1 = new JTable(model);
table1.setAutoCreateRowSorter(true);
table1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table2 = new JTable(model);
table2.setAutoCreateRowSorter(true);
table2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// Make third column not visible
TableColumnModel columnModel = table2.getColumnModel();
columnModel.removeColumn(columnModel.getColumn(2));
applyFilterOnSecondTable();
addAction = new AbstractAction("+") {
@Override
public void actionPerformed(ActionEvent e) {
model.addRow(new Vehicle("new", "default text", true));
}
};
removeAction = new AbstractAction("-") {
@Override
public void actionPerformed(ActionEvent e) {
int viewIndex = table1.getSelectedRow();
if (viewIndex != -1) {
int modelIndex = table1.convertRowIndexToModel(viewIndex);
model.deleteRow(modelIndex);
}
setEnabled(model.getRowCount() > 0);
}
};
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(new JButton(addAction));
buttonsPanel.add(new JButton(removeAction));
JPanel content = new JPanel(new BorderLayout(8, 8));
content.add(new JScrollPane(table1), BorderLayout.WEST);
content.add(buttonsPanel, BorderLayout.CENTER);
content.add(new JScrollPane(table2), BorderLayout.EAST);
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(content);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void applyFilterOnSecondTable() {
DefaultRowSorter sorter = (DefaultRowSorter)table2.getRowSorter();
sorter.setRowFilter(new RowFilter() {
@Override
public boolean include(RowFilter.Entry entry) {
Vehicle vehicle = model.getDataObject((Integer)entry.getIdentifier());
return vehicle.isAvailable();
}
});
}
class Vehicle {
private String plates, description;
private Boolean available;
public Vehicle(String plates, String description, Boolean available) {
this.plates = plates;
this.description = description;
this.available = available;
}
public String getPlates() {
return plates;
}
public void setPlates(String plates) {
this.plates = plates;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean isAvailable() {
return available;
}
public void setAvailable(Boolean available) {
this.available = available;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new DemoSharedTableModel().createAndShowGui();
}
});
}
}
请注意,在第二个表中仅显示可用车辆。
https://imgs.xnip.cn/cj/n/15/140420d6-52be-42c3-8a4b-6bb04f4c3ca2.jpg" width="100%" height="100%" />
问题内容: 我在管理两个JTable和相关数据时遇到一些问题。 我做了这个GUI: 在此处输入图片说明 我解释一下用法:在第一个jTable中,我列出了车辆(卡车, 汽车……)和相关信息。在第二个jTable中 ,我按下 绿色箭头,列出了我要使其“可用”的车辆(即sw代理启动)。因此,是第一个列表的子列表:在第一个 表中选择的行将在第二个表中复制。 第一个问题:在第一列中,我有 车辆类型的说明图(
招呼: 我认为我没有正确更新我的复杂状态: 如何正确更新此状态?谢谢 https://codesandbox.io/s/intelligent-ellis-qi97k?file=/src/App.js
我有一张非常复杂的表格,是这样的:- 现在,我需要处理一个应该重复一行的查询,其中假设p2、p3或p1、p2甚至仅p2值对于该特定年份或从2009年、2010年或2011年中的任何一年都不可用,并将最后一列的值作为零放入其中。 所以现在我的数据库看起来应该像- 我试着使用临时表 但它不起作用。有谁能帮我。
问题内容: 我在对Postgres数据库使用github.com/bmizerany/pq。我需要选择“ todos”表中的所有行,并为每一行检查条件并相应地更新行。伪代码: UpdateTask()函数将发出一条SQL更新语句来更新该行。 在SELECT查询中发出SQL更新是否会锁定数据库?这是进行这种更新的正确方法吗? 问题答案: 首先, 至少 您应该这样做,以防止其他访问锁定行。您必须在事务
问题内容: 我是redux和es6语法的新手。我使用官方的redux教程和此示例制作了我的应用。 以下是JS代码段。我的观点-在post reducer中定义REQUEST_POST_BODY和RECEIVE_POST_BODY案例。主要困难- 在商店中查找和更新合适的对象。 我尝试使用示例中的代码: 但是它使用了简单的帖子数组。无需按ID查找正确的帖子。 这是我的代码: 问题答案: 如果您想坚持
我正在尝试使用useReducer更新组件的状态。我在useEffect中从mongodb获取了一些信息,在那里我调用了我的useReducer dispatch,以便在组件装载后立即设置我的状态。不幸的是,我的状态没有受到影响,我的UI也没有改变。控制台。useffect语句末尾的log语句显示我的状态仍然具有useReducer调用中设置的初始值。有人能告诉我哪里出了问题吗?另外,我计划稍后在