It's a simple question, maybe I just don't understand the tutorial I'm reading from. but I've been stuck on this for a while. My program is as simple as it gets aside from a "hello world". What I'm trying to do is this: when the user clicks the button, the "O" moves to the right. Simple enough, but where do I put repaint()? Do I need to add something.repaint(); to repaint the screen or just by itself? A nested class problem? T_T this is making me miserable how no one seems to have this problem that I can't comprehend. Thanks in advance.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GuiTest {
static int x = 20;
private static class moveTest extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("O", x, 30);
}
}
private static class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
x += 1;
}
}
public static void main(String[] args) {
moveTest displayPanel = new moveTest();
JButton okButton = new JButton("move");
ButtonHandler listener = new ButtonHandler();
okButton.addActionListener(listener);
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(displayPanel, BorderLayout.CENTER);
content.add(okButton, BorderLayout.SOUTH);
JFrame window = new JFrame("GUI Test");
window.setContentPane(content);
window.setSize(250, 100);
window.setLocation(100, 100);
window.setVisible(true);
}
}