我正在尝试制作一个具有网格布局的GUI,该布局在一个文件中显示3个随机的不可重复的卡片。我将所有卡片命名为1-53.png,然后尝试将其插入左侧,中央和右侧面板。当我尝试将文件添加到面板中时,.add出现错误,并且我不知道如何解决它。
我已经尝试更改.add和索引。我什至试图将int转换为组件,但没有任何效果。
public class Question_2 {
static String location = "cards/";
public static void main(String[] args) {
JFrame frmMyWindow = new frmMyWindow("Random Cards");
frmMyWindow.setSize(300, 200);
frmMyWindow.setLocationRelativeTo(null);
frmMyWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMyWindow.setVisible(true);
}
}
class frmMyWindow extends JFrame {
JLabel lblName, l;
JPanel panelMain, panelLeft, panelCenter, panelRight;
JFrame f;
public frmMyWindow(String Cards) {
super("Random Cards");
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);
panelLeft.setBorder(new TitledBorder("Card 1"));
panelCenter.setBorder(new TitledBorder("Card 2"));
panelRight.setBorder(new TitledBorder("Card 3"));
int index = (int) Math.round(Math.random() * 53);
int index2 = (int) Math.round(Math.random() * 53);
int index3 = (int) Math.round(Math.random() * 53);
while (index == index2) {
index2 = (int) Math.round(Math.random() * 53);
}
while (index3 == index2 || index3 == index)
;
{
index3 = (int) Math.round(Math.random() * 53);
}
String image = index + ".png";
String image2 = index2 + ".png";
String image3 = index3 + ".png";
panelLeft.add(index);
panelCenter.add(index2);
panelRight.add(index3);
}
}
我希望程序在面板中显示3张随机卡片,但是.add错误。
答案 0 :(得分:2)
问题确实出在add
方法及其调用方式上。 Container#add
方法将Component
s作为参数。您可以使用int
个参数来调用它。
我什至试图将int转换为组件,但没有任何效果。
(我想)“在容器中添加数字”的最简单方法是创建一个JLabel
并将数字作为文本添加到其中。通过看到您的第一次尝试,我猜您再次弄乱了这些方法。可能是在JLabel
的构造函数中。您做了类似new JLabel(index)
的操作,其中index
是一个整数。再次失败,因为没有带有int
参数的构造函数。解决方案是创建一个JLabel
并将整数转换为文本:
panelLeft.add(new JLabel(String.valueOf(index)));
之后,可以编译并运行该程序。但是,一些注意事项是:
SwingUtilities#invokeLater
运行您的应用程序。public static void main(String[] args) {
SwingUtilities.invokeLater(()->{
JFrame frmMyWindow = new frmMyWindow("Random Cards");
frmMyWindow.setSize(300, 200);
frmMyWindow.setLocationRelativeTo(null);
frmMyWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMyWindow.setVisible(true);
});
}
frmMyWindow
重命名为FrmMyWindow
。