【问题标题】:Java Swing Components not working in public void main(String[]args) [closed]Java Swing 组件在公共 void main(String[]args) 中不起作用 [关闭]
【发布时间】:2014-01-02 04:00:16
【问题描述】:

我通过单击此类中的 jButton 来运行 main 方法。首先尝试使用

public static void main(String[]args)

所有java swing组件开始显示non static variable cannot be referenced from static content错误。所以我改变了

public static void main(String[]args) 

public void main(String[]args)

swing 组件未显示错误,但 jTextArea 中未显示预期结果。如果我在 System.out.println 中打印预期的输出,它会正确显示。我在这里做错了什么?这就是我通过单击 jButton 触发 main() 运行的方式

jButton4.setText("Analyze");
   jButton4.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
         try{
            TestTextRazor test = new TestTextRazor();
            test.main(new String[0]);
            } 
         catch (Exception e) {
            e.printStackTrace();
          }
      }
});

这是我的 main()

public void main(String[] args) throws NetworkException, AnalysisException {

    File textSRC = new File("MyText.txt");
    String myTextCount = null;
    BufferedReader myTextBr = null;
    String check = "";
    try {
        String myTextCurrentLine;
        myTextBr = new BufferedReader(new FileReader(textSRC));
        while ((myTextCurrentLine = myTextBr.readLine()) != null) {
            myTextCount = myTextCount + " " + myTextCurrentLine;
        }

        // Sample request, showcasing a couple of TextRazor features
        String API_KEY = "7d5066bec76cb47f4eb4e557c60e9b979f9a748aacbdc5a44ef9375a";

        TextRazor client = new TextRazor(API_KEY);

        client.addExtractor("words");
        client.addExtractor("entities");
        client.addExtractor("entailments");
        client.addExtractor("senses");
        client.addExtractor("entity_companies");

        String rules = "entity_companies(CompanyEntity) :- entity_type(CompanyEntity, 'Company').";

        client.setRules(rules);

        AnalyzedText response = client.analyze(myTextCount);

        File file = new File("Hello1.txt");
        // creates the file
        file.createNewFile();
        // creates a FileWriter Object
        FileWriter writer = new FileWriter(file); 
        // Writes the content to the file


        for (Sentence sentence : response.getResponse().getSentences()) {
            for (Word word : sentence.getWords()) {
                System.out.println("----------------");
                System.out.println("Word: " + word.getLemma());

                for (Entity entity : word.getEntities()) {
                ///System.out.println("Matched Entity: " + entity.getEntityId());
                }
                for (Sense sense: word.getSenses()) {
                //System.out.println("Word sense: " + sense.getSynset() + " has score: " + sense.getScore());
                }                
            }
         }

            // Use a custom rule to match 'Company' type entities

         for (Custom custom : response.getResponse().getCustomAnnotations()) {
            for (Custom.BoundVariable variable : custom.getContents()) {
                if (null != variable.getEntityValue()) {
                    for (Entity entity : variable.getEntityValue()) {
                        String CompanyFound = ("Variable: " + variable.getKey() +"\n"+ "Value:" + entity.getEntityId());
                        System.out.println(CompanyFound);
                        jTextArea3.append(CompanyFound);

                        writer.write(CompanyFound); 
                        writer.flush();
                        writer.close();
                    }
                }
            }
         }
         String ObjButtons[] = {"Yes","No"};
         int PromptResult;
         PromptResult = JOptionPane.showOptionDialog(null,"Completed Analysis!\nIs there any error in the Analysis?","Homonym Entity Extraction Application",JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE,null,ObjButtons,ObjButtons[1]);

         //JOptionPane.getAlignmentX(Component.BOTTOM_ALIGNMENT);
         if(PromptResult==JOptionPane.YES_OPTION)
         {
             System.out.println("YEs!!!!!");
            jTextArea2.setEditable(true);
            jTextArea3.setEditable(true);
            jButton4.setEnabled(false);
            jButton5.setEnabled(true);
         } 
         else{
            JOptionPane.showMessageDialog(null, "Completed Analysis!","Alert", 1);
            System.out.println("No!!!!!!!!!!");
            jTextArea2.setEditable(false);
            jTextArea3.setEditable(false);
            jButton4.setEnabled(false);
         }


    }catch (IOException ex) {
    }

}

请指导我。

【问题讨论】:

  • 拜托,请拿一本书读一读。了解“静态”的含义。
  • 修复你的第一个错误(来自静态上下文的非静态)
  • 对于Swing 程序,我不会在main 方法中投入太多,看看Swing tutorials 中的一些,您可能会从中学到一些更好的做法。将来也可以帮助您避免这个static 问题。

标签: java swing netbeans


【解决方案1】:

基本上,错误是说,您正试图从静态上下文中引用非静态变量。

非静态变量(通常称为实例变量或字段)需要其父类的实例才能具有某种引用上下文。

查看Understanding Instance and Class Members了解更多详情。

如果没有更多示例,我将创建一个类构造函数并将main 方法的内容移动到它。

然后我会将main 方法修复为static 并从main 方法创建该类的新实例...

我不会制作 Swing 组件static 的原因是它很容易混淆您的引用并最终引用实际未显示在屏幕上的内容...

更新

两件事。

  1. 确保您的 main 方法的上下文正确,您创建的 UI 组件不是 static 并且您正确引用它们。
  2. 不要直接调用TestTextRazor 类。这只是 API 工作原理的一个示例。花时间去理解它,并根据需要融入你自己的课程中

【讨论】:

  • main 中的代码没有在 main() 之外运行。我从 gitHub 获得的 TextRazor API 包。
  • 你在main方法里写的代码吗?如果没有,那么您需要回到做过的人那里并让他们修复它......
  • 好的@MadProgrammer,如果对TextRazor 参考有任何建议,请在此处发布?我需要在 java 中集成 TextRazor API 的指南。
  • main方法是你写的吗?
  • 就个人而言,我可能不会在那里运行“测试”类...
【解决方案2】:

首先,您需要了解的是static 方法无法 访问类字段non-static 的其他方法。所以看看你的代码。 main 必须static,因为这是它的自然签名,必须保持原样。因此,您尝试在main 方法中访问的所有类字段需要static。这是好习惯吗?绝对不。您可以浏览Swing tutorial 以了解良好做法。我敢肯定,如果您浏览了 20 个示例,您会学到很多关于 Swing 的良好编码实践。祝你好运!


我正在通过单击此类中的一个 jButton 来运行 main 方法”

  • 我注意到你做错了完成的一件事是试图从你的actionPerformed 内部调用main 方法。永远不应调用 main 方法。 JVM 使用该方法作为程序的入口点。

  • 您必须了解的另一件事是 Swing 程序是事件驱动的。一个按钮,不应该运行一个完整的程序,除非它是一个非常小的程序。

  • 我会考虑为不同的任务创建方法,例如

    public String getSomethingFromFile(String filename) throws IOExceptions {
    
    }
    

    您可以从actionPerformed 或其他地方调用该方法以将数据附加到文本区域。

  • 学习使用类成员并在构造函数或某些初始化方法中对其进行初始化。

  • 如果您希望在单击按钮时执行 main 方法中的所有操作,请将所有代码放在 actionPerformed 中,而不是 main 中。 main 内部的一个典型形式就是这样,你只需要初始化你的类来让程序运行

    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                JFrame frame = new JFrame();
                frame.add(new MyGUIPanel());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
    

    new MyGUIPanel() 是 Main 类的一个实例

  • 另一种选择是创建一个方法来执行 main 中的所有任务

    public void performTextRazorTask() throws NetworkException, AnalysisException {
        ...
    }
    

    只需从 actionPerformed 调用该方法


再次强调,您可以查看我链接的教程以获得更好的实践,因为该站点不是真正的教程站点,我不想进入教程类型的答案。

【讨论】:

    【解决方案3】:

    首先你不能将 main 方法设为非静态的。

    根据这一行无法从静态内容错误中引用非静态变量。将这些变量设为static

    【讨论】:

    • 我怎样才能将摇摆组件设为静态?
    • @user3003233 Thogh 我没有摇摆经验,但我会尽力帮助你。你能发布完整的代码,以便我在我的系统中运行并告诉你在哪里进行更改
    • @user3003233 是的,你可以,不,你不应该
    • @MadProgrammer 我在想你为什么到现在你还没有发布答案。
    • 很难解释是用户不理解static的概念
    猜你喜欢
    • 2013-06-03
    • 2016-02-23
    • 2012-11-06
    • 2013-11-12
    • 2016-05-22
    • 2016-07-14
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多