Alguem tira esta duvida?

14 respostas
P
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList.*; 

 
 public class BorderLayoutTest extends JFrame
 {    
     public ArrayList notes;
     
     public BorderLayoutTest()
     {    
         //private ArrayList notes;
         notes = new ArrayList();
         int nums;
         JButton botao = new JButton("Botão");
         /*JButton botao2 = new JButton("Botão 2");
         JButton botao3 = new JButton("Botão 3");
         JButton botao4 = new JButton("Botão 4");
         JButton botao5 = new JButton("Botão 5");*/
         
         // Como o padrao de um JFrame é o 
         // BorderLayout, simplesmente adicionamos
         // os componentes na tela
         getContentPane().add(botao, BorderLayout.NORTH);
//         getContentPane().add(botao2, BorderLayout.CENTER);
         /*getContentPane().add(botao3, BorderLayout.WEST);
         getContentPane().add(botao4, BorderLayout.SOUTH);
         getContentPane().add(botao5, BorderLayout.EAST);*/
         
         
         Iterator it = notes.iterator();
         while(it.hasNext()){
             notes.add(botao);
             //notes.add(botao2);
             /*notes.add(botao3);
             notes.add(botao4);
             notes.add(botao5);*/
            System.out.println(it.next());
        }
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         
         pack();
         setVisible(true);
     
    }
      public static void main(String args[])
     {
         new BorderLayoutTest();
     }
     
    
}

A ideia é adicionar botoes a um ArrayList, cujo seu tamanho vai ser definido pelo utilizador. Uma grelha de N*N casas (N entre 10 e 26; as linhas são identificadas por letras a partir de A, e as colunas por números a partir de 1). Será obviamente desatroso adicionar os botoes manualmente né? Que outra forma mais eficaz e simples?

14 Respostas

marllonSimoes

acredito que naum tenha outra forma de adicionar isso,mesmo por que vc teria que validar a quantidade que o usuário solicitar e dai adicionar… melhor memso fazer da forma que vc fez…
certa vez fiz algo semelhante para um tabuleiro de xadrez… onde tinha que adicionar as “casas” do jogo… foi meio trabalho ainda mais porque cada casa tem uma cor… mas ficou parecido com a forma que vc fez…
abraços…

rodrigo1

e se usar uma matriz !?.. não fica mais fácil p/ descobrir depois qual botão foi acionado !? …

P

Como assim ma matriz? Um ArrayList Bidimensional?

A dificuldade que tenho agora é o facto de que terei de inserir à mão os botoes, q podem ser no maximo mais de 80. Fazer à mão mais de 120 (pois tabuleiro pra jogador e cmputador) será desastroso. Não haverá forma mais simples de inserir botoes ao ArrayList?
Digam algo, sugestoes!!! Partilhem ideias malta!! :wink:

rodrigo1

tá meio tosco .....

mas é isto que eu tava querendo dizer ...

vê se ajuda ?

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


@SuppressWarnings("serial")
public class MainFrame extends JFrame implements ActionListener{

	JButton[][] _botoes = null;
	
	public MainFrame() {
		setSize(400, 400);
		setLayout(new BorderLayout());
		setLocation(200, 100);
		getContentPane().add(getPanelComponents());
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setMinimumSize(new Dimension(400, 400));
        setVisible(true);
	}
	
	private JPanel getPanelComponents() {
		JPanel panel = new JPanel();
		panel.setLayout(new GridLayout(20,20));
		_botoes = new JButton[20][20];
		for (int i = 0; i< 20; i++){
			for (int j = 0; j< 20; j++){
				JButton b = new JButton();
				b.addActionListener(this);
				_botoes[i][j] = b;
				panel.add(b,i,j);
			}
		}
		return panel;
	}

	
	public static void main(String[] args) {
		MainFrame fr = new MainFrame();
	}

	public void actionPerformed(ActionEvent e) {
		// OBS: o botão 0,0 (Ref) é o do cando inferior esquerdo
		for (int i = 0; i< 20; i++){
			for (int j = 0; j< 20; j++){
				if (e.getSource() == _botoes[i][j]){
					JOptionPane.showMessageDialog(this, "botão: " + i + "," + j);
				}
			}
		}
	}

}
P

legal.
ja entendi.
:slight_smile:
thanks.
a ideia é fazer o jogo batalha naval e tou pensando fazer dois tabuleiros dentro de uma jframe.
um tabuleiro pra o jogador e outro pra o computador.
como poderia fazer? tipo 2 jframes internas? uma pra cada tabuleiro?

rodrigo1

na verdade seriam dois JPanels, … um para cada tabuleiro …

P

Tentei mas não deu!
Dá erro! Ora vejam o codigo!...

import java.awt.BorderLayout;
 import java.awt.Dimension;
 import java.awt.GridLayout;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import javax.swing.JButton;
 import javax.swing.JFrame;
 import javax.swing.JOptionPane;
 import javax.swing.JPanel;
 
 
public class MainFrame extends JFrame implements ActionListener{
 
 	JButton[][] botoes = null;
 	
 	public MainFrame() {
 		setSize(400, 400);
 		setLayout(new BorderLayout());
 		setLocation(200, 100);
 		getContentPane().add(getPanelComponents());
 		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setMinimumSize(new Dimension(400, 400));
         setVisible(true);
 	}
 	
 	private JPanel getPanelComponents() {
 		JPanel panel1 = new JPanel();
 		JPanel panel2 = new JPanel();
 		panel1.setLayout(new GridLayout(10,10));
 		panel2.setLayout(new GridLayout(20,20));
 		botoes = new JButton[10][10];
 		botoes = new JButton[20][20];
 		for (int i = 0; i< 10; i++){
 			for (int j = 0; j< 10; j++){
 				JButton b = new JButton();
 				b.addActionListener(this);
 				botoes[i][j] = b;
 				panel1.add(b,i,j);
 				panel2.add(b,i,j);
 			}
 		}
 		return panel1;
 		return panel2;
 	}
 
 	
 	public static void main(String[] args) {
 		MainFrame fr = new MainFrame(); //desnecessario pois nunca é lida a fr
 	}
 
 	public void actionPerformed(ActionEvent e) {
 		// OBS: o botão 0,0 (Ref) é o do cando inferior esquerdo
 		for (int i = 0; i< 10; i++){
 			for (int j = 0; j< 10; j++){
 				if (e.getSource() == botoes[i][j]){
 					JOptionPane.showMessageDialog(this, "botão: " + i + "," + j);
 				}
 			}
 		}
 	}
 
 }
rodrigo1

return panel1;
return panel2;

depois que um método executa o return …
o que vier depois não é executado …

vê aqui :

vc pode por exemplo fazer dois desses um para cada tabuleiro …

P

sim entendi, mas dá erro, ora veja:

import java.awt.BorderLayout;
 import java.awt.Dimension;
 import java.awt.GridLayout;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import javax.swing.JButton;
 import javax.swing.JFrame;
 import javax.swing.JOptionPane;
 import javax.swing.JPanel;
 
 
public class MainFrame extends JFrame implements ActionListener{
 
 	JButton[][] botoes = null;
 	
 	public MainFrame() {
 		setSize(400, 400);
 		setLayout(new BorderLayout());
 		setLocation(200, 100);
 		getContentPane().add(getPanelComponents());
 		getContentPane().add(getPanelComponents());
 		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setMinimumSize(new Dimension(600, 500));
         setVisible(true);
 	}
 	
 	private JPanel getPanelComponents() {
 		JPanel panel1 = new JPanel();
 		//JPanel panel2 = new JPanel();
 		panel1.setLayout(new GridLayout(10,10));
 		//panel2.setLayout(new GridLayout(20,20));
 		botoes = new JButton[10][10];
 		//botoes = new JButton[20][20];
 		for (int i = 0; i< 10; i++){
 			for (int j = 0; j< 10; j++){
 				JButton b = new JButton();
 				b.addActionListener(this);
 				botoes[i][j] = b;
 				panel1.add(b,i,j);
 				//panel2.add(b,i,j);
 			}
 		}
 		return panel1;
 		//return panel2;
 		
 		}
 	
 	private JPanel getPanelComponents()() {
 		//JPanel panel1 = new JPanel();
 		JPanel panel2 = new JPanel();
 		//panel1.setLayout(new GridLayout(10,10));
 		panel2.setLayout(new GridLayout(20,20));
 		//botoes = new JButton[10][10];
 		botoes = new JButton[20][20];
 		for (int i = 0; i< 10; i++){
 			for (int j = 0; j< 10; j++){
 				JButton b = new JButton();
 				b.addActionListener(this);
 				botoes[i][j] = b;
 				//panel1.add(b,i,j);
 				panel2.add(b,i,j);
 			}
 		}
 		//return panel1;
 		return panel2;
 		
 		}
 	
 
 	public static void main(String[] args) {
 		MainFrame fr = new MainFrame(); //desnecessario pois nunca é lida a fr
 	}
 
 	public void actionPerformed(ActionEvent e) {
 		// OBS: o botão 0,0 (Ref) é o do cando inferior esquerdo
 		for (int i = 0; i< 10; i++){
 			for (int j = 0; j< 10; j++){
 				if (e.getSource() == botoes[i][j]){
 					JOptionPane.showMessageDialog(this, "botão: " + i + "," + j);
 				}
 			}
 		}
 	}
 
 }
P

o q será q me escapa?
humm…

Luca

Olá

A criação de títulos de tópicos com o mínimo bom senso.

[]s
Luca

rodrigo1

olha meu amigo … tá doze viu …

vc tá cometendo erros de conceito muito básicos …

rola estudar mais Java …

o que é isto !?

além disto … dois métodos com a mesma assinatura ?

P

eu tou aprendendo java sim.
inda tou no começo.
e esta materia inda n dei, apenas tou aprendendo antecipadamente!
:wink:
mas obrigado pelas lições/sugestoes!
o getPanelComponents() é um metodo que mostra q “saca” painel, certo?
Sim, erro grave (q ja aprendi) de ter metodos com as assinaturas iguazinhas!
Sim, tenho antes de aprender pra dps questionar por aqui.
Que recomendação dá pra estudar este conteúdo? Swings, Awt, JFrames, Jframes internas, …! O tutorial da Sun n gosto. Conhece algum tutorial bom que fale bem de forma simples e agradavel sobre esta materia. Assim estarei dentro do assunto e assim falaremos sobre ele, …!
:wink:

P

Fiz umas experiencias mas continua a dar erro:...
se tenho de estudar mais, digam no problem ora ;)

import java.awt.*; 
 import javax.swing.*; 
 import javax.swing.border.*; 

 public class manGui extends JFrame implements ActionListener
 { 
 	// variaveis
 	private JPanel contentPane; 
 	private JPanel jPanel1; 
   	private JPanel jPanel2; 
 	private JPanel jPanel3; 

        JButton[][] _botoes = null;
 
   
 	public manGui() 
 	{ 
 		super(); 
 		initializeComponent(); 
 		  
 		this.setVisible(true); 
 	} 

 	private void initializeComponent() 
 	{ 
 		contentPane = (JPanel)this.getContentPane(); 
 		//----- 
 		jPanel1 = new JPanel(); 
 		//----- 
 		jPanel2 = new JPanel(); 
 		//----- 
 		jPanel3 = new JPanel(); 
 		//----- 
  
 	
 		// contentPane 
 		contentPane.setLayout(null); 
 		addComponent(contentPane, jPanel1, 28,75,319,356); 
 		addComponent(contentPane, jPanel2, 368,75,297,356); 
 		addComponent(contentPane, jPanel3, 30,465,636,66); 

 		// jPanel1 
  		jPanel1.setLayout(null); 
 		jPanel1.setBorder(new TitledBorder("Jogador")); 

//---------------
 		_botoes = new JButton[10][10];
 		for (int i = 0; i< 10; i++){
 			for (int j = 0; j< 10; j++){
 				JButton b = new JButton();
 				b.addActionListener(this);
 				_botoes[i][j] = b;
 				JPanel1.add(b,i,j);
 				
 			}
                   return JPanel1;
 		}
 		
//---------------


 		 
 		// jPanel2 
  		jPanel2.setLayout(null); 
 		jPanel2.setBorder(new TitledBorder("Computador")); 

 		// jPanel3 
  		jPanel3.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); 

 		// manGui 
 		this.setTitle("IGui"); 
 		this.setLocation(new Point(0, 0)); 
 		this.setSize(new Dimension(722, 577)); 
 	} 
  
 	// Add Componentes 
 	private void addComponent(Container container,Component c,int x,int y,int width,int height) 
 	{ 
 		c.setBounds(x,y,width,height); 
 		container.add(c); 
 	} 
  
//Main
 	public static void main(String[] args) 
 	{ 
 		JFrame.setDefaultLookAndFeelDecorated(true); 
 		JDialog.setDefaultLookAndFeelDecorated(true); 
 		try 
 		{ 
 			UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); 
 		} 
 		catch (Exception ex) 
 		{ 
 			System.out.println("Nao abre L&F: "); 
 			System.out.println(ex); 
 		} 
 		new manGui(); 
 	} 
public void actionPerformed(ActionEvent e) {
 		// OBS: o botão 0,0 (Ref) é o do cando inferior esquerdo
 		for (int i = 0; i< 10; i++){
 			for (int j = 0; j< 10; j++){
 				if (e.getSource() == _botoes[i][j]){
 					JOptionPane.showMessageDialog(this, "botão: " + i + "," + j);
 				}
 			}
 		}
 	}

 }

Nao aparecem os botoes no 1º painel! Porque será?

Criado 6 de novembro de 2006
Ultima resposta 8 de nov. de 2006
Respostas 14
Participantes 4