【问题标题】:Ability to access a Text Area from a different class能够从不同的类访问文本区域
【发布时间】:2013-03-25 20:23:05
【问题描述】:

我如何能够从我的 main() 运行这个函数来构建 gui,然后使用其他地方的代码来处理按钮单击并从文本字段中检索输入?

package main;

import javax.swing.*;
import java.awt.*;

public class Gui {

public static void mainGUI() {
    UIManager.put("swing.boldMetal", Boolean.FALSE);
    java.net.URL imgApp = ClassLoader.getSystemResource("res/app.png");
    JFrame mainWin = new JFrame("jIRC");
    mainWin.setSize(1024, 720);
    mainWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainWin.setIconImage(new ImageIcon(imgApp).getImage());

    Container panel = mainWin.getContentPane();
    panel.setLayout(null);

    JTextArea inputBox = new JTextArea();
    inputBox.setSize(300, 100);
    inputBox.setLocation(500, 250);

    JButton sendButton = new JButton();
    sendButton.setText("Send");
    sendButton.setFont(new Font("Helvetica", Font.ITALIC, 16));
    sendButton.setSize(72, 32);
    sendButton.setLocation(500, 500);

    panel.add(inputBox);
    panel.add(sendButton);
    mainWin.setVisible(true);
}
}

这是我的主要功能类:

public class Run{

public static void main(String[] args) {

    main.Debug.startupDebug();
    main.Gui.mainGUI();
}
}

如何将我的一些代码放在非静态字段中?

【问题讨论】:

    标签: java swing class function


    【解决方案1】:

    您已将所有内容都放在一个静态方法中,这将不允许您使用任何面向对象编程的强大功能。考虑创建符合 OOP 的类非静态字段和方法以及公共 getter 和 setter 方法,这样其他类可以影响此类的行为。

    编辑
    您发布了:

    public class Run{ 
      public static void main(String[] args) { 
        main.Debug.startupDebug(); 
        main.Gui.mainGUI(); 
      } 
    }
    

    但你需要做的是:

    public class Run{ 
      public static void main(String[] args) { 
        GUI gui = new GUI();
        Debug debug = new Debug();
    
         debug.setGui(gui);
         gui.setDebug(debug);
    
         gui.startGui();
      } 
    }
    

    或类似的东西。再次避免使用静态的任何东西。

    【讨论】:

    • @DrZarreh:请将此代码发布为对您问题的编辑,因为代码在 cmets 中的格式不正确。
    • @DrZarreh:如果你想充分利用 Java,是的,你不会后悔的。
    • @DrZarreh:如果你想看到一个更大的例子,让单独的类处理 GUI 或视图部分与侦听器或控制部分,请查看我在 this question 中的回答。跨度>
    • 我现在正在看,我正在清理我的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 2010-12-03
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    相关资源
    最近更新 更多