构建GUI框架但显示为空白

时间:2016-11-24 03:11:36

标签: java swing user-interface

这是一个帧查看器类

import javax.swing.JFrame;

public class Viewer
{
  public static void main(String[]args)
{
   JFrame frame = new Frame();

   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setTitle("Shinkei-suijaku");
   frame.setVisible(true);
}
}

这是一个框架类

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;


public class Frame extends JFrame
{
   private static final int FRAME_WIDTH = 1000;
   private static final int FRAME_HEIGHT = 800;
   private final int FIELD_WIDTH = 10;
   private ImageIcon image1;
   private JLabel label1;
   private ImageIcon image2;
   private JLabel label2;
   private ImageIcon image3;
   private JLabel label3;
   private JComboBox combo;
   private JTextField textField1;
   private JTextField textField2;
   private JButton button;
   private JPanel ChoosePanel;
   private JPanel ImagePanel;
   public Frame()
   {  

      createImagePanel();
      createChoosePanel();
      add(ChoosePanel,BorderLayout.CENTER);
      add(ImagePanel, BorderLayout.SOUTH); 
      setSize(FRAME_WIDTH,FRAME_HEIGHT);
   }
      //create a image panel for images
      public void createImagePanel()
      {
      ImagePanel = new JPanel();
      ImagePanel.setLayout(new GridLayout(2,3));
      image1 = new ImageIcon(getClass().getResource("cover.jpg"));
      label1 = new JLabel(image1);
      ImagePanel.add(label1);
      ImagePanel.add(label1);
      ImagePanel.add(label1);
      ImagePanel.add(label1);
      ImagePanel.add(label1);
      ImagePanel.add(label1);
      }
      //create a panel for combobox and textfield
      public void createChoosePanel()
      {
      ChoosePanel = new JPanel();
      ChoosePanel.setLayout(new GridLayout(1,4));
      combo =new JComboBox();
      combo.addItem("reveal");
      combo.addItem("cover");
      combo.addItem("done");
      ChoosePanel.add(combo);

      textField1 = new JTextField(FIELD_WIDTH);
      textField2 = new JTextField(FIELD_WIDTH);
      ChoosePanel.add(textField1);
      ChoosePanel.add(textField2);

      button = new JButton("check");
      ChoosePanel.add(button);

      }




      //Frame uses BorderLayout by default


      }

这是记忆游戏程序的一部分。首先,我们需要构建一个包含图像,按钮和文本字段的GUI框架。它可以编译,但是当我运行它时,它只显示空白帧。我不知道问题。

1 个答案:

答案 0 :(得分:0)

enter image description here

我可以运行你的应用程序并获得图片所示的GUI。

但我在

上有一个NullPointer异常
image1 = new ImageIcon(getClass().getResource("cover.jpg"));

请确保图片文件的路径正确。