【发布时间】:2016-05-13 20:49:26
【问题描述】:
我通常用 C# 编写代码,我什至用 C# 完成了应用程序,但我需要将它移植到 Java。
今天刚开始,之前没真正用过Java。
这个问题很奇怪,因为我没有收到任何错误,它只是没有更新,这里是代码:
public void setInfoStrip(String infoStrip) {
InfoStrip.setText(infoStrip);
}
上面是一个应该更新 JTextField 的 Setter(如果我使用按钮的 ActionListener 更新它,它会更新它),但是当我在类中甚至在 main(String [] args) 使用此代码的应用程序入口点:
mainGUI GUI = new mainGUI();
GUI.setInfoStrip("test");
或此代码:
new mainGUI().setInfoStrip("test");
我的猜测是它什么都不做,因为我从静态类调用它
public static void main(String[] args)
但是,即使我创建了一个非静态的新类并从公共 staitc void main(String[] args) 引用它,然后放任一
mainGUI GUI = new mainGUI();
GUI.setInfoStrip("test");
或
new mainGUI().setInfoStrip("test");
它是新创建的类,我称之为
new ImGoingToCry().Alot();
它仍然什么都不做。
我很困惑,我什至在谷歌上阅读了一些与此相关的问题,但它们都被这个解决了:
mainGUI GUI = new mainGUI();
GUI.setInfoStrip("test");
这是你们中的一些人要求的 MVCE:
public class mainGUI {
// GUI Elements
private JPanel WorkSpace;
private JTabbedPane tabbedPane1;
private JList DetectedProfiles;
private JButton StartGame;
private JTextField CurProf;
private JButton BackupProfiles;
private JButton SearchSaves;
private JButton RetrieveProfiles;
private JTextField InfoStrip;
private JLabel ProfileSize;
/**
* Getter and Setter functions
*/
public void setInfoStrip(String infoStrip) {
InfoStrip.setText(infoStrip);
}
// Initialize the main application GUI and set it's properties
public static void main(String[] args) {
JFrame mainGUIFrame = new JFrame("The Witcher 3 Save Manager | " + " ver. " + GlobalVariables.appversion);
mainGUIFrame.setContentPane(new mainGUI().WorkSpace);
mainGUIFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainGUIFrame.setLocationRelativeTo(null);
mainGUIFrame.setPreferredSize(new Dimension(420, 370));
mainGUIFrame.setResizable(false);
mainGUIFrame.pack();
mainGUIFrame.setVisible(true);
new mainGUI().run();
}
public void run() {
/**
* Initialize the core application functions
*/
// Load the application settings
GlobalVariables.Settings();
// Initialize the app components
GlobalVariables.Initialize();
// Pass the value to setter
new mainGUI().setInfoStrip("test"); // This should change the text but it does nothing there's not even an error
}
}
【问题讨论】:
-
请发布MVCE(最小、完整且可验证的示例)。不是所有的小sn-ps代码。您可以点击问题下方的
edit链接来编辑您的帖子。 -
什么是
InfoStrip?这是您要设置文本的JTextField变量的名称,还是您创建的一个类(可能有一个名为setText()的静态方法)?只是要清楚。顺便说一句,如前所述,请minimal reproducible example。 -
刚刚发布了 MVCE,抱歉没有早点发布。我确信解决方案非常简单,但我要么太盲目,要么太笨,无法弄清楚。
-
@Marcin 你的 MCVE 甚至没有运行。
GlobalVariables是什么?你能给你整个代码的链接吗?我认为这也可以在不使用文档侦听器的情况下解决。顺便说一句,您可能需要遵循 java 类/变量命名约定。你的看起来更像 C# ;-) -
GlobalVariables是我自己的类,它工作得很好,你甚至可以跳过它与 JTextField 无关。 DocumentListener 工作正常,但似乎只是在一个简单的文本字段中更新文本需要相当多的努力。如果您对如何在不使用 DocumentListener 的情况下解决它有任何建议,请告诉我。它看起来也像 C#,因为这是我第一次用 Java 编写任何东西。
标签: java jtextfield