Questo di seguito è un esempio minimale (ho cercato di ridurre il codice il più possibile) che ho scritto al volo per muovere un pallino tramite 4 pulsanti. Prendine spunto.
codice:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class DotMoveFrame extends JFrame implements ActionListener {
private DotMovePanel dotMovePanel = new DotMovePanel();
private JButton leftButton = new JButton("LEFT");
private JButton rightButton = new JButton("RIGHT");
private JButton upButton = new JButton("UP");
private JButton downButton = new JButton("DOWN");
private int movement = 5;
public DotMoveFrame() {
super("Dot Move");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 400);
setLocationRelativeTo(null);
JPanel controlPanel = new JPanel();
controlPanel.add(leftButton);
controlPanel.add(rightButton);
controlPanel.add(upButton);
controlPanel.add(downButton);
add(dotMovePanel, BorderLayout.CENTER);
add(controlPanel, BorderLayout.SOUTH);
leftButton.addActionListener(this);
rightButton.addActionListener(this);
upButton.addActionListener(this);
downButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == leftButton) {
dotMovePanel.moveDot(-movement, 0);
} else if (source == rightButton) {
dotMovePanel.moveDot(movement, 0);
} else if (source == upButton) {
dotMovePanel.moveDot(0, -movement);
} else if (source == downButton) {
dotMovePanel.moveDot(0, movement);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DotMoveFrame().setVisible(true);
}
});
}
}
codice:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import javax.swing.JPanel;
public class DotMovePanel extends JPanel {
private int dotX = 100;
private int dotY = 100;
public void moveDot(int addX, int addY) {
dotX += addX;
dotY += addY;
repaint(); // Richiede il repaint completo del componente!
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Ellipse2D.Float dot = new Ellipse2D.Float(dotX-4, dotY-4, 8, 8);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.RED);
g2d.fill(dot);
}
}