Prezados,
Pesquisei bastante na internet e não sanei minha dúvida, por isso decidi criar esse tópico para que possam me ajudar se puderem.
Sou iniciante na linguagem (assim como em qualquer outra) e estou tentando criar uma aplicação gráfica começando por um formulário simples.
Não consigo de jeito nenhum colocar JButtons e JLabels em um JFrame, em uma das tentativas consegui criar um button que cobriu toda a área do frame rsrs. Onde estou errando?
Classe Main:
public class Principal {
public static void main(String[] args) {
JanelaPrincipal janPrin = new JanelaPrincipal();
}
}
Classe que cria a janela(frame):
import java.awt.*;
import javax.swing.*;
class JanelaPrincipal extends JFrame{
//COMPONENTES
private JButton botao1 = new JButton();
private JLabel label1 = new JLabel();
public JanelaPrincipal(){
montaJanela();
iniciaComponentes();
}
public void montaJanela(){
//INICIA A JANELA PRINCIPAL DO PROGRAMA
this.setSize(640, 480);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setAutoRequestFocus(true);
this.setTitle("Justice");
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
public void iniciaComponentes(){
//INICIA O BOTAO1
this.botao1.setVisible(true);
this.botao1.setText("BOTÃO");
this.botao1.setLocation(100,50);
this.botao1.setSize(1, 2);
this.add(botao1);
//INICIA O LABEL1
this.label1.setVisible(true);
this.label1.setText("Label 1");
this.label1.setLocation(120,10);
this.label1.setSize(10, 200);
this.add(label1);
}
}
usa o netbeans, e contrua com o swing. dps veja os codigos gerados
Faça exatamente isto que o augusto340 disse. Só reescrevendo seu código e explicando algumas coisa:
import java.awt.*;
import javax.swing.*;
class JanelaPrincipal extends JFrame{
private JButton botao1 = new JButton();
private JLabel label1 = new JLabel();
public JanelaPrincipal(){
montaJanela();
iniciaComponentes();
}
public void montaJanela(){
setSize(640, 480);
//this.setVisible(true); Para setar como visível seu JFrame use este comando na ultima linha do construtor (após iniciaComponentes();), porém é uma boa prática deixar que a classe que instancia (Principal) o JFrame JanelaPrincipal chame o método setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this.setAutoRequestFocus(true); Neste código não precisa disto
setTitle("Justice");
setExtendedState(JFrame.MAXIMIZED_BOTH);
setLayout(new FlowLayout()); //Usando gerenciador de layout de fluxo, pesquise sobre eles.
}
public void iniciaComponentes(){
//INICIA O BOTAO1
//this.botao1.setVisible(true); Por default os componentes já aparecem visíveis (com exceção do JFrame)
this.botao1.setText("BOTÃO");
//this.botao1.setLocation(100,50); Não use setLocation(); aprenda usar gerenciadores de layout...
//this.botao1.setSize(1, 2); ...assim não precisa coocar tamanho em botão
add(botao1);
//INICIA O LABEL1
// this.label1.setVisible(true);
this.label1.setText("Label 1");
//this.label1.setLocation(120,10);
//this.label1.setSize(10, 200);
add(label1);
}
}
public class Principal {
public static void main(String[] args) {
JanelaPrincipal janPrin = new JanelaPrincipal();
janPrin.setVisible(true);
}
}
:thumbup:
Obrigado Henrique, ajudou bastante. Pesquisei bastante aqui no GUJ e implementei o layout manager GridBagLayout. E com suas dicas dei uma reformulada no código (fiz também pelo NetBeans mas achei um pouco dificil de aprender). Ficou assim:
import java.awt.*;
import javax.swing.*;
public class TelaLogin extends JFrame {
//COMPONENTES
private JButton botao1 = new JButton();
private JButton botao2 = new JButton();
private JButton botao3 = new JButton();
private JLabel label1 = new JLabel();
private JLabel label2 = new JLabel();
private JTextField text1 = new JTextField();
private JTextField text2 = new JTextField();
//MÉTODO CONSTRUTOR
public TelaLogin(){
//VARIAVEIS DO GRIDBAGLAYOUT
GridBagLayout layout = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
getContentPane().setLayout(layout);
//INICIA A JANELA PRINCIPAL DO PROGRAMA
this.setSize(340, 240);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Justice");
//CONFIGURA AS PROPRIEDADES DO BOTAO1
botao1.setVisible(true);
botao1.setText("BOTÃO 1");
c.gridy = 2; // terceira linha
c.gridx = 1; // segunda coluna
layout.setConstraints(botao1, c);
getContentPane().add(botao1);
//CONFIGURA AS PROPRIEDADES DO BOTAO2
botao2.setText("BOTÃO 2");
c.gridy = 2; // terceira linha
c.gridx = 2; // terceira coluna
layout.setConstraints(botao2, c);
getContentPane().add(botao2);
//CONFIGURA AS PROPRIEDADES DO BOTAO3
botao3.setText("BOTÃO 3");
c.gridy = 2; // terceira linha
c.gridx = 3; // quarta coluna
layout.setConstraints(botao3, c);
getContentPane().add(botao3);
//CONFIGURA AS PROPRIEDADES DO LABEL1
label1.setText("Label 1");
c.gridy = 0; // primeira linha
c.gridx = 0; // primeira coluna
layout.setConstraints(label1, c);
getContentPane().add(label1);
//CONFIGURA AS PROPRIEDADES DO LABEL2
label2.setText("Label 2");
c.gridy = 1; // segunda linha
c.gridx = 0; // primeira coluna
layout.setConstraints(label2, c);
getContentPane().add(label2);
//CONFIGURA AS PROPRIEDADES DO TEXTFIELD1
c.gridy = 0; // segunda linha
c.gridx = 1; // primeira coluna
layout.setConstraints(text1, c);
getContentPane().add(text1);
//CONFIGURA AS PROPRIEDADES DO TEXTFIELD2
c.gridy = 1; // segunda linha
c.gridx = 1; // primeira coluna
layout.setConstraints(text2, c);
getContentPane().add(text2);
//MOSTRA A JANELA
this.setVisible(true);
}
}
Outra questão que tenho é a forma de instânciar os componentes, eu instanciei dentro da classe dessa forma:
private JButton botao1 = new JButton();
Mas parece que está errado já que nos exemplos que vi o pessoal termina de instânciar no método construtor desse modo:
class exemplo{
JButton botao1;
public exemplo(){
botao1 = new JButton;
}
}
Nos meus testes os dois modos deram certo, então porque fazem do 2º jeito se é possível instânciar os componentes em uma só linha?