Chamar método em botão no JFrame:

2 respostas
felipehts

Fala pessoal!
Minha dúvida é a seguinte; estou desenvolvendo um aplicativo para calcular derivadas e jogar os valores no gráfico, estou utilizando um java class (codigo abaixo) e um Jframe principal onde crio os botões e etc, atrases do Netbeans, estou colocando o codigo abaixo em um Jpanel dentro do Jframe, ou seja alterei o codigo do JPanel, para new Grafico, enfim criei um botão dentro do Jframe para chamar os metodos do codigo abaixo, da seguinte forma:

private void BotaoTestActionPerformed(java.awt.event.ActionEvent evt) {
Grafico f = new Grafico();

f.LerFuncao();
                f.TamMatriz();
                f.Agrupa();
                f.Ordena();

Porém quando o grafico não traça novamente as retas, tipo queria que cada vez que desse um clique no botão, novamente chamar o codigo abaixo, para um nova função e por fim traçar nova reta, não está acontecendo isso…
Creio que seja por casa desse metodo:
desenhaPlano(Graphics g)
que não estou chamando no botão…então gostaria de saber como chamar esse metodo: “desenhaPlano(Graphics g)”,dentro do botão… agradeço.

import java.awt.Color;
import java.awt.Graphics;
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;

/**
 *
 * @author Pedro e Felipe
 */



public class Grafico extends JPanel {

    public static JTextArea areaTexto;
    public static int continuar = JOptionPane.YES_OPTION;
    public static String Str1 = "";
    public static DecimalFormat formata = new DecimalFormat("0.00");
    public static String funcao, deriva = "", integra = ""; //[?]
    public static double mat[][];
    public static boolean maior = false, menor = false, maiormenor = true;
    public static boolean desenha = true;
    public static boolean limpar = true;

    
    public static void LerFuncao() {
        String x;
        x = JOptionPane.showInputDialog("Digite a função: ");
        funcao = x.replaceAll(",", ".");

        if (x.charAt(0) != '-' && x.charAt(0) != '+') {
            funcao = '+' + funcao;

        }
    }

    public static void TamMatriz() {
        int i, tam, l, c;
        i = tam = l = c = 0;

        while (i < funcao.length()) {
            if (funcao.charAt(i) == '-' || funcao.charAt(i) == '+') {
                tam++;
            }
            i++;
        }

        mat = new double[2][tam + 1];

        for (l = 0; l < 2; l++) {
            for (c = 0; c < mat[0].length; c++) {
                mat[l][c] = 0;
            }
        }

    }

    public static void Agrupa() {
        int i, inicio, fim, iniexp, fimexp, c;
        String aux = "";
        double num = 0, exp = 0;

        i = inicio = fim = iniexp = fimexp = c = 0;


        while (i < funcao.length()) {

            if ((i < funcao.length()) && (funcao.charAt(i) == '-')) {
                i++;
                if ((i < funcao.length()) && (funcao.charAt(i) > 46 && funcao.charAt(i) < 58)) {
                    inicio = i;
                    while ((i < funcao.length()) && ((funcao.charAt(i) > 46 && funcao.charAt(i) < 58) || (funcao.charAt(i) == '.'))) {
                        i++;
                    }
                    fim = i;

                    aux = "-" + funcao.substring(inicio, fim);
                    num = Double.parseDouble(aux);

                } else {
                    num = -1.0;
                }
                if ((i < funcao.length()) && funcao.charAt(i) == 'x') {
                    exp = 1.0;
                    i++;

                    if ((i < funcao.length()) && funcao.charAt(i) == '^') {
                        i++;
                        iniexp = i;

                        while ((i < funcao.length()) && (funcao.charAt(i) > 46 && funcao.charAt(i) < 58)) {
                            i++;
                        }
                        fimexp = i;
                        aux = funcao.substring(iniexp, fimexp);
                        exp = Double.parseDouble(aux);
                    }
                }
            } else if ((i < funcao.length()) && (funcao.charAt(i) == '+')) {
                i++;
                if ((i < funcao.length()) && (funcao.charAt(i) > 46 && funcao.charAt(i) < 58)) {
                    inicio = i;
                    while ((i < funcao.length()) && ((funcao.charAt(i) > 46 && funcao.charAt(i) < 58) || (funcao.charAt(i) == '.'))) {
                        i++;
                    }
                    fim = i;

                    aux = funcao.substring(inicio, fim);
                    num = Double.parseDouble(aux);

                } else {
                    num = 1.0;
                }
                if ((i < funcao.length()) && funcao.charAt(i) == 'x') {
                    exp = 1.0;
                    i++;

                    if ((i < funcao.length()) && funcao.charAt(i) == '^') {
                        i++;
                        iniexp = i;

                        while ((i < funcao.length()) && (funcao.charAt(i) > 46 && funcao.charAt(i) < 58)) {
                            i++;
                        }
                        fimexp = i;
                        aux = funcao.substring(iniexp, fimexp);
                        exp = Double.parseDouble(aux);
                    }
                }
            }


            if (exp == 0) {
                mat[1][0] += num;
            } else {
                for (c = 1; c <= mat[0].length; c++) {
                    if (mat[0][c] == exp) {
                        mat[1][c] += num;
                        c = mat[0].length;
                    } else if (mat[0][c] == 0) {
                        mat[0][c] = exp;
                        mat[1][c] = num;
                        c = mat[0].length;
                    }

                }
            }

            inicio = fim = iniexp = fimexp = c = 0;
            num = exp = 0;
        }

    }

    public static void Ordena() {
        int c, i;
        double exp, num;
        for (i = 1; i < mat[0].length; i++) {
            for (c = 1; c < mat[0].length; c++) {
                if (mat[0][i] < mat[0][c]) {
                    exp = mat[0][i];
                    num = mat[1][i];
                    mat[0][i] = mat[0][c];
                    mat[1][i] = mat[1][c];
                    mat[0][c] = exp;
                    mat[1][c] = num;
                    c = 0;
                }
            }
        }
    }

    public static void LimpaVariavel() {

        funcao = "";
        deriva = "";
        integra = "";

        if (mat != null) {
            for (int l = 0; l < mat[0].length - 1; l++) {
                for (int c = 1; c < mat[0].length - 1; c++) {
                    mat[l][c] = 0;
                }
            }
        }


    }

    public static double GeraY(double funcional) {
        double aux = 0;
        double y = 0;
        for (int i = 1; i < mat[0].length; i++) {
            if (i != 0) {
                aux = Math.pow(funcional, mat[0][i]);
                y += aux * mat[1][i];
            }

        }
        y += mat[1][0];
        return y;

    }

    public static double GeraY2(double funcional, double matriz1[][], double matriz2[][]) {
        double aux1 = 0, aux2 = 0;
        double y1 = 0, y2 = 0;


        for (int i = 1; i < matriz1[0].length; i++) {
            if (i != 0) {
                aux1 = Math.pow(funcional, matriz1[0][i]);
                y1 += aux1 * matriz1[1][i];
            }

        }
        y1 += matriz1[1][0];


        for (int i = 1; i < matriz2[0].length; i++) {
            if (i != 0) {
                aux2 = Math.pow(funcional, matriz2[0][i]);
                y2 += aux2 * matriz2[1][i];
            }

        }
        y2 += matriz2[1][0];

        if (maiormenor) {
            if (y1 > y2) {
                maior = true;
            } else {
                menor = true;
            }
            maiormenor = false;
        }
        if (maior) {
            if (y1 < y2) {
                maiormenor = true;
                maior = false;
                return y1;
            } else {
                return 6000;
            }
        } else if (menor) {
            if (y1 > y2) {
                maiormenor = true;
                menor = false;
                return y1;
            } else {
                return 6000;
            }
        }
        return 6000;

    }

    public static double GeraY3(double funcional, double matriz[][]) {
        double aux = 0;
        double y = 0;
        for (int i = 1; i < matriz[0].length; i++) {
            if (i != 0) {
                aux = Math.pow(funcional, matriz[0][i]);
                y += aux * matriz[1][i];
            }

        }
        y += matriz[1][0];
        return y;

    }








         public void paint ( Graphics g ){

     	super.paint ( g );

     	Graphics g2d = (Graphics) g.create();
     	desenhaPlano(g);

     }

     public void desenhaPlano(Graphics g){


        if (limpar == true) {
            g.setColor(Color.white);
            g.fillRect(0, 0, 302, 482);
//				Desenha o quadro onde ser�o colocados os eixos cartesianos
            g.setColor(Color.white);
            g.fillRect(0, 0, 302, 482);



//				Tra�a os eixos cartesianos
            g.setColor(Color.black);
            g.drawLine(0, 240, 300, 240); // eixo X
            g.drawLine(150, 0, 150, 480); // eixo Y


//				Tra�a as coordenadas do eixo x
            int cont = -10;
            for (int i = 0; i <= 300; i += 30) {
                g.drawLine(i, 235, i, 245);
                if (cont != 0) {
                    g.drawString(String.valueOf(cont), i - 9, 230);
                }
                cont += 1;
            }

//				Tra�a as coordenadas do eixo y
            cont = 8;
            for (int i = 0; i <= 480; i += 30) {
                g.drawLine(145, i, 155, i);
                if (cont != 0) {
                    g.drawString(String.valueOf(cont), 130, i + 5);
                }
                cont -= 1;
            }

            g.drawString("0", 153, 243);


            limpar = false;

        }

        if (desenha == true) {
            while (continuar == JOptionPane.YES_OPTION) {

                LimpaVariavel();
//						desenha a funcao.
                if (continuar == JOptionPane.YES_OPTION) {
                    continuar = JOptionPane.NO_OPTION;

                    LerFuncao();
                    TamMatriz();
                    Agrupa();
                    Ordena();

                    int x = 0, y = 0;
                    int espacox = 30;
                    int espacoy = 30;
                    double funcional;
                    //super.paint(g);
                    g.setColor(Color.red);

                    for (int ii = 0; ii < 300 - 1; ii++) {
                        funcional = (ii - (300 / 2)) * 1.0 / espacox;
                        if (ii == 0) {
                            x = ii;
                            y = (int) ((480 / 2) - Grafico.GeraY(funcional) * espacoy);
                        }


                        g.setColor(Color.red); //cor do tra�o do gr�fico
                        g.drawLine(x, y, ii, (int) ((480 / 2) - Grafico.GeraY(funcional) * espacoy));
                        x = ii;
                        y = (int) ((480 / 2) - Grafico.GeraY(funcional) * espacoy);
                    }



 
                    desenha = false;
                }
            }//fim do desenha = true


        }




    }// fim do Paint




}

2 Respostas

Prudencio

Não entendi bem sua explicação, mas vamos lá…

Se a classe Grafico é um Jpanel que vc altera quando clica no botão, vc não precisa instanciar ele todas as vezes. Isso vai ‘zerar’ as alterações anteriores, e você teria de adicionar o JPanel ao JFrame novamente.

Fora isso, não tem segredo, é só chamar o método mesmo, que já está como público.

Outro detalhe… se vc instancia sua classe, pq seus métodos são estáticos?

felipehts

Realmente eu não expliquei muito bem…vou tentar de novo:

O codigo que eu mencionei acima é uma java class, referente a um grafico, quando “rodo” o codigo separado ele apresenta um pop-up pedindo para digitar a função, logo em seguida ele traça as retas. O que fiz, cirei um projeto no Nebeans, com um Jframe, logo em seguida cirei um botão no Jframe com a intenção de chamar o java class que contem o grafico que juntei no projeto e “chamei” no Jpanel, tipo cirei um Panel e faço a chamada do java class dentro dele…

o que acontece que não consigo chamar o metodo de traçar as retas dentro do botão que criei no JFrame, tenho certeza que é algo simples, porém que não tenho conhecimento ainda… vlw…ajudem ai…abrasss

Criado 19 de maio de 2010
Ultima resposta 19 de mai. de 2010
Respostas 2
Participantes 2