java - 为什么我的 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 张卡片的网格布局。
解决方案
一切都很好,除了您正在创建JFrame
实例而不是您的自定义类。
以下行
JFrame frmMyWindow = new JFrame( "Random Cards" );
应该
JFrame frmMyWindow = new frmMyWindow( "Random Cards" );
推荐阅读
- python - Beautiful Soup:从 p 元素中分离出 span 元素
- maven - 使用 maven pom.xml 生成包含 WAR 文件的 Ear 文件
- php - DATETIME2 到 UNIX 时间戳
- c++ - 为什么 test.h.gcov 将内容显示为 /EOF/
- python - 什么是计算python中两个向量角度余弦的稳健方法?
- php - 根原因拥有的 Laravel Storage Cache 文件夹无法清除缓存
- python - Dataframe.to_json() 不呈现所有参数(熊猫)
- python - 从 protobuf 字节数据读取到 msg
- blueprism - Blue Prism 未检测到 Chrome 打开工具中的元素
- spring-boot - 如何使用 spring boot 和 spring secuirty 使用基本身份验证标头中的凭据对 LDAP 中的用户进行身份验证