0

When I try to draw lines using the for loop below, it works, but it displays pretty slowly even when just loading in. It also pauses at every reload when moving (only added the d key for simplicity) Is that just my monitor/specs being slow, or is there a way to make graphics draw faster using some trade secret technique? Couldn't find anything on the matter by myself

Example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
  
public class Prosscce extends Canvas implements KeyListener
{
   int xshift = 0;
   
   public Prosscce()
   {
      //Add Keystrokes
      setFocusable(true);
      requestFocus();
      addKeyListener(this);
   }
   
   public void keyTyped(KeyEvent e)
   {
      if (e.getKeyChar() == 'd')
         xshift+=2;
      
      repaint();
   }
   
   public void keyPressed(KeyEvent e) { }
   
   public void keyReleased(KeyEvent e) { }
     
   public void paint(Graphics g) 
   {
      int spacing = 20;
      
      for (int i = xshift%spacing; i < getWidth(); i+=spacing)
         g.drawLine(i, 0,  i, getHeight());
   }
    
   public static void main(String[] args) 
   {  
      Prosscce xd = new Prosscce();  
      JFrame f = new JFrame();  
      f.setSize(600, 600);
      f.setResizable(true);  
      f.setLocationRelativeTo(null);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.add(xd);
      f.setVisible(true);
   }
}
camickr
  • 321,443
  • 19
  • 166
  • 288
Epic Coder
  • 19
  • 6
  • 1
    Using a KeyListener is not what you should be doing. Instead, use Key Bindings as per [MadProgrammer's example](https://stackoverflow.com/a/16867943/522444) and have it start a Swing timer. – Hovercraft Full Of Eels Jun 30 '23 at 02:25
  • 2
    Custom painting is done by overriding `paintComponent(...)` of a `JPanel` (or JComponent) and you need to invoke `super.paintComponent(...)` as the first statement to clear the background. Read the Swing tutorial on [Custom Painting](https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) for more information. – camickr Jun 30 '23 at 02:25
  • 2
    Also, do not mix AWT and Swing components. Get rid of the Canvas and use a JPanel and override paintComponent. – Hovercraft Full Of Eels Jun 30 '23 at 02:25
  • K thanks for the help @HovercraftFullOfEels – Epic Coder Jun 30 '23 at 02:30

0 Answers0