[英]Why doesn't my JFrame show up?
我正试图在一个有81个盒子的窗口中显示一个解决的数独拼图。 我这样做了:
import java.awt.GridLayout;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class GraphicSolver extends JFrame {
GraphicSolver(int[][] spelplan) {
Panel panel = new Panel(new GridLayout(9,9));
for(int i=9;i<9;i++){
for(int x=0;x<9;x++){
panel.add(new JLabel(""+spelplan[i][x]));
}
}
Frame frame = new Frame();
frame.add(panel);
frame.setVisible(true);
}
}
但是,它只给了我一个没有任何数字的空窗口。 如果有人能指出我正确的方向,我会很高兴。
外循环应从零开始:
for(int i=0;i<9;i++){
尝试调用frame.pack ()
,这将在使用面板计算正确大小后将所有组件打包到要显示的框架中。 另外,按照@trashgod建议的修复将解决没有添加任何面板的事实,@ Ashkan Aryan的修复将使你的代码更合理(虽然它应该没有它,但是没有意义继承自JFrame)。
以下代码适用于我:
GraphicSolver(int[][] spelplan) {
Panel panel = new Panel(new GridLayout(9,9));
for(int i=0;i<9;i++){
for(int x=0;x<9;x++){
panel.add(new JLabel(""+spelplan[i][x]));
}
}
this.add(panel);
this.pack ();
this.setVisible(true);
}
你好像有两个框架。 1是JFrame(类GrpahicSolver本身),另一个是您在其中创建的框架。
我建议你用this.addPanel()替换frame.addPanel(),它应该工作。
import java.awt.GridLayout;
import javax.swing.*;
public class GraphicSolver {
GraphicSolver(int[][] spelplan) {
// presumes each array 'row' is the same length
JPanel panel = new JPanel(new GridLayout(
spelplan.length,
spelplan[0].length,
8,
4));
for(int i=0;i<spelplan.length;i++){
for(int x=0;x<spelplan[i].length;x++){
panel.add(new JLabel(""+spelplan[i][x]));
}
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
int[][] plan = new int[4][7];
for (int x=0; x<plan.length; x++) {
for (int y=0; y<plan[x].length; y++) {
plan[x][y] = (x*10)+y;
}
}
new GraphicSolver(plan);
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.