It looks like you're making progress, but you might like to see the tutorial examples, too.
Martijn Courteaux's analysis is correct: you should override paintComponent()
. Also, it's a bad idea to mix AWT and Swing components. Both ideas are discussed in Painting in AWT and Swing.
Scrolling shouldn't cause flickering. Here's an example that scrolls a grid of components and paints a checkerboard on the background.
import java.awt.*;
import javax.swing.*;
public class Scrolling extends JFrame {
private static final int MAX = 8;
private static final int SIZE = 480;
private static final Color light = new Color(0x40C040);
private static final Color dark = new Color(0x408040);
private static class MyPanel extends JPanel {
public MyPanel() {
super(true);
this.setLayout(new GridLayout(MAX, MAX, MAX, MAX));
this.setPreferredSize(new Dimension(SIZE, SIZE));
for (int i = 0; i < MAX * MAX; i++) {
this.add(new JLabel(String.valueOf(i), JLabel.HORIZONTAL));
}
}
@Override
public void paintComponent(final Graphics g) {
int w = this.getWidth()/MAX;
int h = this.getHeight()/MAX;
for (int row = 0; row < MAX; row++) {
for (int col = 0; col < MAX; col++) {
g.setColor((row + col) % 2 == 0 ? light : dark);
g.fillRect(col * w, row * h, w, h);
}
}
}
}
public Scrolling() {
this.setLayout(new BorderLayout());
final MyPanel panel = new MyPanel();
final JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.getHorizontalScrollBar().setUnitIncrement(16);
scrollPane.getVerticalScrollBar().setUnitIncrement(16);
this.add(scrollPane, BorderLayout.CENTER);
this.pack();
this.setSize(SIZE - SIZE / 3, SIZE - SIZE / 3);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
}
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new Scrolling().setVisible(true);
}
});
}
}