本質上,我編碼的是一款益智遊戲。新創建的JButton不會覆蓋以前創建的JButtons
它包含一個圖像,圖像被進一步分成9個部分,放置在包含3x3 JButton GridLayout的JPanel上。最初,9個按鈕是空的。當用戶點擊「開始遊戲」時,9個按鈕將顯示按鈕上的圖像。
我用setPreferredSize()來設置包含9個空的JButton的JPanel的大小。之後,我使用Inset(0,0,0,0)使按鈕的內容填充整個按鈕。
但現在,當我想添加圖像按鈕來替換空的按鈕,當用戶點擊「開始遊戲」,它不起作用。
我認爲這是因爲我之前設置的setPreferredSize()
正在阻止Insets
的值工作。
我插入了一些system.out.println
值來檢查方法是否正在運行,它會運行,但當用戶單擊「開始遊戲」時圖像仍然拒絕出現在按鈕上。
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()
}
爲什麼要更換JButtons?爲什麼不簡單地交換JButtons顯示的ImageIcons? –
請檢查編輯到@ GagandeepBali的答案。他提供了一些很好的清晰示例代碼來說明他的觀點。 –