I have got a grid with rectangles which I will fill in with values. However, depending on the input the grid may be quite large so I would like to add a scrollbar option to the image. The code below does not seem to do what I want? Any help is appreciated.
class Cube extends JComponent
{
public void paint(Graphics g)
{
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
g.setColor(Color.GRAY);
g.fillRect(i*40, j*40, 40, 40);
}
}
for (int i = 0; i < 50; i++)
{
for (int j = 0; j < 50; j++)
{
g.setColor(Color.BLACK);
g.drawRect(i*40, j*40, 40, 40);
}
}
}
public static void main(String[] a)
{
// CREATE SCROLLBAR
JScrollPane scroller = new JScrollPane();
JFrame window = new JFrame();
window.setSize(200,200);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(new Cube());
//ADD THE SCROLLBAR
window.getContentPane().add(scroller, BorderLayout.CENTER);
window.setVisible(true);
}
}
Some tips:
I rewrite your program as below.
class Cube extends JComponent
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
g.setColor(Color.GRAY);
g.fillRect(i*40, j*40, 40, 40);
}
}
for (int i = 0; i < 50; i++)
{
for (int j = 0; j < 50; j++)
{
g.setColor(Color.BLACK);
g.drawRect(i*40, j*40, 40, 40);
}
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(1000, 1000);
}
public static void main(String[] a){
// use event dispatcher thread
EventQueue.invokeLater(
new Runnable() {
public void run() {
Cube cube = new Cube();
JScrollPane scroller = new JScrollPane(cube);
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set the content pane
window.setContentPane(scroller);
window.pack();
window.setVisible(true);
}
});
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.