I am trying to create a "simple tetras" as an initial encoder. As the code shown below, the white block can be moved by pressing the arrow keys when it is not possible to execute ( y = y + 10
) in the timer. I guess that ActionListener
is in the wrong position. All I want to do is move the block left and right as it descends.
Here is my code:
import java.awt.event.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Experiment extends JFrame {
int x = 100;
int y = 100;
ASD exp = new ASD();
public Experiment() {
add(exp);
exp.setFocusable(true);
}
public class ASD extends JPanel {
public ASD() {
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
x -= 10;
break;
case KeyEvent.VK_RIGHT:
x += 10;
break;
}
repaint();
}
});
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.BLACK);
g.setColor(Color.WHITE);
g.fillRect(x, y, 30, 30);
}
public class Movement extends JPanel implements ActionListener {
Timer tm = new Timer(5, this);
public void actionPerformed(ActionEvent e) {
y = y + 10;
repaint();
}
}
}
public static void main(String[] args) {
Experiment frame = new Experiment();
frame.setTitle("ASD");
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
source
share