1ª Parte: |

Exemplo
| Arquivo: JavaGrafico.java |
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JavaGrafico extends JFrame {
public JavaGrafico() {
super("Formulario");
this.setSize(200,200);
this.setLocation(50, 100);
Container ct = this.getContentPane();
ct.setLayout(null);
Grafico g2D = new Grafico();
g2D.setBounds(0,0,400,400);
ct.add(g2D);
Image Icone = Toolkit.getDefaultToolkit().getImage("icon.gif");
setIconImage(Icone);
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}});
}
public static void main(String[] args) {
new JavaGrafico();
}
class Grafico extends JPanel {
public void paintComponent(Graphics g){
g.setColor(new Color(255, 0, 0));
g.drawRect(5, 10, 90, 50);
g.fillRect(100, 10, 90, 50);
}
}
} |
| Constante Color | Cor | Valor RGB |
| Color.orange | laranja | 255, 200, 0 |
| Color.pink | cor-de-rosa | 255, 175, 175 |
| Color.cyan | ciano | 0, 255, 255 |
| Color.magenta | magenta | 255, 0, 255 |
| Color.yellow | amarelo | 255, 255, 0 |
| Color.black | preto | 0, 0, 0 |
| Color.white | branco | 255, 255, 255 |
| Color.gray | cinza | 128, 128, 128 |
| Color.ligthGray | cinza-claro | 192, 192, 192 |
| Color.darkGray | cinza-escuro | 64, 64, 64 |
| Color.red | vermelho | 255, 0, 0 |
| Color.green | verde | 0, 255, 0 |
| Color.blue | azul | 0, 0, 255 |
| Exemplo: |
| g.setColor(Color.blue); g.drawRect(5, 10, 90, 50); g.fillRect(100, 10, 90, 50); |
![]() |
Color(int r, int g, int b) |
|
| setColor(Color c) | Configura a cor atual para desenho com o contexto gráfico |
| Exemplo: | |
| g.setColor(new Color(255, 175, 175)); g.drawRect(5, 10, 90, 50); g.fillRect(100, 10, 90, 50); |
|
![]() |
|
| Método | Descrição |
| getRed() | Devolve um valor entre 0 e 255 que representa conteúdo de vermelho |
| getGreen() | Devolve um valor entre 0 e 255 que representa conteúdo de verde |
| getBlue() | Devolve um valor entre 0 e 255 que representa conteúdo de azul |
| getColor() | Devolve o objeto Color que representa a cor atual para contexto gráfico. |
| Exemplo: | |
Color cor = new Color(78,127,25); |
|
![]() |
|

| Exemplo: |
| g.setColor(Color.blue); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.red); g.drawRect(5, 10, 90, 50); g.fillRect(100, 10, 90, 50); |
| Constante | Descrição |
| Font.PLAIN | Constante que representa um estilo de fonte simples |
| Font.BOLD | Constante que representa um estilo de fonte em negrito |
| Font.ITALIC | Constante que representa um estilo de fonte em itálico |
| Font.BOLD+Font.ITALIC | Constante que representa um estilo de fonte em negrito e itálico |
Font(String name, int style, int size) |
|
| setFont(Font f) | Configura a fonte atual com a fonte, o estilo e o tamanho especificados pela referência ao objeto Font f. |
| Exemplo: | |
g.setColor(Color.blue); |
|
![]() |
|
| Estilo da Fonte | |
| Método | Descrição |
| getFont() | Devolve uma referência do objeto Font que representa a fonte atual. |
| getFont().getStyle() | Devolve um valor inteiro que indica o estilo de fonte atual (Negrito e Itálico). |
| getFont().getSize() | Devolve um valor inteiro que indica o tamanho da fonte atual. |
| getFont().getName() | Devolve o nome da fonte atual como um string. |
| getFont().getFamily() | Devolve o nome da família de fontes como um string. |
| getFont().isPlain() | Verifica se o estilo da fonte é simples. Devolve true se a fonte for simples. |
| getFont().isBold() | Verifica se o estilo da fonte é negrito. Devolve true se a fonte estiver em negrito. |
| getFont().isItalic() | Verifica o estilo da fonte é itálico. Devolve true se a fonte estiver em itálico. |
| Medida da Fonte | |
![]() |
|
| Metodo | Descrição |
| FontMetrics metrics = g.getFontMetrics() | Devolve as mediadas da fonte usada. |
| String mensagem = "Testando Java 2D: Hello World (y-Ô)"; metrics.stringWidth(mensagem) |
Devolve um valor que representa a largura de uma fonte em pontos. |
| metrics.getHeight() | Devolve um valor que representa a altura de uma fonte em pontos. |
| metrics.getLeading() | Devolve um valor que representa em cima de uma fonte, em pontos. |
| metrics.getAscent() | Devolve um valor que representa o meio de uma fonte, em pontos. |
| metrics.getDescent() | Devolve um valor que representa em baixo de uma fonte, em pontos. |
| Exemplo: Arquivo: JavaGrafico.java |
|
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JavaGrafico extends JFrame {
private JButton botao;
String texto ="";
public JavaGrafico() {
super("Formulario");
this.setSize(200,200);
this.setLocation(50, 100);
Container ct = this.getContentPane();
ct.setLayout(null);
Grafico g2D = new Grafico();
g2D.setBounds(0,0,400,200);
ct.add(g2D);
botao = new JButton("Resultado");
botao.setBounds(0,50,150,25);
ct.add(botao);
Image Icone = Toolkit.getDefaultToolkit().getImage("icon.gif");
setIconImage(Icone);
this.setVisible(true);
botao.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, texto);
}});
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}});
}
public static void main(String[] args) {
new JavaGrafico();
}
class Grafico extends JPanel {
public void paintComponent(Graphics g){
g.setColor(Color.blue);
g.setFont(new Font("SansSerif",Font.BOLD+Font.ITALIC, 22));
String mensagem = "Testando Java 2D: Hello World (y-Ô)";
g.drawString(mensagem, 5, 25);
texto = "";
texto += g.getFont().getName()+"\n";
texto += g.getFont().getSize()+" pontos\n";
if(g.getFont().isBold()== true){
texto += "Negrito\n";
}
if(g.getFont().isItalic()== true){
texto += "Italico\n";
}
FontMetrics metrics = g.getFontMetrics();
texto += "Largura: "+metrics.stringWidth(mensagem)+"\n";
texto += "Altura: "+metrics.getHeight()+"\n";
texto += "[em cima]: "+metrics.getLeading()+"\n";
texto += "[do meio]: "+metrics.getAscent()+"\n";
texto += "[em baixo]: "+metrics.getDescent();
}
}
} |
|
![]() |
|

Se você quer obter a lista de fontes, use esse código:
| Arquivo: Estudos.java |
/*
Este exemplo mostra como obter a lista
de fontes disponíveis no sistema. Observe
que apenas os nomes das fontes são obtidas
com o método getAvailableFontFamilyNames. Outras
dicas contém códigos mais avançados em relação
ao uso de fontes em Java.
*/
import java.awt.*;
import javax.swing.*;
public class Estudos extends JFrame{
public Estudos(){
super("Lista de Fontes");
String[] fontNames; // nomes das fontes
Toolkit toolkit = Toolkit.getDefaultToolkit();
fontNames =
GraphicsEnvironment.getLocalGraphicsEnvironment().
getAvailableFontFamilyNames();
Container c = getContentPane();
FlowLayout layout = new FlowLayout(FlowLayout.LEFT);
c.setLayout(layout);
JTextArea textArea = new JTextArea(15, 40);
JScrollPane scrollPane = new JScrollPane(textArea);
c.add(scrollPane);
// adiciona os nomes das fontes ao JTextArea
for(int i = 0; i < fontNames.length; i++){
textArea.setText(textArea.getText() +
fontNames[i] + "\n");
}
setSize(500, 350);
setVisible(true);
}
public static void main(String args[]){
Estudos app = new Estudos();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
|

g.drawLine(int x1, int y1, int x2, int y2); |
| Exemplo: |
| g.setColor(new Color(78,127,25)); g.drawLine(5, 10, 95, 60); g.setColor(Color.blue); g.drawLine(10, 60, 95, 10); |

g.drawRect(int x, int y, int width, int height); |
| Exemplo: |
| g.setColor(new Color(78,127,25)); g.drawRect(5, 10, 90, 50); g.setColor(Color.blue); g.fillRect(100, 10, 90, 50); |

g.drawOval(int x, int y, int width, int height); Desenha uma elipse (linha) na cor atual com a width e a height específicadas. O canto superior esquerdo está nas coordenadas (x, y). Desenha uma elipse (sólido) na cor atual com a width e a height específicadas. O canto superior esquerdo está nas coordenadas (x, y). |
| Exemplo: |
| g.setColor(new Color(78,127,25)); g.drawOval(5, 10, 90, 50); g.setColor(Color.blue); g.fillOval(100, 10, 90, 50); |

| g.drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight); Desenha um retângulo com cantos arredondados (linha) na cor atual com a width e a height especificadas. A arcWidth e arc Height determinam o arredondamento dos cantos. g.fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight); Desenha um retângulo com cantos arredondados (sólido) na cor atual com a width e a height especificadas. A arcWidth e arcHeight determinam o arredondamento dos cantos. |
|
| Exemplo: |
| g.setColor(new Color(78,127,25)); g.drawRoundRect(5, 10, 90, 50, 40, 40); g.setColor(Color.blue); g.fillRoundRect(100, 10, 90, 50, 40, 40); |

Obs:
|
g.fillArc(int x, int y, int width, int height, inicio_do_angulo, int fim_do_angulo); |
| Exemplo: |
| g.setColor(new Color(78,127,25)); g.fillArc(10, 10, 100, 100, 0, 120); g.fillArc(120, 10, 100, 100, 360, -240); g.setColor(Color.blue); g.drawArc(10, 120, 100, 100, 0, 120); g.drawArc(120, 120, 100, 100, 360, -240); |

Polygon p1 = new Polygon(int xValor, int yValor, int número_de_pontos); |
| Exemplo: |
g.setColor(new Color(78,127,25)); Polygon p1 = new Polygon(xValor_1, yValor_1, 6); g.setColor(Color.blue); Polygon p2 = new Polygon(xValor_2, yValor_2, 6); |
| Ou: |
g.setColor(new Color(78,127,25)); g.setColor(Color.blue); |
| Ou: |
g.setColor(new Color(78,127,25)); g.drawPolygon(xValor_1, yValor_1, 6); g.setColor(Color.blue); g.fillPolygon(xValor_2, yValor_2, 6); |
| g.drawPolyline(int xValor, int yValor, int número_de_pontos); Desenha uma série de linhas conectadas. A linha tem número_de_pontos ao lado, com cada ponto consistindo em uma coordenada x de xValor e uma coordenada y de yValor. |
| Exemplo: |
g.setColor(new Color(78,127,25)); g.drawPolyline(xValor, yValor, 6); |

private Image img = null; |
| Exemplo: Arquivo: JavaGrafico.java |
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JavaGrafico extends JFrame {
private Image img = null;
public JavaGrafico() {
super("Formulario");
this.setSize(200,200);
this.setLocation(50, 100);
Container ct = this.getContentPane();
ct.setLayout(null);
Toolkit toolkit = getToolkit();
img = toolkit.createImage("coracao.gif");
Grafico g2D = new Grafico();
g2D.setBounds(0,0,400,400);
ct.add(g2D);
Image Icone = Toolkit.getDefaultToolkit().getImage("icon.gif");
setIconImage(Icone);
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}});
}
public static void main(String[] args) {
new JavaGrafico();
}
class Grafico extends JPanel {
public void paintComponent(Graphics g){
// Diminuindo a imagem
g.drawImage(img, 10, 10, img.getWidth(this)/2, img.getHeight(this)/2, this);
// Normal
g.drawImage(img, 100, 10, img.getWidth(this), img.getHeight(this), this);
// Aumentando a imagem
g.drawImage(img, 200, 10, img.getWidth(this)*2, img.getHeight(this)*2, this);
}
}
} |
2ª Parte: |

| Exemplo: |
import java.awt.geom.*; |

| Exemplo: |
| import java.awt.geom.*; . . . Graphics2D grp = (Graphics2D) g; grp.setPaint(new Color(78,127,25)); grp.draw(new Ellipse2D.Double(5, 10, 90, 50)); grp.setPaint(Color.blue); grp.fill(new Ellipse2D.Double(100, 10, 90, 50)); |

| Exemplo: |
| import java.awt.geom.*; . . . Graphics2D grp = (Graphics2D) g; grp.setPaint(new Color(78,127,25)); grp.draw(new RoundRectangle2D.Double(5, 10, 90, 50, 40, 40)); grp.setPaint(Color.blue); grp.fill(new RoundRectangle2D.Double(100, 10, 90, 50, 40, 40)); |

| Exemplo: |
import java.awt.geom.*; grp.setPaint(new Color(78,127,25)); grp.fill(new Arc2D.Double(10, 10, 100, 100, 0, 120, Arc2D.PIE)); grp.setPaint(Color.blue); grp.draw(new Arc2D.Double(10, 120, 100, 100, 0, 120, Arc2D.OPEN)); |
Arc2D.PIE
grp.setPaint(Color.blue); grp.draw(new Arc2D.Double(10, 10, 100, 100, 315, -90, Arc2D.PIE)); |
Arc2D.CHORD
grp.setPaint(Color.blue); grp.draw(new Arc2D.Double(10, 10, 100, 100, 315, -90, Arc2D.CHORD)); |
Arc2D.OPEN
grp.setPaint(Color.blue); grp.draw(new Arc2D.Double(10, 10, 100, 100, 315, -90,Arc2D.OPEN)); |

| Exemplo: |
| import java.awt.geom.*; . . . Graphics2D grp = (Graphics2D) g; grp.setPaint(new Color(78,127,25)); grp.draw(new Line2D.Double(5, 10, 95, 60)); grp.setPaint(Color.blue); grp.draw(new Line2D.Double(10, 60, 95, 10)); |

| Exemplo: |
import java.awt.geom.*; grp.setPaint(new Color(78,127,25)); int xValor_1[] = {5, 5, 47, 90, 90, 47}; GeneralPath p1 = new GeneralPath(); p1.moveTo(xValor_1[0], yValor_1[0]); for(int count = 1; count < xValor_1.length; count++){ p1.closePath(); grp.draw(p1); grp.setPaint(Color.blue); int xValor_2[] = {100, 100, 147, 190, 190, 147}; GeneralPath p2 = new GeneralPath(); p2.moveTo(xValor_2[0], yValor_2[0]); for(int count = 1; count < xValor_2.length; count++){ p2.closePath(); grp.fill(p2); |

| Exemplo: |
import java.awt.geom.*; grp.setPaint(new Color(78,127,25)); int xValor[] = {10, 40, 70, 100, 130, 160}; GeneralPath p1 = new GeneralPath(); p1.moveTo(xValor[0], yValor[0]); for(int count = 1; count < xValor.length; count++){ grp.draw(p1); |

pac-man
Em nosso Exemplo:

| Exemplo: |
import java.awt.geom.*; GeneralPath gp = new GeneralPath(); //linha lateral esquerda gp.quadTo(15, 95, 20, 80); //linha lateral direita // Cor azul // Transporte grp.draw(gp); // Transporte grp.fill(gp); |

| Arquivo: ShapedWindow.java |
import java.awt.*; import javax.swing.*; public class ShapedWindow extends JFrame { this.setSize(new Dimension(400, 400)); public static void main(String[] args) { // Ponto Inicial //linha lateral esquerda gp.quadTo(15, 95, 20, 80); //linha lateral direita //Topo com.sun.awt.AWTUtilities.setWindowShape(w, gp); } } |
Transformações geométricas |

| Exemplo: |
import java.awt.geom.*; grp.draw(new Rectangle2D.Double(5, 10, 90, 50)); grp.setStroke(new BasicStroke(10)); grp.draw(new Rectangle2D.Double(130, 10, 90, 50)); |

| Exemplo: |
import java.awt.geom.*; grp.setStroke(new BasicStroke(20, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER)); grp.draw(new Rectangle2D.Double(50, 50, 90, 50)); grp.setStroke(new BasicStroke(20, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND)); grp.draw(new Rectangle2D.Double(200, 50, 90, 50)); grp.setStroke(new BasicStroke(20, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); grp.draw(new Rectangle2D.Double(50, 150, 90, 50)); |
| Borda quadrada | Borda circular | Borda triangular |
BasicStroke.JOIN_MITER
grp.setPaint(Color.blue); grp.setStroke(new BasicStroke(20, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER)); grp.draw(new Rectangle2D.Double(50, 50, 90, 50)); |
BasicStroke.JOIN_ROUND
grp.setPaint(Color.blue); grp.setStroke(new BasicStroke(20, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND)); grp.draw(new Rectangle2D.Double(50, 50, 90, 50)); |
BasicStroke.JOIN_BEVEL
grp.setPaint(Color.blue); grp.setStroke(new BasicStroke(20, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); grp.draw(new Rectangle2D.Double(50, 50, 90, 50)); |

| Exemplo: |
| import java.awt.geom.*; . . . Graphics2D grp = (Graphics2D) g; grp.setPaint(new GradientPaint(5, 10, Color.blue, 65, 80, Color.yellow, true)); grp.fill(new Rectangle2D.Double(5, 10, 90, 50)); |

Exemplo: |
import java.awt.geom.*; BufferedImage buffImage = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB); grp.setPaint(new TexturePaint(buffImage, new Rectangle(10, 10))); grp.fill(new Ellipse2D.Double(5, 10, 90, 50)); |

| Exemplo: |
import java.awt.geom.*; grp.setPaint(Color.blue); grp.translate(25, 25); grp.fill(new Rectangle2D.Double(0, 0, 50, 50)); |

| Exemplo: |
import java.awt.geom.*; grp.setPaint(Color.blue); grp.translate(50, 0); // Rotação de 45º grp.fill(new Rectangle2D.Double(0, 0, 50, 50)); |

| Exemplo: |
import java.awt.geom.*; float linha[] = {10, 20}; grp.setPaint(Color.blue); |
BasicStroke.CAP_BUTT
|
BasicStroke.CAP_ROUND
|
BasicStroke.CAP_SQUARE
|
| CAP_BUTT extremidade nenhuma. Por padrão é quadrada. |
CAP_ROUND extremidade circular. | CAP_SQUARE extremidade quadrada. |

| Exemplo: |
Graphics2D grp = (Graphics2D) g; float linha[] = {10, 20}; grp.setPaint(Color.blue); |

| Arquivo: JavaGrafico.java |
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;
public class JavaGrafico extends JFrame {
private Image img = null;
public JavaGrafico() {
super("Formulario");
this.setSize(200,200);
this.setLocation(50, 100);
Container ct = this.getContentPane();
ct.setLayout(null);
Toolkit toolkit = getToolkit();
img = toolkit.createImage("coracao.gif");
Grafico g2D = new Grafico();
g2D.setBounds(0,0,400,400);
ct.add(g2D);
Image Icone = Toolkit.getDefaultToolkit().getImage("icon.gif");
setIconImage(Icone);
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}});
}
public static void main(String[] args) {
new JavaGrafico();
}
class Grafico extends JPanel {
public void paintComponent(Graphics g){
Graphics2D grp = (Graphics2D) g;
int largura = img.getWidth(this);
int altura = img.getHeight(this);
try {
BufferedImage buffImage = new BufferedImage(largura, altura, BufferedImage.TYPE_INT_RGB);
Graphics2D gg = buffImage.createGraphics();
gg.drawImage(img, 0, 0, largura, altura, this);
grp.setPaint(new TexturePaint(buffImage, new Rectangle(largura, altura)));
} catch(Exception rem){ /*erro removido e apagado*/ }
grp.translate(100, 50);
grp.rotate(Math.PI/1.5);
grp.fill(new Rectangle2D.Double(0, 0, largura, altura));
}
}
} |
Criando animações com imagens |
| T1.gif | T2.gif | T3.gif | T4.gif | T5.gif |
| T6.gif | T7.gif | T8.gif | T9.gif | T10.gif |
| T11.gif | T12.gif | T13.gif | T14.gif | T15.gif |
| T16.gif | T17.gif |
| Arquivo: JavaGrafico.java |
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.lang.*;
public class JavaGrafico extends JFrame {
private Image img[];
private int tempoEspera = 150;
private int numImg = 17;
private int imgAtual;
public JavaGrafico() {
super("Formulario");
this.setSize(200,200);
this.setLocation(50, 100);
Container ct = this.getContentPane();
ct.setLayout(null);
img = new Image[numImg];
Toolkit t = getToolkit();
for(int i = 1; i <= numImg; i++){
try {
img[i] = t.createImage("duke\\T"+i+".gif");
} catch (ArrayIndexOutOfBoundsException erro) {/* Erro desapareceu */}
}
imgAtual = 0;
Grafico g2D = new Grafico();
g2D.setBounds(0,0,400,400);
ct.add(g2D);
Image Icone = Toolkit.getDefaultToolkit().getImage("icon.gif");
setIconImage(Icone);
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}});
}
public static void main(String[] args) {
new JavaGrafico();
}
class Grafico extends JPanel {
public void paintComponent(Graphics g){
g.drawImage(img[imgAtual], 10, 10, this);
imgAtual = (imgAtual + 1) % numImg;
try {
Thread.sleep(tempoEspera);
} catch (InterruptedException e) {
e.printStackTrace();
}
repaint();
}
}
} |
Eventos |
| Arquivo: JavaGrafico.java |
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class JavaGrafico extends JFrame {
public JavaGrafico() {
super("Formulario");
this.setSize(200,200);
this.setLocation(50, 100);
Container ct = this.getContentPane();
ct.setLayout(null);
PaintPanel g2D = new PaintPanel();
g2D.setBounds(0,0,400,400);
ct.add(g2D);
Image Icone = Toolkit.getDefaultToolkit().getImage("icon.gif");
setIconImage(Icone);
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}});
}
public static void main(String[] args) {
new JavaGrafico();
}
class Grafico extends JPanel {
public void paintComponent(Graphics g){
Graphics2D grp = (Graphics2D) g;
float linha[] = {10, 20};
grp.setPaint(Color.blue);
grp.setStroke( new BasicStroke(4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 10, linha, 0));
grp.draw(new Ellipse2D.Double(5, 5, 100, 100));
}
}
} |
| Arquivo: PaintPanel.java |
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PaintPanel extends JPanel {
private int pointCount = 0; // número de contagem de pontos
// array de 10000 referências java.awt.Point
private Point points[] = new Point[ 10000 ];
private String mouse[] = new String[10000];
private String mensagem = "Testando";
// configura a GUI e registra handler de evento de mouse
public PaintPanel() {
this.setFocusable(true);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent tecla) {
char caracter = tecla.getKeyChar();
int codigo = tecla.getKeyCode();
if(codigo == KeyEvent.VK_BACK_SPACE) {
if(!mensagem.equals("")){
mensagem = mensagem.substring(0, mensagem.length()-1);
}
} else if(codigo != KeyEvent.VK_BACK_SPACE) {
mensagem += ""+caracter;
}
repaint();
}});
addMouseMotionListener( new MouseMotionAdapter(){
public void mouseDragged( MouseEvent event ){
if (event.isMetaDown()){
if ( pointCount < points.length ){
points[ pointCount ] = event.getPoint(); // localiza o ponto
mouse[pointCount]="vermelho";
pointCount++; // incrementa número de pontos em array
repaint(); // repinta JFrame
}//fim if interno
}else{
if ( pointCount < points.length ){
points[ pointCount ] = event.getPoint(); // localiza o ponto
mouse[pointCount]="azul";
pointCount++; // incrementa número de pontos em array
repaint(); // repinta JFrame
}//fim if interno
}//fim do if else
}});
} // fim do construtor PaintPanel
public void paintComponent( Graphics g ){
super.paintComponent( g );
g.setColor(Color.blue);
g.setFont(new Font("Arial",Font.PLAIN, 22));
g.drawString(mensagem, 5, 25);
for ( int i = 0; i < pointCount; i++ ){
if (mouse[i] == "azul"){
g.setColor(Color.BLUE);
}else if(mouse[i] == "vermelho"){
g.setColor(Color.red);
}
g.fillOval( points[ i ].x, points[ i ].y, 4, 4 );
}
}
} |
Eventos |
| Arquivo: JavaGrafico.java (Obs: Applet) |
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class JavaGrafico extends JApplet {
public Ellipse2D ellipse;
private Grafico g2D;
boolean cor = false;
public void init() {
Container ct = this.getContentPane();
ct.setLayout(null);
g2D = new Grafico();
g2D.setBounds(0,0,150,150);
ct.add(g2D);
}
class Grafico extends JPanel {
public Grafico(){
addMouseListener( new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
if (ellipse.contains(e.getX(), e.getY())) {
if (cor == false){
cor = true;
} else if(cor == true){
cor = false;
}
repaint();
}
}});
}
public void paintComponent(Graphics g){
Graphics2D grp = (Graphics2D) g;
if (cor == false){
grp.setPaint(Color.blue);
} else if(cor == true){
grp.setPaint(new Color(78,127,25));
}
ellipse = new Ellipse2D.Double(25, 25, 100, 100);
grp.fill(ellipse);
}
}
} |
| Arquivo: JavaGrafico.java (Obs: Applet) |
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class JavaGrafico extends JApplet {
public Ellipse2D ellipse;
private Grafico g2D;
boolean cor = false;
public void init() {
Container ct = this.getContentPane();
ct.setLayout(null);
g2D = new Grafico();
g2D.setBounds(0,0,150,150);
ct.add(g2D);
}
class Grafico extends JPanel {
public Grafico(){
addMouseListener( new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
if(e.getClickCount() == 2) {
// Duplo-clique detectado
if (ellipse.contains(e.getX(), e.getY())) {
if (cor == false){
cor = true;
} else if(cor == true){
cor = false;
}
} else {
// Clique simples detectado.
}
repaint();
}
}});
}
public void paintComponent(Graphics g){
Graphics2D grp = (Graphics2D) g;
if (cor == false){
grp.setPaint(Color.blue);
} else if(cor == true){
grp.setPaint(new Color(78,127,25));
}
ellipse = new Ellipse2D.Double(25, 25, 100, 100);
grp.fill(ellipse);
}
}
} |
| Arquivo: javaGrafico.java (Obs: Applet) |
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class JavaGrafico extends JApplet {
public Ellipse2D ellipse;
private Grafico g2D;
boolean cor = false;
public void init() {
Container ct = this.getContentPane();
ct.setLayout(null);
g2D = new Grafico();
g2D.setBounds(0,0,150,150);
ct.add(g2D);
}
class Grafico extends JPanel {
public Grafico(){
addMouseMotionListener( new MouseMotionAdapter(){
public void mouseMoved(MouseEvent e) {
if (ellipse.contains(e.getX(), e.getY())) {
cor = true;
}else {
cor = false;
}
repaint();
}});
}
public void paintComponent(Graphics g){
Graphics2D grp = (Graphics2D) g;
if (cor == false){
grp.setPaint(Color.blue);
} else if(cor == true){
grp.setPaint(new Color(78,127,25));
}
ellipse = new Ellipse2D.Double(25, 25, 100, 100);
grp.fill(ellipse);
}
}
} |
| Arquivo: JavaGrafico.java (Obs: Applet) |
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class JavaGrafico extends JApplet {
public Ellipse2D ellipse;
private Grafico g2D;
boolean cor = false;
boolean valor = true;
public void init() {
Container ct = this.getContentPane();
ct.setLayout(null);
g2D = new Grafico();
g2D.setBounds(0,0,150,150);
ct.add(g2D);
}
class Grafico extends JPanel {
public Grafico(){
addMouseListener( new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
if (ellipse.contains(e.getX(), e.getY())) {
if (e.isMetaDown()){
cor = true;
} else{
cor = false;
}
valor = false;
repaint();
}
}});
}
public void paintComponent(Graphics g){
Graphics2D grp = (Graphics2D) g;
if (cor == false){
grp.setPaint(Color.blue);
} else if(cor == true){
grp.setPaint(new Color(78,127,25));
}
if (valor == true){
grp.setPaint(Color.red);
}
ellipse = new Ellipse2D.Double(25, 25, 100, 100);
grp.fill(ellipse);
}
}
} |
| Arquivo: JavaGrafico.java (Obs: Applet) |
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class JavaGrafico extends JApplet {
public Ellipse2D ellipse;
private Grafico g2D;
private String mensagem1 = "";
private String mensagem2 = "";
int x = 0;
int y = 0;
public void init() {
Container ct = this.getContentPane();
ct.setLayout(null);
g2D = new Grafico();
g2D.setBounds(0,0,150,150);
ct.add(g2D);
g2D.setFocusable(true);
}
class Grafico extends JPanel {
public Grafico(){
addMouseListener( new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
if(e.getButton() == 1){
mensagem2 = "Botão Esquerdo";
} else if(e.getButton() == 2){
mensagem2 = "Botão Central";
} else if(e.getButton() == 3){
mensagem2 = "Botão Direito";
}
repaint();
}});
addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
y = e.getWheelRotation();
x = x + y;
if (y < 0) {
mensagem1 = "Para cima... " + y + " valor = " + x;
} else if(y > 0) {
mensagem1 = "Para baixo... " + y + " valor = " + x;
}
repaint();
}});
}
public void paintComponent(Graphics g){
super.paintComponent( g );
g.setColor(Color.blue);
g.setFont(new Font("Arial",Font.PLAIN, 12));
g.drawString("Mouse Wheel", 5, 25);
g.drawString(mensagem1, 5, 50);
g.drawString(mensagem2, 5, 75);
}
}
} |
| Arquivo: JavaGrafico.java (Obs: Applet) |
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class JavaGrafico extends JApplet {
public Ellipse2D ellipse;
private Grafico g2D;
private String mensagem = "A";
public void init() {
Container ct = this.getContentPane();
ct.setLayout(null);
g2D = new Grafico();
g2D.setBounds(0,0,150,150);
ct.add(g2D);
g2D.setFocusable(true);
}
class Grafico extends JPanel {
public Grafico(){
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent tecla) {
mensagem = "" + tecla.getKeyChar();
repaint();
}});
}
public void paintComponent(Graphics g){
super.paintComponent( g );
g.setColor(Color.blue);
g.setFont(new Font("Arial",Font.PLAIN, 22));
g.drawString(mensagem, 5, 25);
}
}
} |
| Arquivo: JavaGrafico.java (Obs: Applet) |
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class JavaGrafico extends JApplet {
public Ellipse2D ellipse;
private Grafico g2D;
boolean cor = false;
public void init() {
Container ct = this.getContentPane();
ct.setLayout(null);
g2D = new Grafico();
g2D.setBounds(0,0,150,150);
ct.add(g2D);
g2D.addMouseListener(new testandoMouse());
}
class Grafico extends JPanel {
public Grafico(){
}
public void paintComponent(Graphics g){
Graphics2D grp = (Graphics2D) g;
if (cor == false){
grp.setPaint(Color.blue);
} else if(cor == true){
grp.setPaint(new Color(78,127,25));
}
ellipse = new Ellipse2D.Double(25, 25, 100, 100);
grp.fill(ellipse);
}
}
class testandoMouse extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if (ellipse.contains(e.getX(), e.getY())) {
if (cor == false){
cor = true;
} else if(cor == true){
cor = false;
}
repaint();
}
}
}
} |
Salvado a imagem do gráfico |
Exemplo:

Resultado:

| Arquivo: JavaGrafico.java |
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.*;
public class JavaGrafico extends JFrame {
public JavaGrafico() {
super("Formulario");
this.setSize(200,200);
this.setLocation(50, 100);
Container ct = this.getContentPane();
ct.setLayout(null);
Grafico g2D = new Grafico();
g2D.setBounds(0,0,100,60);
ct.add(g2D);
try {
BufferedImage dest = new BufferedImage(g2D.getWidth(), g2D.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = dest.createGraphics();
g2D.paintComponent(graphics);
graphics.dispose();
// png, gif ou jpg:
ImageIO.write(dest, "png", new File("teste.png"));
} catch (Exception e) {
e.printStackTrace();
}
Image Icone = Toolkit.getDefaultToolkit().getImage("icon.gif");
setIconImage(Icone);
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}});
}
public static void main(String[] args) {
new JavaGrafico();
}
class Grafico extends JPanel {
public void paintComponent(Graphics g){
Graphics2D grp = (Graphics2D) g;
BufferedImage buffImage = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB);
Graphics2D gg = buffImage.createGraphics();
gg.setColor(Color.yellow);
gg.fillRect(0, 0, 10, 10);
gg.setColor(Color.black);
gg.drawRect(1, 1, 6, 6);
gg.setColor(Color.blue);
gg.fillRect(1, 1, 3, 3);
gg.setColor(Color.red);
gg.fillRect(4, 4, 3, 3);
grp.setPaint(new TexturePaint(buffImage, new Rectangle(10, 10)));
grp.fill(new Ellipse2D.Double(5, 5, 90, 50));
}
}
} |

| Arquivo: JavaGrafico.java |
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;
public class JavaGrafico extends JFrame {
private Image img = null;
private JButton botao;
private Grafico g2D;
int teste = 0;
public JavaGrafico() {
super("Formulario");
this.setSize(200,200);
this.setLocation(50, 100);
Container ct = this.getContentPane();
ct.setLayout(null);
Toolkit toolkit = getToolkit();
img = toolkit.createImage("coracao.gif");
g2D = new Grafico();
g2D.setBounds(0,0,400,400);
ct.add(g2D);
botao = new JButton("tonalidade");
botao.setBounds(0,100,100,25);
ct.add(botao);
Image Icone = Toolkit.getDefaultToolkit().getImage("icon.gif");
setIconImage(Icone);
this.setVisible(true);
botao.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
g2D.repaint();
}});
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}});
}
public static void main(String[] args) {
new JavaGrafico();
}
class Grafico extends JPanel {
public void paintComponent(Graphics g){
Graphics2D grp = (Graphics2D) g;
int largura = img.getWidth(this);
int altura = img.getHeight(this);
int lay = 0;
if (teste == 0){
lay = BufferedImage.TYPE_INT_ARGB;
teste = 1;
}else if (teste == 1){
lay = BufferedImage.TYPE_INT_RGB;
teste = 2;
}else if (teste == 2){
lay = BufferedImage.TYPE_BYTE_GRAY;
teste = 3;
}else if (teste == 3){
lay = BufferedImage.TYPE_BYTE_BINARY;
teste = 0;
}
try {
BufferedImage buffImage = new BufferedImage(largura, altura, lay);
Graphics2D gg = buffImage.createGraphics();
gg.drawImage(img, 0, 0, largura, altura, this);
grp.setPaint(new TexturePaint(buffImage, new Rectangle(largura, altura)));
} catch(Exception rem){ /*erro removido e apagado*/ }
grp.fill(new Rectangle2D.Double(0, 0, largura, altura));
}
}
} |
| import java.awt.Robot; . . public Color getPixelColor(int x, int y) |