对于 Java 编程,我是个新手。希望您能为我提供一个可以轻松实现的答案。我正在编写一个代码来跟踪两个人一起花了多少钱。
我使用文本文件作为数据库,并且我已经成功地正确读取了该文件。
我有一个主 JFrame,其中添加了一个包含两个 JPanel 的 JTabbedPane。 JPanel 是使用我在两个单独的类中编写的两个独立的方法创建的。一个面板有两个 JTextFiled,人们可以在其中写入购买后花费的金额。另一个 JPanel 正在显示历史记录,并有一个重置按钮,可删除文本文件中的所有数据。
我已向 JTextFields 添加了一个 KeyListener,向 JButton 添加了一个 ActionListener。每个监听器都是在单独的类中编写的。
除了主框架的重新绘制之外,一切正常。现在,我需要重新打开程序才能看到更改。我希望能够在监听器中重新绘制主 JFrame,但我无法使其工作。
这是主框架:
public class Frame extends JFrame {
static JTabbedPane tabs = new JTabbedPane();
static JFrame frame = new JFrame("Reimbursment Control");
public Frame() throws FileNotFoundException {
JPanel c = ControlTab.getControlTab();
JPanel h = HistoryTab.getHistoryTab();
JTabbedPane tabs = new JTabbedPane();
tabs.addTab("Overview", c);
tabs.addTab("History", h);
frame.getContentPane().add(tabs);
//...
这是我将监听器添加到 JTextFields 和 JButton 的方法:
ButtonClicked.addActionListener(button);
KeyPressed.addKeyListener(textfield);
这些是包含上面调用的 Listener 方法的类:
public class ButtonClicked {
public static void addActionListener(JButton button) {
button.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent click) {
//Here's code that deletes all the data in the file
//and it should be displayed right away but I don't
//know how to update the main JFrame from here?
}
}
);
}
...
public class KeyPressed {
public static void addKeyListener(final JTextField textfield) {
textfield.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent key) {
//When pressing enter the value written
//in one of the JTextFields will be entered in
//the file which works but how can the repainting
//of the main JFrame be implemented here?
}
}
);
}
最佳答案
基本上,您需要某种模型,两个面板都可以与之交互。
“控制”面板将使用新信息更新模型,“历史记录”面板将监听模型的更改并相应地更新其 View 。
这是一个基本的 Producer/Consumer和 Observer pattern问题。
考虑您当前的示例。您将监听器附加到组件并收到更改通知。这是观察者模式的示例。
关于java - 无法从其他类中的键/操作监听器更新我的主 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21562794/