我创建了两个名为 Graphic 和 Objects 的类。在我的图形类中,我创建了一个创建框架的方法。在对象类中,我想创建组件,所有JLabel,JPanel等等,所以一个类不会变大。现在我在一个类中有300多行代码。
图形课程:
public class Graphic extends UnicastRemoteObject implements Runnable, InterfaceI {
private static final long serialVersionUID = 1L;
private JFrame frame;
private JPanel panel;
private static double kWh;
private static double liter;
private static double temp;
private static String message = "Message";
private static String message2 = "Message";
private static String message3 = "Message";
private static boolean connection = true;
private Objects obj = new Objects();
protected Graphic() throws RemoteException {
super();
// Create objects
obj.createGuiObjects(frame, panel, kWh, liter, temp, message, message2, message3, connection);
}
public void createFrame() {
// Create window
frame = new JFrame(); // Create a new frame
frame.setSize(900, 400); // Sets size
frame.setResizable(false);
frame.setTitle("Monitor Service"); // Sets title
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setLocationRelativeTo(null); // Sets the window on the center of the screen
frame.setVisible(true);
}
对象类:
public void createGuiObjects(JFrame frame, JPanel panel, double kWh, double liter, double temp, String message, String message2, String message3, boolean connection) {
"All my labels and so on.
panel = new JPanel();
panel.setLayout(new GridLayout(1, 4, 10, 5));
panel.setBorder(new EmptyBorder(20, 20, 20, 20));
panel.setBackground(Color.decode("#34495e"));
panel.add(radiatorpanel);
panel.add(temppanel);
panel.add(waterpanel);
panel.add(powerpanel);
不知道是否可以将面板作为参数发送,因为我仍然在我的图形类中得到一个nullpointer异常,我正在运行 frame.add(panel); 这一行
这是一个分裂它的坏方法,还是我应该只在一个类中保存所有GUI元素?
答案 0 :(得分:0)
您的问题是,您永远不会在private JPanel panel
中初始化Graphics
。
obj.createGuiObjects(frame, panel, kWh, liter, temp, message, message2, message3, connection);
创建您的Objects
,但只要您离开
private JPanel panel;
原样,导致
frame.add(panel);
始终会抛出异常,因为面板始终保持默认值=> null
。
因此,您需要某种getter来访问您在Objects
public JPanel getInstance() { return this.panel; }
并在Graphics
panel = ob.getInstance();