基本上,我编码的是益智游戏 .
它包含一个图像,图像进一步分为9个部分,放在包含3x3 JButton GridLayout的JPanel上 . 最初,9个按钮是空的 . 当用户点击“开始游戏”时,9个按钮将显示按钮上的图像 .
我使用setPreferredSize()来设置包含9个空JButton的JPanel的大小 . 之后,我使用Inset(0,0,0,0)使按钮的内容填满整个按钮 .
但现在,当我想添加成像按钮以在用户点击“开始游戏”时替换空按钮时,它不起作用 .
我想这是因为我之前设置的 setPreferredSize()
阻止了 Insets
值的工作 .
我插入了一些 system.out.println
值来检查方法是否正在运行,它运行,但是当用户单击"Start Game"时,图像仍然拒绝显示在按钮上 .
public class GameFrame extends JFrame implements ActionListener {
private JButton button1;
private JButton[] button = new JButton[9];
private Insets buttonMargin;
private boolean testImageMethod;
private JPanel puzpiece;
public GameFrame(){
//.. coding ..
// create new buttons - button1
button1 = new JButton("Start Game");
// add action event to "Start" button
button1.addActionListener(this);
// creates a new panel for the splitted puzzle pieces
puzpiece = new JPanel();
puzpiece.setLayout(new GridLayout(3,3));
// check if testImageMethod boolean ( in setupImage() ) is true,
//if it isn't, adds 9 buttons w/o images.
for(int a=0; a<9; a++){
if(testImageMethod){
}
else{
// adds 9 buttons without images
button[a] = new JButton();
puzpiece.add(button[a]);
puzpiece.setPreferredSize(new Dimension(500,200));
}
}
// adds puzpiece panel into the frame
this.add(puzpiece,BorderLayout.WEST);
//.. coding ..
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == button1){
// puzpiece.button.setVisible(false);
//puzpiece.remove(button);
// call setImage() method
setImage();
for(int a=0; a<9; a++){
// adds the new 9 buttons with images into panel
puzpiece.add(button[a]);
// test if method is running
System.out.println("qq");
}
}
else{
System.out.println("bbb");
}
}
// method setImage() divides the image into subimages
public void setImage(){
//.. coding ..
// test if method is running
System.out.println("a");
setupImage( count++, sc );
}
// method setupImage() adds the subimages to the buttons
private void setupImage( int a, Image wi )
{
// test if method is running
System.out.println("d");
buttonMargin = new Insets( 0, 0, 0, 0 );
button[a] = new JButton( new ImageIcon( wi ) );
button[a].setMargin( buttonMargin );
// test if method is running
System.out.println("e");
} // end method setupImage()
}
2 回答
我不确定我到底知道你在做什么,但......
看来您正在使用3x3纯JButton网格填充JPanel,
按下按钮,您将添加显示图像的JButton .
但是在添加新按钮之前我没有看到你删除原始按钮 .
在改变组件后,我也没有看到你在puzpiece JPanel上调用
revalidate()
然后repaint()
.更重要的是,为什么交换JButton时更容易交换已经由puzpiece JPanel持有的JButton中的ImageIcons?这是10分钟前我在评论中推荐的,但我现在正在回答 .
只需
setIcon
表示JButton
,不要将JButton
重新添加到JPanel
,已经可见一个小例子: