【问题标题】:Accessing JFrame stuff from the outside从外部访问 JFrame 内容
【发布时间】:2014-02-04 10:09:14
【问题描述】:

这里真的,真的很愚蠢的问题。我是 Java(和 OOP)的新手,来自 Javascript(实际上是扩展脚本)背景。我这里有一个 JFrame:

package info.chrismcgee.sky.production;

import java.awt.EventQueue;
import java.awt.Font;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;

import net.miginfocom.swing.MigLayout;

import org.jdesktop.swingx.JXTreeTable;

import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;

public class ProductionWindow extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = -1899673458785493250L;
    private JPanel contentPane;
    private JTextField textField;
    private JLabel lblTodaysDate;
    private JXTreeTable treeTable;

    /**
     * Create the frame.
     */
    public ProductionWindow() {
        setMinimumSize(new Dimension(450, 300));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new MigLayout("", "[][grow,center][]", "[][grow][]"));

        JButton btnPrev = new JButton("<- PREV");
        contentPane.add(btnPrev, "cell 0 0,alignx left");

        lblTodaysDate = new JLabel("Today's Date");
        lblTodaysDate.setHorizontalAlignment(SwingConstants.CENTER);
        lblTodaysDate.setFont(new Font("Lucida Grande", Font.PLAIN, 20));
        contentPane.add(lblTodaysDate, "cell 1 0,growx");

        JButton btnNext = new JButton("NEXT ->");
        contentPane.add(btnNext, "cell 2 0,alignx right");

        treeTable = new JXTreeTable();
        treeTable.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
        contentPane.add(treeTable, "cell 0 1 3 1,grow");

        JLabel lblTotal = new JLabel("Total:");
        lblTotal.setFont(new Font("Lucida Grande", Font.PLAIN, 24));
        contentPane.add(lblTotal, "cell 0 2");

        textField = new JTextField();
        textField.setEditable(false);
        textField.setHorizontalAlignment(SwingConstants.RIGHT);
        textField.setFont(new Font("Lucida Grande", Font.PLAIN, 24));
        textField.setText("1,000");
        contentPane.add(textField, "cell 1 2 2 1,growx");
        textField.setColumns(10);
    }

    public JPanel getContentPane() {
        return contentPane;
    }

    public void setContentPane(JPanel contentPane) {
        this.contentPane = contentPane;
    }

    public JTextField getTextField() {
        return textField;
    }

    public void setTextField(JTextField textField) {
        this.textField = textField;
    }

    public JLabel getLblTodaysDate() {
        return lblTodaysDate;
    }

    public void setLblTodaysDate(String today) {
        this.lblTodaysDate.setText(today);
    }

    public JXTreeTable getTreeTable() {
        return treeTable;
    }
}

然后我从 Main 类中调用此代码:

package info.chrismcgee.sky.production;

import info.chrismcgee.sky.production.tables.JobManager;
import info.chrismcgee.sky.production.tables.ShowJobs;
import info.chrismcgee.util.InputHelper;

import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.apache.commons.io.FileUtils;
import org.joda.time.LocalDate;

public class Main {

    // This enum will call a stored procedure which returns all of a certain day's jobs.
    public static final String SQL_JOBS_BY_DATE = "{CALL GetJobsWithCountByDate(?, ?)}";

    private static Connection conn = ConnectionManager.getInstance().getConnection();

    public static void main(String[] args) throws Exception {

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ProductionWindow frame = new ProductionWindow();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        ConnectionManager.getInstance().setDBType(DBType.MYSQL);

        JobManager.displayAllRows();

        LocalDate searchDate = new LocalDate(2014, 01, 02);
        Date sqlDate = Date.valueOf(searchDate.toString());

        ResultSet rs = null;
        try (
                // Create a statement object. (Defines how the result set is handled.)
                CallableStatement stmt = conn.prepareCall(
                        SQL_JOBS_BY_DATE,
                        ResultSet.TYPE_FORWARD_ONLY,
                        ResultSet.CONCUR_READ_ONLY);
                ) {
            // Create the result set for today.
            stmt.setDate(1, sqlDate);
            stmt.registerOutParameter("total", Types.INTEGER);
            rs = stmt.executeQuery();

            int nRows = stmt.getInt("total");

            ShowJobs.displayData(rs, nRows);

            ShowJobs.getTodaysJobs(rs, nRows, ProductionWindow, textField);

        } catch (SQLException e) {
            // In case there is some error with the database.
            ConnectionManager.processException(e);
        } finally {
            rs.close();
        }

        ConnectionManager.getInstance().close();

    }

}

这仍在开发中;甚至还没有测试过。我的问题是从 Main 类访问 ProductionWindow 的方法。当我在 Main 末尾附近的 ShowJobs.getTodaysJobs 行中键入 ProductionWindow. 后按 [CTRL]-[SPACE] 时,Eclipse 不允许我选择 getTreeTable() 方法。

我知道对此有一个明显的答案、一个很好的理由等,以及使它在 Java 中更“正确”工作的解决方案。我只是不知道这些,因为我还是 Java 和 OOP 的新手。

【问题讨论】:

    标签: java eclipse swing oop swingx


    【解决方案1】:

    从这个问题和你的其他一些问题来看,你似乎有一个具体的想法,即这些窗口必须非常简单,其中没有代码,然后由其他类在外部进行操作。这不是 Swing(甚至 Java)的意义所在。

    将 JFrame 和 JDialog 想象成您家中的房间。你不会用所有合适的器具来设置你的厨房,然后进入餐厅并尝试远程操作炉子!

    如果窗口的工作是在屏幕中填充表格、更新表格并处理与表格相关的用户输入,那么所有代码​​都应该窗口的类中(无论是JFrame 或 JDialog)。

    考虑焦点。如果用户的焦点和输入在一个窗口内,那么处理它的代码也应该在那个窗口内。

    这是最基本的 OOP 原则之一:Encapsulation

    【讨论】:

      【解决方案2】:

      问题在于 getTreeTable() 不是静态方法,因此无法通过类名 (ProductionWindow.getTreeTable()) 访问。您需要一个对象的句柄来执行此操作。

      在你的 run() 中,当你声明一个新的“框架”时,将它存储在 Main 类的类级别属性中。然后使用“frame.getTreeTable()”。为了演示,写“框架”。在您声明“框架”之后,然后按 ctrl+space。你会在那里得到很多方法。

      【讨论】:

      • 哇,真快!谢谢!但是,现在我看到 frame 变量仅在 run() 方法中可用。如果我尝试在 EventQueue.invokeLater 块之外声明它,Eclipse 会给我更多错误(关于内部类和非最终变量的东西)。那我应该把我所有的操作代码都放在run() 方法中吗?我很困惑。
      • 不,我已经在答案中解释了这一点。就像您在 Main 类中有“Connection conn”一样,但作为静态属性;将“JFrame frame”作为 Main 类中的属性,但没有静态标识符。
      • 恐怕也不行。我被告知我不能对非静态字段进行静态引用。不过,如果我给它static 标识符,它似乎确实有效。
      • 啊,我的错。 Main 类中的属性应该是静态的。您可以从非静态上下文(在您的情况下运行方法)分配静态变量。它应该在你的 main 方法的其余部分中可用。
      • 好吧,它只是似乎起作用了。在实际运行中,将 ShowJobs.getTodaysJobs 行更改为 ShowJobs.getTodaysJobs(rs, nRows, frame.getTreeTable(), frame.getTextField()); 后,我被告知 frame.getTreeTable() 导致 NullPointerException。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-29
      • 1970-01-01
      相关资源
      最近更新 更多