Reputation: 195
I want this to slowly create a line that paints from 10,0 to 10,600. The line won't even paint at all, the only reason why I think it isn't working is my format and placing of different components are a little off? Why?
public class Moving extends JPanel {
int counter;
Timer time;
public void setUp() {
ActionListener action = new ActionListener() {
public void actionPerformed(ActionEvent event){
counter++;
repaint();
}
};
time = new Timer(100, action);
time.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.drawRect(10, counter, 20, 20);
}
public static void main(String[] args) {
Moving game = new Moving();
JFrame frame = new JFrame("Frame");
frame.setSize(320, 340);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(game);
game.setUp();
}
}
Upvotes: 0
Views: 285
Reputation: 347204
You've not added Moving
to the frame you create...
Updated
I've updated the code slightly to demonstrate the point, adding Moving
to a frame. I've also included the Initial Thread requirements
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
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;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Moving extends JPanel {
int counter;
Timer time;
public Moving() {
ActionListener action = new ActionListener() {
public void actionPerformed(ActionEvent event) {
counter++;
repaint();
}
};
time = new Timer(100, action);
}
public void start() {
time.start();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.drawRect(10, counter, 20, 20);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
Moving moving = new Moving();
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(moving);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
moving.start();
}
});
}
}
Upvotes: 3