[Duvida] livro Use a cabeça java

10 respostas
T
Boa tarde a todos. Iniciei no mundo java faz pouco tempo , e optei pelo livro Use a cabeça java para começar a aprender sobre o assunto. Acontece que acabei "encalhando" em uma parte, onde inicia o construção de GUI's em java. Ficaria muito agradecido se alguem pudesse me ajudar. A duvida minha esta na pagina 261 onde tenho que fazer um botão que desenhe circulos em um JPanel , acontece que não tenho a minima ideia de como fazer isso. Segue o codigo das classes:
import java.awt.*;
import javax.swing.*;

public class MyDrawPanel extends JPanel{
}

public void MyDrawPanel(){
Graphics2D g2d = (Graphics2D) g;

int red = (int) (Math.random()*255);
int green = (int) (Math.random()*255);
int blue = (int) (Math.random()*255);
Color startColor = new Color(red, green, blue);

red = (int) (Math.random()*255);
green = (int) (Math.random()*255);
blue = (int) (Math.random()*255);
Color endColor = new Color(red, green, blue);

GradientPaint gradient = new GradientPaint(70,70,startColor,150,150,endColor);
g2d.setPaint(gradient);
g2d.fillOval(70,70,100,100);

}

}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SimpleGui3C implements ActionListener{
JFrame frame;
public static void main(String[] args){
 SimpleGui3C gui = new SimpleGui3C();
 gui.go();
}

public void go(){
frame = new JFrame();
frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);
JButton button = new JButton("Change color");
button.addActionListener(this);
Graphics gra;
MyDrawPanel drawPanel = new MyDrawPanel(gra);

frame.getContentPane().add(BorderLayout.SOUTH, button);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setSize(300,300);
frame.setVisible(true);

}

public void actionPerformed(ActionEvent event){
frame.repaint();
}

public void repaint(){


}
}
Obrigado desde já...

10 Respostas

InSeOfKn

Bem vindo ao GUJ e ao JAVA!

Porque você esta fechando claves na linha 5 do MyDrawPanel??

Até!

T
Desculpe pelo erro , os codigos ficariam assim
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SimpleGui3C implements ActionListener{
JFrame frame;
public static void main(String[] args){
 SimpleGui3C gui = new SimpleGui3C();
 gui.go();
}

public void go(){
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Change color");
button.addActionListener(this);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.SOUTH, button);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);

frame.setSize(300,300);
frame.setVisible(true);

}

public void actionPerformed(ActionEvent event){
frame.repaint();
}

public void repaint(){


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

public class MyDrawPanel extends JPanel{


public void paintComponents(Graphics g){
Graphics2D g2d = (Graphics2D) g;

int red = (int) (Math.random()*255);
int green = (int) (Math.random()*255);
int blue = (int) (Math.random()*255);
Color startColor = new Color(red, green, blue);

red = (int) (Math.random()*255);
green = (int) (Math.random()*255);
blue = (int) (Math.random()*255);
Color endColor = new Color(red, green, blue);

GradientPaint gradient = new GradientPaint(70,70,startColor,150,150,endColor);
g2d.setPaint(gradient);
g2d.fillOval(70,70,100,100);
	

}

}

Não estou entendendo muito bem o funcionamento do JPanel e como adiciono o desenho;/

T

Não entendo o método paintComponents não pode ser chamado???
Como eu faço?? :frowning:

hudsonpereira

vou dar uma olhada, já posto.

T

Obrigado pela ajuda, agradeço muito

T
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SimpleGui3C implements ActionListener{
JFrame frame;

public static void main(String[] args){
 SimpleGui3C gui = new SimpleGui3C();
 gui.go();
}

public void go(){
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Change color");
button.addActionListener(this);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.SOUTH, button);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);

frame.setSize(300,300);
frame.setVisible(true);

}

public void actionPerformed(ActionEvent event){
frame.repaint();
}


}
import java.awt.*;
import javax.swing.*;
class MyDrawPanel extends JPanel{
public void paintComponente(Graphics g){
g.fillRect(0,0,this.getWidth(), this.getHeight());

int red = (int)(Math.random()*255);
int green = (int)(Math.random()*255);
int blue = (int)(Math.random()*255);

Color randomColor = new Color(red, green, blue);
g.setColor(randomColor);
g.fillOval(70,70,100,100);

}

}

Aparentemente o codigo esta certo , mais quando eu clico no botao ele deveria desenhar o circulo , mas não desenha =///
o que pode ser ???

W

tioola, eu fiz quase todos os exemplos do livro Use a Cabeça Java e se não e engano, todos que fiz, funcionam. Como não estou com o livro agora, dou a dica de vc fazer os código com toda a atenção para ao compilar não dar erro. Isso é normal quando se está iniciando. Sempre que abrir um parênteses, aspas, chaves, etc, já feche imediatamente e construa o código entre eles, daí vc não corre o risco de esquecer de fechar algum. Se vc já faz isso, desconsidere.

Eu particularmente não gostei do método desse livro, embora muitos falem bem dele, eu acho que enrola muito e é não é objetivo, mas não deixa de ser um bom livro. É preciso paciência pra estudá-lo bem.

T

O grande problema, creio eu, é a tradução que peca muito , achei varios erros, não apenas de tradução mas também erros de sintaxe que não deveriam existir.
Acho que vou ter que pular essa parte pois ja li e reli milhões de vezes e não achei o problema.
Vou começar a ler a apostila fj-11 talvez seja melhor, pois infelizmente meu inglês ainda não é bom o suficiente para ler um livro tecnico completo :cry:

Paulo_Dias

no ultimo codigo que vc postou tem um “e” a mais no metodo paintComponent

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

public class SimpleGui3C implements ActionListener{
	JFrame frame;

	public static void main(String[] args){
		SimpleGui3C gui = new SimpleGui3C();
		gui.go();
	}

	public void go(){
		
		frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JButton button = new JButton("Change color");
		button.addActionListener( this );
		
		MyDrawPanel drawPanel = new MyDrawPanel();
		
		frame.getContentPane().add(BorderLayout.SOUTH, button);
		frame.getContentPane().add(BorderLayout.CENTER, drawPanel);

		frame.setSize( 300, 300 );
		frame.setVisible( true );
	}
	
	public void actionPerformed( ActionEvent e ) {
		
		frame.repaint();
	}
	

}

class MyDrawPanel extends JPanel{
	public void paintComponent (Graphics g){
		g.fillRect(0,0,this.getWidth(), this.getHeight());

		int red = (int)(Math.random()*255);
		int green = (int)(Math.random()*255);
		int blue = (int)(Math.random()*255);

		Color randomColor = new Color(red, green, blue);
		g.setColor(randomColor);
		g.fillOval(70,70,100,100);

	}
}
T


Como podemos observar , a tradução esta deixando muito a desejar :?
Em caso de pessoas leigas como eu pode acabar passando despercebido e acontecer isso.
Obrigado pela ajuda^^

Criado 18 de janeiro de 2011
Ultima resposta 20 de jan. de 2011
Respostas 10
Participantes 5