Estou fazendo o jago batalha naval e estou com dificuldade para inserir um icone no meu botão, pois quando faço isso a tabela fica toda bagunçada, segue o meu codigo e as imagens que usei nele.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class CGridBagLayot extends JFrame {
private ImageIcon im = new ImageIcon(getClass().getResource("fotos/back.jpg"));
private ImageIcon im2 = new ImageIcon(getClass().getResource("fotos/agua.jpg"));
private JButton[][] botao = new JButton[10][10];
private Container cJFrame = getContentPane();
private Container cJPanel1 = new JPanel();
private Container cJPanel2 = new JPanel();
private JLabel imagem = new JLabel(im);
private GridBagConstraints configBotao = new GridBagConstraints();
private int x = Toolkit.getDefaultToolkit().getScreenSize().width;
private int y = Toolkit.getDefaultToolkit().getScreenSize().height-35;
public CGridBagLayot(){
cJFrame.setLayout(new BorderLayout());
cJPanel1.setLayout(new GridBagLayout());
cJPanel2.setLayout(new GridBagLayout());
criarBotoes(cJPanel1);
criarBotoes(cJPanel2);
cJFrame.add(BorderLayout.EAST,cJPanel1);
cJFrame.add(BorderLayout.WEST,cJPanel2);
cJFrame.add(BorderLayout.CENTER,imagem);
setSize(x,y);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void criarBotoes(Container c){
for (int i = 0; i < botao.length; i++) {
for (int j = 0; j < botao.length; j++) {
botao[i][j]=new JButton();
// botao[i][j].setIcon(im2);
adcionaNoGridBagLayout(i, j,botao[i][j],c);
}
}
}
public void adcionaNoGridBagLayout(int linha,int coluna,JButton b, Container c ){
configBotao.gridx = coluna;
configBotao.gridy = linha;
configBotao.gridwidth = 1;
configBotao.gridheight = 1;
configBotao.weightx=0;
configBotao.weighty=1;
configBotao.fill = GridBagConstraints.BOTH;
configBotao.anchor = GridBagConstraints.CENTER;
c.add(b,configBotao);
}
public String toString(){
String tabuleiro="";
for (int i = 0; i < 10; i++) {
tabuleiro+= "\n";
for (int j = 0; j < 10; j++) {
tabuleiro+=botao[i][j].getName()+"|";
}
}
return tabuleiro;
}
public static void main(String[] args) {
CGridBagLayot g = new CGridBagLayot();
g.toString();
}
}