How can I call the repaint() method with a keyboard event in java?

26 Views Asked by At

I´m trying to writa a code that paints a Line2D with 2 points that i`ve defined in the paint method. There is a static variable(i) that every time that the paint method is invoked it increases(i++) and creates new points based on the value of i. Now the line prints that points. The problem comes when I use repaint() because it does nothing, it is located inside the listener class. I know the listener class is right becaouse it prints on the console correctly. The paint method is correct becaouse every time i close and open the window generated the system calls the paint method automatically and prints a new Line2D.

Should I locate the repaint method in other site? I also have thought about do this program using threads and placing repaint() inside the run method.

Thanks for reading aand sorry for my bad english, any advice will be hightly apreciated :)

After seeing that it didn´t work there i tried to move the source object of the listener class to the frame and to the panel.

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

import java.util.ArrayList;
import java.lang.Math;
import java.awt.event.*;
import java.awt.event.KeyEvent;
import java.awt.Component;

public class Graficador3{ //nombre más comercial: GrafTY
    static ArrayList<Point2D.Float> punts= new ArrayList<Point2D.Float>();
    public static void main(String[] args){
    
    generapuntos poli = new generapuntos(1, 1, 0, 1, 100, 1000, (float) 0.1);
    punts = poli.generador();
    
    marcos3 mimarco = new marcos3(200, 200, 400, 250, "Grafico 1");  //x,y,w,h,title
    
    mimarco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    
    
    
    
    //laminas.dibujaPuntos(punts);
    
    
    
    
    }
}

class marcos3 extends JFrame{
    public marcos3(int x, int y, int w, int h, String title){
        
        setTitle(title);
        setBounds(x, y, w, h);
        setVisible(true);
        
        laminas3 milamina = new laminas3();
    
        add(milamina);
        
        eventosTeclado mievento = new eventosTeclado();
        
        addKeyListener(mievento);
        
        }
    /*
    public void addlamina(
    El plan es eliminar la creación de la lámina del constructor y hacerlo como un
    método para cada objeto, el problema es que necesitamos pasar el parámetro de la clase
    por lo que necesitamos tipos genéricos.     
    
    */
}

class laminas3 extends JPanel{
/*

#Combiar ambos bucles en 1.
#Arreglar fallo de unión de los extremos
#

#NO PONER ESTA CLASE A LA ESCUCHA, la podemos ejecutar directamente con repaint();
    añadir el listener en el frame y hacer que también sea la fuente, al pulsar ejecuta repaint()
    y i = i+1 por lo que vamos avanzando en la función
    
    Utilizar update() para el incremental drawing


  eventosTeclado mievento2 = new eventosTeclado();
    JButton botonAzul = new JButton("Azul");
    add(botonAzul);
    botonAzul.addActionListener(mievento2);
*/

    public void paint(Graphics g){
    
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(Color.BLACK);
    
    
    //for(float i= inicio*escala; i<fin*escala; i++){
            puntos.add(new Point2D.Float(i, (float) (a*Math.pow(i,3)+ b*Math.pow(i,2)+ c*Math.pow(i,1)+ d)));
            puntos.add(new Point2D.Float(i+1, (float) (a*Math.pow(i+1,3)+ b*Math.pow(i+1,2)+ c*Math.pow(i+1,1)+ d)));
        //System.out.println(new Point2D.Float(i, (float) (a*Math.pow(i,3)+ b*Math.pow(i,2)+ c*Math.pow(i,1)+ d)).toString());
        
    
    //for(int i=0; i<puntos.size()-1; i++){
            //System.out.println(i);
            mipunto = puntos.get(i);
            mipunto2 = puntos.get(i+1);
            System.out.println(mipunto.toString());
            System.out.println(mipunto2.toString());
            g2.draw(new Line2D.Double(mipunto, mipunto2));
            
            i++;
            
        


}
private double a = 0.0005;
private double b = -0.01;
private int c = -2;
private int d = 65;
private int inicio = 100;
private int fin = 1000;
private float escala = (float) 0.1;
private ArrayList<Point2D.Float> puntos= new ArrayList<Point2D.Float>();
private Point2D.Float mipunto = new Point2D.Float();
private Point2D.Float mipunto2 = new Point2D.Float();

//Modificamos el código para que al pulsar espacio se ejecute repaint() que tiene un static int i=0; tal que i++; al ejecutarse
//por lo que se va incrementando la pintura. Si pasamos los parámetros de zona a repaint() podemos hacer que pinte conforme avanza
//el eje de las abscisas sin que borre el trabajo anterior. También podemos utilizar update.

private static int i=0;
}

class eventosTeclado extends laminas3 implements KeyListener, ActionListener{
        public void keyPressed(KeyEvent e){
            //aquí queríamos poner repaint(), pero no podemos poruqe no hereda de java.awt.Component
            repaint();
            System.out.println("tecla pulsada");
        }
        public void keyReleased(KeyEvent e){
        
        }
        public void keyTyped(KeyEvent e){
        
        }
        
        public void actionPerformed(ActionEvent e){ 
        
        }
}
0

There are 0 best solutions below