我有一个作业问题,我试图设置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的位置,然后显示从Card文件中随机选择的3张卡的网格布局。
答案 0 :(得分:0)
一切都很好,只不过您要创建JFrame
实例而不是自定义类。
以下行
JFrame frmMyWindow = new JFrame( "Random Cards" );
应该是
JFrame frmMyWindow = new frmMyWindow( "Random Cards" );