[英]Array of JLabel ImageIcon
我正在嘗試創建數獨游戲。 我想使用JSwing API。 因此,我正在使用JLabel數組顯示網格。 我有一張3x3網格的圖片,我想在3x3網格中顯示。 我的問題是它不會顯示圖像。 有人可以幫我解決問題嗎?
我的當前代碼看起來像這樣,分為兩個類。
Main.class
package com.brendenbunker;
import javax.swing.*;
import java.awt.*;
public class Main{
FileMaker fileMaker;
void init() {
fileMaker = new FileMaker();
}
public static void main(String args[]){
ScreenGenerator gui = new ScreenGenerator();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = gui.gridPic.getIconWidth();
double height = gui.gridPic.getIconHeight();
int h = (int) height*4;
int w = (int) width*3;
gui.setSize(w,h);
gui.setTitle("Suduko");
gui.setVisible(true);
}
}
ScreenGenerator.class
package com.brendenbunker;
import javax.swing.*;
import java.awt.*;
public class ScreenGenerator extends JFrame{
//Intro Components
//JLabel temp;
JLabel[] gridLabel;
ImageIcon gridPic;
//intro Vars
public ScreenGenerator() {
setLayout(new FlowLayout());
gridPic = new ImageIcon(getClass().getResource("/Grid_Unified.png"));
gridLabel = new JLabel[8];
for (int i=0; i>=9; i++) {
gridLabel[i] = new JLabel("Hello");
}
for (int i=0; i>=9; i++) {
gridLabel[i].setIcon(gridPic);
add(gridLabel[i]);
}
}
}
所有幫助下
更改您的循環,它不會根據您的條件進入循環。
更改此循環。
for (int i=0; i<8; i++) {
gridLabel[i] = new JLabel("Hello");
}
for (int i=0; i<8; i++) {
gridLabel[i].setIcon(gridPic);
add(gridLabel[i]);
}
它會工作..
package com.brendenbunker;
import javax.swing.*;
import java.awt.*;
public class ScreenGenerator extends JFrame{
//Intro Components
//JLabel temp;
JLabel[] gridLabel;
ImageIcon gridPic;
//intro Vars
public ScreenGenerator() {
setLayout(new FlowLayout());
gridPic = new ImageIcon(getClass().getResource("/Grid_Unified.png"));
gridLabel = new JLabel[8];
//for (int i=0; i>=9; i++) {
//gridLabel[i] = new JLabel("Hello");
// }
for (int i=0; i>=9; i++) {
gridLabel[i] = new JLabel(gridPic);
add(gridLabel[i]);
}
}
}
如果您需要圖標,則使用上面的代碼,如果您想要文本和圖標,則以下更改將為您提供幫助
gridLabel[i] = new JLabel("hello", gridPic, JLabel.CENTER);
希望有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.