我有 14 个 JFrame
类和一个 JFrame
类,其中包含一个充当日历的 JTable
。我希望当用户从 JTable
日历中选择日期时,更改 14 个 JFrame
类中任何一个文本字段或任何其他组件的日期。现在,这些框架一次出现一个,并且 jtable 是从 14 个 JFrame 类中任意一个上的 JButton
实例化的。
我的困境是如何识别已实例化包含 JTable
的 JFrame
的 JFrame
类,以便它的文本字段值可以是改变了。
实例化包含表的 JFrame 的代码:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFrame frmMain = new Calender();
frmMain.setVisible(true);
frmMain.setSize(367, 342);
}
更改 14 个 JFrame
类之一的文本字段值的代码:
@Override
public void mouseClicked(MouseEvent me) {
if (me.getClickCount()==2){
int selected1 = jTable1.getSelectionModel().getLeadSelectionIndex();
int selected2 =jTable1.getColumnModel().getSelectionModel().getLeadSelectionIndex();
Object c = jTable1.getModel().getValueAt(selected1, selected2);
SowInformation.jTextField4.setText(c.toString());
this.setVisible(false);
}
}
其中 SowInformation
是 14 个 JFrame
类之一。
最佳答案
正如@AndrewThompson 明智地提到的,the use of multiple JFrame是一种不好的做法。在这种情况下,(非)模态对话框将是更好的选择。
现在假设您选择非模式对话框,那么您仍然遇到同样的问题。有多种方法可以解决此问题,但本质上您需要保留对打开日历框架的框架/对话框的引用。更好的是,您可以使用接口(interface)来定义契约来更新文本字段,从而将所需的行为与实际实现隔离开来。例如:
public interface IUpdateText {
public void updateText(String text);
}
现在您的日历框架需要保留对 IUpdateText
兼容对象的引用:
class Calender extends JFrame {
...
private IUpdateText updateText;
...
public void setIUpdateText(IUpdateText ut) {
this.updateText = ut;
}
...
}
然后在您的鼠标监听器实现中只需调用 updateText()
方法:
@Override
public void mouseClicked(MouseEvent me) {
if (me.getClickCount()==2){
int selectedRow = jTable1.getSelectedRow();
int selectedColumn = jTable1.getSelectedColumn();
if (selectedRow > -1 && selectedColumn > -1) {
Object value = jTable1.getValueAt(selectedRow, selectedColumn); // ask the value to the view, not the model. Otherwise you need to convert both row and column indexes
this.updateText.updateText(value.toString());
this.setVisible(false); // maybe this.dispose() instead ?
}
}
}
当然,可以打开此日历框架的所有其他框架/对话框都必须实现 IUpdateText
接口(interface)。例如SowInformation
框架:
class SowInformation extends JFrame implements IUpdateText {
...
private JTextField jTextField4;
...
@Override
public void updateText(String text) {
this.jTextfield4.setText(text);
}
...
}
最后,在实例化它时,将符合 IUpdateText
的对象设置为日历框架:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Calender frmMain = new Calender();
calender.setIUpdateText(this); // assuming 'this' is an IUpdateText interface compliant
frmMain.pack();
frmMain.setVisible(true);
}
<小时/>
其他评论
从架构的角度来看,这个问题可以通过 MVC 模式得到更好的解决,让 Controller 充当框架/对话框的中介。有多个问题about MVC pattern and Swing在这里,但我真的很喜欢 this answer 中显示的示例/解释作者:@MadProgrammer(一位真正的 Swing 大师)。
关于java - 通过从 Jframe 类 3 中的 jtable 中选择项目来更改 JFrame class1、JFrame class2...中的文本字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27014743/