Chamar método ao pressionar botão

2 respostas
L

Prezados, tive que fazer um trabalho que recebe o raio e o centro e desenha uma circunferência através do calculo de octantes(http://groups.csail.mit.edu/graphics/classes/6.837/F98/Lecture6/circle.html)
Então, fiz um JFrame com dois Jtextfields para capturar essas informações e efetuar os cálculos, mais um botão que ao ser clicado, chama o método que desenha o circulo. Desculpe, não sou uma programadora experiente, me bato em coisinhas simples, e minhas dúvidas são, vai funcionar os componentes do swing mais a impressão do desenho no Jframe juntos?
O botao deve chamar o metodo calculos, porém estou em dúvida se ele irá executar o outro método desenhaCirculo.
Me ajudem por gentileza, ja foram varias noites sem dormir e um feriado neste trabalho…

package cg;

import java.awt.<em>;

import javax.swing.</em>;

import java.awt.Color;

import java.awt.Component;

import java.awt.Graphics;

public class DesenhaCirculo extends JFrame{

public class Tela extends JFrame {
	private static final int WINDOW_WIDTH  = 400;
    private static final int WINDOW_HEIGHT = 400;
	private JLabel lcentro,lraio;
    private JTextField tcentro,traio;
    private JButton desenha;
    int raio;
    int centro;
    int xc;
    int yc;
    int i;
    int j;
    public Tela() {
        setTitle("Círculos");
 
        lcentro = new JLabel("Digite o centro:");
        lraio = new JLabel("Digite o raio:");
        tcentro = new JTextField();
        traio = new JTextField();
        desenha = new JButton("Gerar Círculo");
        
        JPanel painel = new JPanel();
        painel.setLayout(new GridLayout(10, 5, 5, 5));
        
        painel.add(lcentro);
        painel.add(tcentro);
        painel.add(lraio);
        painel.add(traio);
        painel.add(desenha);
        
        setContentPane(painel);
        
        pack();
        desenha.addActionListener(this);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    
    @Override
    public void actionPerformed(ActionEvent ev) {
     
    	 raio  = Integer.parseInt(traio.getText());
    	 centro  = Integer.parseInt(tcentro.getText());
    	 
    }
    
    
    @Override public void paint(Graphics g) {
        super.paint(g);
    }
    
    void inserePonto(Graphics g, int x, int y)
    
    {
    	g.drawLine(xc, yc, x, y);
    
    }    
    
  public  void calculos (Graphics g, int xc,int yc,int radius){
        radius=raio;
        xc=centro;
        yc=centro;
        int p = 1 - radius;
        int y = radius;

       for (int x = 0;x <= y;x++) {
       desenhaCirculo (g, xc,  yc,  x,  y);
        if (p < 0)
        p += 2 * x + 1;
        else {
        y--;
        p += 2 * (x - y) + 1;
        }
        }
        }
  

  void desenhaCirculo(Graphics g, int xc, int yc, int x, int y){
	  inserePonto (g, xc + x, yc + y);
	  inserePonto (g, xc - x, yc + y);
	  inserePonto (g,xc + x, yc - y);
	  inserePonto (g,xc - x, yc - y);
	  inserePonto (g,xc + y, yc + x);
	  inserePonto (g,xc - y, yc + x);
	  inserePonto (g,xc + y, yc - x);
	  inserePonto (g,xc - y, yc - x);
	  } 
        
    	} 
}

2 Respostas

wldomiciano

Olá! Sou eu de novo.

Mexer com Swing é bem chatinho, mas acho que consegui algo funcional.

Não consegui fazer seu código funcionar, mas peguei os métodos da página que vc linkou. Tive que modificá-los um pouco. O método setPixel do raster tive que trocar por setRGB do BufferedImage.

Sei que não é legal colocar código pronto aqui no fórum, mas como o assunto me interessou desde o inicio e eu já tinha começado com isso, quis ir até o final. Prometo que é a última vez!

Mesmo que o algoritmo usado não seja o seu, o código abaixo pelo menos serve pra mostrar uma das possiveis formas de fazer seu JPanel atualizar ao clique de um botão.

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

public class App extends JFrame {
    private JPanel inputPanel    = new JPanel();
    private MyPanel circlePanel  = new MyPanel();
    private JButton drawButton   = new JButton("Draw!");
    private JButton clearButton  = new JButton("Clear!");
    private JLabel xLabel        = new JLabel("X");
    private JLabel yLabel        = new JLabel("Y");
    private JLabel raioLabel     = new JLabel("Raio");
    private JTextField xInput    = new JTextField(4);
    private JTextField yInput    = new JTextField(4);
    private JTextField raioInput = new JTextField(4);
    private boolean toDraw       = false;

    private BufferedImage raster;
    private int x, y, raio;

    class MyPanel extends JPanel {
        public void draw() {
            super.paint(getGraphics());
            if (toDraw) circleMidpoint(x, y, raio, Color.BLUE);
            getGraphics().drawImage(raster, 0, 0, null);
        }

        public void clear() {
            super.paint(getGraphics());
            raster = new BufferedImage(circlePanel.getWidth(), circlePanel.getHeight(), BufferedImage.TYPE_INT_RGB);
        }

        private final void circlePoints(int cx, int cy, int x, int y, int pix) {
            int act = Color.red.getRGB();

            if (x == 0) {
                raster.setRGB(cx, cy + y, act);
                raster.setRGB(cx, cy - y, pix);
                raster.setRGB(cx + y, cy, pix);
                raster.setRGB(cx - y, cy, pix);
            } else
            if (x == y) {
                raster.setRGB(cx + x, cy + y, act);
                raster.setRGB(cx - x, cy + y, pix);
                raster.setRGB(cx + x, cy - y, pix);
                raster.setRGB(cx - x, cy - y, pix);
            } else
            if (x < y) {
                raster.setRGB(cx + x, cy + y, act);
                raster.setRGB(cx - x, cy + y, pix);
                raster.setRGB(cx + x, cy - y, pix);
                raster.setRGB(cx - x, cy - y, pix);
                raster.setRGB(cx + y, cy + x, pix);
                raster.setRGB(cx - y, cy + x, pix);
                raster.setRGB(cx + y, cy - x, pix);
                raster.setRGB(cx - y, cy - x, pix);
            }
        }

        private void circleMidpoint(int xCenter, int yCenter, int radius, Color c) {
            int pix = c.getRGB();
            int x = 0;
            int y = radius;
            int p = (5 - radius*4)/4;

            circlePoints(xCenter, yCenter, x, y, pix);
            while (x < y) {
                x++;
                if (p < 0) {
                    p += 2*x+1;
                } else {
                    y--;
                    p += 2*(x-y)+1;
                }
                circlePoints(xCenter, yCenter, x, y, pix);
            }
        }
    }

    public App() {
        drawButton.addActionListener(listener -> {
            try {
                x    = Integer.parseInt( xInput.getText() );
                y    = Integer.parseInt( yInput.getText() );
                raio = Integer.parseInt( raioInput.getText() );
                toDraw = true;
                circlePanel.draw();
            } catch (Exception e) {}
        });

        clearButton.addActionListener(listener -> {
            circlePanel.clear();
        });

        inputPanel.setSize(400, 50);
        inputPanel.setBackground(Color.LIGHT_GRAY);
        inputPanel.add(xLabel);
        inputPanel.add(xInput);
        inputPanel.add(yLabel);
        inputPanel.add(yInput);
        inputPanel.add(raioLabel);
        inputPanel.add(raioInput);
        inputPanel.add(drawButton);
        inputPanel.add(clearButton);

        circlePanel.setSize(400, 400);
        circlePanel.setLocation(0, inputPanel.getHeight());
        circlePanel.setBackground(Color.BLACK);

        raster = new BufferedImage(circlePanel.getWidth(), circlePanel.getHeight(), BufferedImage.TYPE_INT_RGB);

        add(inputPanel);
        add(circlePanel);
        setSize(400,inputPanel.getHeight() + circlePanel.getHeight());
        setLayout(null);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) { new App(); }
}

Bons estudos!

L

Muito obrigada Wellington, me ajudou muito, parabéns por compartilhar seu conhecimento!
Prometo que não irei usar seu código no trabalho, vou me inspirar nele!

Abração!

Criado 18 de abril de 2017
Ultima resposta 18 de abr. de 2017
Respostas 2
Participantes 2