I am making an adaptation of a board game. The board will be drawn on a JPanel by overriding the paintComponent(Graphics g)
method. The board can possibly be larger than the size of the JPanel it is drawn in, so I planned to use a JScrollPane
to allow the user to scroll across the board to view it. As an example, I made the board a single large rectangle to see if I could get it to scroll across that, but to no avail. I have used JScrollPane
successfully before but I cannot figure out why this case is any different from the way I previously used it.
Can anyone see why it is not working correctly?
Here is the code for the Game's JFrame:
public class GameFrame extends JFrame{
JPanel playerDeckPanel, contentPane;
JScrollPane gameScrollPane;
BoardPanel boardPanel;
public GameFrame(){
super();
SwingUtilities.invokeLater(new Runnable(){
public void run(){
boardPanel = new BoardPanel();
playerDeckPanel = new JPanel();
boardPanel.setLayout(new GridLayout(1,1));
playerDeckPanel.setLayout(new CardLayout());
boardPanel.setSize(1000,1000);
gameScrollPane = new JScrollPane(boardPanel);
gameScrollPane.setPreferredSize(new Dimension(300,300));
contentPane = ((JPanel) getContentPane());
contentPane.setLayout(new GridLayout(1,2));
contentPane.add(gameScrollPane);
contentPane.add(playerDeckPanel);
setMinimumSize(new Dimension(800,600));
}
});
}
public static void main(String[] args){
GameFrame gameFrame = new GameFrame();
gameFrame.setVisible(true);
}
private class BoardPanel extends JPanel{
public BoardPanel(){
super();
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(100, 10, 700, 600);
revalidate();
}
}
}
This is my first time posting a question, so let me know if you need additional information to solve this problem
You need to
setPreferredSize
on BoardPanel, that seems to do the trick. Don't ask why ;-)-@geert3