首页 > 解决方案 > 为什么我的 GUI 不工作,我需要一个可见的代码吗?

问题描述

我有一个作业问题,我正在尝试设置 GUI 并执行以下操作:

  Step 1. Create a random list of 52 elements holding 52 numbers 
           corresponding to 52 cards in the cards folder

   Step 2. Create a JFrame
        2a. set title of your frame
        2b. set layout of your frame to have a GridLayout

   Step 3. Create 3 cards
        3a. create 3 objects of ImageIcon whose image's location is 
            pointing to the image in the cards folder
        3b. create 3 JLabel object, each one hold an ImageIcon object 
            created above

   Step 4. Add three JLabel into your JFrame

   Step 5. Pack and display your frame

我在尝试使我的 GUI 可见时遇到了麻烦,并且在理解如何实现 ImageIcon 时也遇到了问题。我需要做一个网格布局,但没有一个显示出来。

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

public class Question_2 {

   static String location = "cards/";

   public static void main( String[] args ) {
      String[] cards;
      cards = new String[ 52 ];

      JFrame frmMyWindow = new JFrame( "Random Cards" );
      frmMyWindow.setSize( 300, 200 );
      frmMyWindow.setLocationRelativeTo( null );
      frmMyWindow.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

      frmMyWindow.setVisible( true );
   }

}

class frmMyWindow extends JFrame {

   JLabel lblName;
   JPanel panelMain, panelLeft, panelCenter, panelRight;
   private int realityState;
   private int commState;

   public frmMyWindow( String Cards ) {
      super( "Cards" );
      realityState = commState = 0;

      lblName = new JLabel( "Cards" );
      panelMain = new JPanel( new GridLayout( 1, 3, 10, 10 ) );
      setLayout( new BorderLayout( 20, 10 ) );

      add( lblName, BorderLayout.NORTH );

      add( panelMain, BorderLayout.CENTER );

      panelLeft = new JPanel( new FlowLayout( FlowLayout.CENTER, 5, 10 ) );
      panelCenter = new JPanel( new FlowLayout( FlowLayout.LEFT, 5, 5 ) );
      panelRight = new JPanel( new FlowLayout( FlowLayout.CENTER, 5, 10 ) );

      panelMain.add( panelLeft );
      panelMain.add( panelCenter );
      panelMain.add( panelRight );

   }

}

我希望代码显示在标题中包含单词 Cards 的位置,然后显示带有从卡片文件中随机选择的 3 张卡片的网格布局。

标签: java

解决方案


一切都很好,除了您正在创建JFrame实例而不是您的自定义类。

以下行

JFrame frmMyWindow = new JFrame( "Random Cards" );

应该

JFrame frmMyWindow = new frmMyWindow( "Random Cards" );

推荐阅读