gpt4 book ai didi

java - 使用按钮数组调试 JFrame

转载 作者:行者123 更新时间:2023-11-30 05:52:41 24 4
gpt4 key购买 nike

我在为类(class)的战舰克隆生成一组按钮时遇到问题,而且似乎无法弄清楚为什么它不起作用。任何建议都会有所帮助...我让主类创建 jFrame,然后是网格类,更具体地说,生成器方法构建按钮数组。

import java.awt.*;

import javax.swing.*;

public class warship {

/**
* @param args
*/

public static void main(String[] args) {
JFrame gui = new JFrame();
gui.setSize(700, 350);
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setLayout(new FlowLayout());
grid oceanGrid = new grid();
oceanGrid.Generator();
gui.add(oceanGrid);
gui.setVisible(true);

}

}

网格.java

     import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.LayoutManager;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;


@SuppressWarnings("serial")
public class grid extends JPanel{
private static int rows = 7;
private static int col = 10;

public void Generator(){

ImageIcon wIcon = new ImageIcon ("H:\\workspace\\Warship\\src\\images\\water.jpg");
JPanel jPan1 = new JPanel();
jPan1.setLayout((LayoutManager) new GridLayout(rows,col,1,1));
jPan1.setSize(350,350);

//Set Border
TitledBorder bdr = javax.swing.BorderFactory.createTitledBorder(null, "Targeting Grid",
javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
javax.swing.border.TitledBorder.DEFAULT_POSITION,
new java.awt.Font("Arial", 0, 16));
bdr.setTitleColor(java.awt.Color.RED);
jPan1.setLayout((LayoutManager) new GridLayout(rows,col,1,1));
jPan1.setBorder(bdr);

//Creates the array of buttons
JButton b[]=new JButton[rows*col];
for (int i = 0, j= rows*col; i < j; i++){
b[i] = new JButton(wIcon);
b[i].setSize(20, 20);
b[i].setMaximumSize(new Dimension(20,20));
b[i].setPreferredSize(new Dimension(20,20));
System.out.println("loop test " + i);
jPan1.add(b[i]);
}
}
}

最佳答案

我认为这是你犯的错误:
您的类网格扩展了 JPanel,但是您声明并初始化了另一个 JPanel,您在其中添加了按钮。所以您实际上并没有将按钮添加到您的网格,而是添加到您不使用的另一个面板。

解决方法是去掉这一行

JPanel jPan1 = new JPanel();

并用 this 替换所有出现的 jPan1

这样您就可以将按钮添加到您的网格中。

关于java - 使用按钮数组调试 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11419654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com