【问题标题】:Passing data to new GUI将数据传递到新的 GUI
【发布时间】:2016-09-30 03:01:00
【问题描述】:

我有一个JTable,上面有我从 CSV 文件中读取的内容。我正在使用以下方法,当我单击一行时,它将打开一个新的JFrame 并关闭前一个。它将显示诸如 ID、坐标、该表上所写内容的状态等内容,并且可以根据需要对其进行编辑。例如。下表:

|ID  |co-ordinates      | status   | 
| 1  |   (3,21)          |  pending | 
|  2 |  (4,21)           | full     | 
|  3 |  (9, 12)          |  empty   |

如果我单击第 1 行,它将在另一个框架的文本字段中弹出 ID(1)、坐标(3,21) 和状态的框架,并且是可编辑的。我能够执行单击功能,但不确定单击行时如何将该数据带到下一帧。

 //in location class
 table.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                  if (e.getClickCount() == 1) {
                    int row = table.getSelectedRow();
                    AddEdit An = new AddEdit(); //goes to next class 
                    An.setVisible(true);
                    dispose();
                }
             }
          });

单击行时如何将该数据带到下一帧?

【问题讨论】:

  • "..打开一个新的 JFrame 并关闭前一个。" 1) 参见The Use of Multiple JFrames, Good/Bad Practice? 2) 改为使用CardLayout,如this answer 所示.
  • 顺便说一句 - 鉴于这是一个问答网站,我添加了一个实际问题,形式为 “单击该行时如何将该数据带到下一帧?”请不要忘记添加问题。
  • 是的,谢谢您的回复。

标签: swing oop user-interface jframe


【解决方案1】:

不知道你的JTable 有什么类型的内容,我只能提供一个通用的解决方案。

int row = table.getSelectedRow();
int userID = (Integer) table.getValueAt(row, 0);
// is co-ordinates [sic] a String or a Point? 
// You can do the same as for userID and use (row,1) to get the value
String status = (String) table.getValueAt(row, 2)

有了这个,您可以创建一个Object[] 并将其发送给AddEdit 的构造函数,或者在AddEdit 中编写一个方法getJTableObject() 或类似的东西。这取决于您是否可以更改AddEdit

您还应该考虑 Andrews 的建议并使用 cardLayout。有了这个,您可以使用 ObserverPattern 并发送您的对象。


另一种方法是使用JOptionPane

Object[] message = { "Please update the information:", newStatusPanel };
int response = JOptionPane.showConfirmDialog(null, message, "Update information",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);

newStatusPanel 只是一个JPanel,您可以在上面放置,即JTextFields。然后,您通过我之前展示的方法使用 JTable 中的内容填充这些字段,当用户单击确定时,您更新 JTable

// Do something with the result
if (response == JOptionPane.OK_OPTION) {
model.addRow(new Object[] { txtID.getText(), coordinates.getText(), ... });

看起来像这样:

(PS:我稍后会将基于文本的密码更改为基于哈希的密码。请忽略这种公然不安全的密码处理方式)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 2020-01-10
    • 1970-01-01
    相关资源
    最近更新 更多