【问题标题】:Swing dependent components and event systemSwing 依赖组件和事件系统
【发布时间】:2012-08-21 09:33:15
【问题描述】:

我必须用 Swing 在 JAVA 中构建一个复杂的 GUI(目前我有近 80 个类)。 应用程序的图形部分拆分如下:第一个选项卡系列(例如“管理”、“管理”、“配置”),然后是第二个级别(例如,“用户”、“组”、“游戏” )。现在我有两个年级(每个级别的标签一个)。下一个级别是管理业务对象的 JPanel(我的整个 GUI 是围绕我的业务模型构建的),在这个级别有 2 种类型的 JPanel:谁管理简单对象(例如,“用户”、“类别”、“游戏” ”、“关卡”)和管理对象的“复合主键”(例如“User_Game”,它代表所有用户的每个游戏关卡的复式表的形式)。 我的第二级选项卡可以包含多个 JPanel。 当我的 JPanel 管理单个对象时,它由一个 JTable 和两个按钮(添加和删除)组成,我在上面放置事件,如果不是,它就是一个简单的 JTable。当我有外键(例如“用户”的“组”和“游戏”的“类别”或“用户游戏”的“级别”)时,它是一个直接从 JTableModel 获取其信息的 JComboBox。在管理 JTable 对象以“复合主键”时,列和行也直接依赖于模型(例如“Game”和“User”“User_Game”)。 每个都有自己的 JTable 模型来处理持久层(用于信息的 Hibernate)和其他 TableModel。 为了管理更改(例如添加、修改或删除“用户”),我使用以下代码:

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

/*
 *  This class listens for changes made to the data in the table via the
 *  TableCellEditor. When editing is started, the value of the cell is saved
 *  When editing is stopped the new value is saved. When the oold and new
 *  values are different, then the provided Action is invoked.
 *
 *  The source of the Action is a TableCellListener instance.
 */
public class TabCellListener implements PropertyChangeListener, Runnable
{
    private JTable table;
    private Action action;

    private int row;
    private int column;
    private Object oldValue;
    private Object newValue;

    /**
     *  Create a TableCellListener.
     *
     *  @param table   the table to be monitored for data changes
     *  @param action  the Action to invoke when cell data is changed
     */
    public TabCellListener(JTable table, Action action)
    {
        this.table = table;
        this.action = action;
        this.table.addPropertyChangeListener( this );
        this.table.getModel().addTableModelListener(new ModelListenerTableGui(this.table, this.action));
    }

    /**
     *  Create a TableCellListener with a copy of all the data relevant to
     *  the change of data for a given cell.
     *
     *  @param row  the row of the changed cell
     *  @param column  the column of the changed cell
     *  @param oldValue  the old data of the changed cell
     *  @param newValue  the new data of the changed cell
     */
    private CellListenerTableGui(JTable table, int row, int column, Object oldValue, Object newValue)
    {
        this.table = table;
        this.row = row;
        this.column = column;
        this.oldValue = oldValue;
        this.newValue = newValue;
    }

    /**
     *  Get the column that was last edited
     *
     *  @return the column that was edited
     */
    public int getColumn()
    {
        return column;
    }

    /**
     *  Get the new value in the cell
     *
     *  @return the new value in the cell
     */
    public Object getNewValue()
    {
        return newValue;
    }

    /**
     *  Get the old value of the cell
     *
     *  @return the old value of the cell
     */
    public Object getOldValue()
    {
        return oldValue;
    }

    /**
     *  Get the row that was last edited
     *
     *  @return the row that was edited
     */
    public int getRow()
    {
        return row;
    }

    /**
     *  Get the table of the cell that was changed
     *
     *  @return the table of the cell that was changed
     */
    public JTable getTable()
    {
        return table;
    }
//
//  Implement the PropertyChangeListener interface
//
    @Override
    public void propertyChange(PropertyChangeEvent e)
    {
        //  A cell has started/stopped editing

        if ("tableCellEditor".equals(e.getPropertyName()))
        {
            if (table.isEditing())
                processEditingStarted();
            else
                processEditingStopped();
        }
    }

    /*
     *  Save information of the cell about to be edited
     */
    private void processEditingStarted()
    {
        //  The invokeLater is necessary because the editing row and editing
        //  column of the table have not been set when the "tableCellEditor"
        //  PropertyChangeEvent is fired.
        //  This results in the "run" method being invoked

        SwingUtilities.invokeLater( this );
    }
    /*
     *  See above.
     */
    @Override
    public void run()
    {
        row = table.convertRowIndexToModel( table.getEditingRow() );
        column = table.convertColumnIndexToModel( table.getEditingColumn() );
        oldValue = table.getModel().getValueAt(row, column);
        newValue = null;
    }

    /*
     *  Update the Cell history when necessary
     */
    private void processEditingStopped()
    {
        newValue = table.getModel().getValueAt(row, column);

        //  The data has changed, invoke the supplied Action

        if ((newValue == null && oldValue != null) || (newValue != null && !newValue.equals(oldValue)))
        {
            //  Make a copy of the data in case another cell starts editing
            //  while processing this change

            CellListenerTableGui tcl = new CellListenerTableGui(
                getTable(), getRow(), getColumn(), getOldValue(), getNewValue());

            ActionEvent event = new ActionEvent(
                tcl,
                ActionEvent.ACTION_PERFORMED,
                "");
            action.actionPerformed(event);
        }
    }
}

还有以下动作:

import java.awt.event.ActionEvent;
import java.beans.PropertyChangeListener;

import javax.swing.Action;

public class UpdateTableListener<N> extends AbstractTableListener implements Action
{
    protected boolean enabled;
    public UpdateTableListener(AbstractTableGui<N> obs)
    {
        super(obs);
        this.enabled = true;
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        if (null != e && e.getSource() instanceof CellListenerTableGui)
        {
            TabCellListener tcl = (TabCellListener)e.getSource();

            this.obs.getModel().setValueAt(tcl.getNewValue(), tcl.getRow(), tcl.getColumn());
            int sel = this.obs.getModel().getNextRequiredColumn(tcl.getRow());

            if (sel == -1)
                this.obs.getModel().save(tcl.getRow());
        }
    }

    @Override
    public void addPropertyChangeListener(PropertyChangeListener arg0)
    {
    }

    @Override
    public Object getValue(String arg0)
    {
        return null;
    }

    @Override
    public boolean isEnabled()
    {
        return this.enabled;
    }

    @Override
    public void putValue(String arg0, Object arg1)
    {

    }

    @Override
    public void removePropertyChangeListener(PropertyChangeListener arg0)
    {

    }

    @Override
    public void setEnabled(boolean arg0)
    {
        this.enabled = arg0;

    }

}

这段代码运行良好,数据保存良好。 然后我添加这段代码来刷新依赖组件:

import java.awt.event.ActionEvent;
import java.beans.PropertyChangeListener;

import javax.swing.Action;

public class ChangeTableListener implements Action
{

    protected AbstractTableGui table;

    public ChangeTableListener(AbstractTableGui table)
    {
        this.table = table;
    }

    @Override
    public void actionPerformed(ActionEvent arg0)
    {
        this.table.getModel().fireTableDataChanged();
        this.table.repaint();
    }

    @Override
    public void addPropertyChangeListener(PropertyChangeListener arg0)
    {
    }

    @Override
    public Object getValue(String arg0)
    {
        return null;
    }

    @Override
    public boolean isEnabled()
    {
        return false;
    }

    @Override
    public void putValue(String arg0, Object arg1)
    {
    }

    @Override
    public void removePropertyChangeListener(PropertyChangeListener arg0)
    {
    }

    @Override
    public void setEnabled(boolean arg0)
    {
    }
}

我的 TableModel.fireTableDataChanged 重建 JTable 内容(调用 super.fireTableDataChanged 和 fireTableStructureChanged),JTable.repaint 重置渲染器,它适用于 Combobox(外键),它可以更新复式表上的标题,但它可以' t 在复式表中添加或删除列或行。 此外,如果有最轻微的变化,我会看到更高的延迟。

我的问题很简单:如何管理相互依赖的组件?

为了您的帮助, 提前, 谢谢。

编辑: 这里是 TableCellEditor 的一个例子。

import javax.swing.DefaultCellEditor;
import javax.swing.JTextField;

public class TextColumnEditor extends DefaultCellEditor
{

    public TextColumnEditor()
    {
        super(new JTextField());
    }

    public boolean stopCellEditing()
    {
        Object v = this.getCellEditorValue();
        if(v == null || v.toString().length() == 0)
        {
            this.fireEditingCanceled();
            return false;
        }
        return super.stopCellEditing();
    }
}

TableModel 的一个例子:

import java.util.ArrayList;

public class GroupModelTable extends AbstractModelTable<Groups>
{
    protected GroupsService service;

    public GroupModelTable(AbstractTableGui<Groups> content)
    {
        super(content, new ArrayList<String>(), new ArrayList<Groups>());
        this.headers.add("Group");
        this.content.setModel(this);
        this.service = new GroupsService();
        this.setLines(this.service.search(new Groups()));
    }

    public Object getValueAt(int rowIndex, int columnIndex)
    {
        switch (columnIndex)
        {
            case 0:
                return this.lines.get(rowIndex).getTitle();
            default:
                return "";
        }
    }

    public void setValueAt(Object aVal, int rowIndex, int columnIndex)
    {
        switch (columnIndex)
        {
            case 0:
                this.lines.get(rowIndex).setTitle(aVal.toString());
                break;
            default:
                break;
        }
    }

     @Override
     public Groups getModel(int line, int column)
     {
         return null;
     }

     @Override
     public Groups getModel(int line)
     {
         return this.lines.get(line);
     }

     public boolean isCellEditable(int row, int column)
     {
        return true;
     }

    @Override
    public GroupModelTableGui newLine()
    {
        this.lines.add(new Groups());
        return this;
    }

    @Override
    public int getNextRequiredColumn(int row)
    {
        Groups g = this.getModel(row);
        if (g != null && g.getTitle() != null && g.getTitle().length() > 0)
            return -1;

        return 0;
    }

    @Override
    public void save(int row)
    {
        Groups g = this.getModel(row);
        if (g != null)
        {
            try
            {
                if (g.getId() == null)
                    this.service.create(g);
                else
                    this.service.update(g);
            }
            catch (Exception e)
            {

            }
        }
    }

    @Override
    public void removeRow(int row)
    {
        Groups g = this.getModel(row);
        if (g != null)
        {
            try
            {
                if (g.getId() != null)
                    this.service.delete(g);

                super.removeRow(row);
            }
            catch (Exception e)
            {

            }
        }
    }
}

表格示例:

public class GroupTable extends AbstractTable<Groups>
{
    public GroupTable()
    {
        new GroupModelTableGui(this);
        new CellListenerTableGui(this.getContent(), new UpdateTableListenerGui<Groups>(this));
        this.getContent().getColumnModel().getColumn(0).setCellEditor(new TextColumnEditorGui());
    }

}

希望能帮助你理解:/

【问题讨论】:

  • 懒得给它比粗略的外观更多,所以只是几个 cmets:a) never-ever(如 reeeally never)代表一个模型,这是它自己的核心责任。 b)从来没有(与上面相同的程度:)有必要在模型的视图上调用 repaint - 如果这似乎修复了某些问题,则模型不会正确通知其侦听器 c)在编辑器实现中,不要第二猜测客户的意图 - 如果编辑的值无效,则返回 false 而不是更多 d) 实施不可更改的操作是无用的 - 表现良好的客户不得执行它

标签: java swing jtable tablemodel tablecelleditor


【解决方案1】:

你的TabCellListener 我不熟悉。您的TableCellEditor 不应该直接与TableModel 交互。它应该实现getTableCellEditorComponent()getCellEditorValue(),如example 所示。当编辑器结束时,模型将具有新值。您的 TableModel 应该处理持久性。多个视图可以通过TableModelListener 收听单个TableModel

附录:您的CellEditorTextColumnEditor 可能不应该调用fireEditingCanceled()。按 Escape 应该足以恢复编辑,如example 所示。您还可以查看相关的tutorial sectionexample

【讨论】:

  • 您好,感谢您的回答,我添加了一些代码,希望这能让您更好地了解问题。你有没有看到,我的 TableCellEditor 不直接与我的 TableModel 交互,所以我在这方面做得很好。我将尝试用 TableModelListener 替换我的 TabCellListener。
  • 我上面已经详细阐述了,但是我还是不明白问题所在;来自您的sscce 可能会有所帮助。断章取义,我不明白你的其他推导。
  • 我很努力,自从我第一次发帖以来,我重建了所有的事件系统,但这不是一件容易的事,生成的事件数除以 100,所以我的应用程序明显更快。感谢那。我的最后一个问题是当我尝试添加、删除或重命名列时,没有出现修改。
猜你喜欢
  • 2014-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-02
  • 2018-06-24
  • 2017-06-25
  • 2019-10-18
相关资源
最近更新 更多