如何使 JPanel 中的绘制图形可滚动?
How can I make painted graphics in a JPanel scrollable?
我正在改编棋盘游戏。将通过重写 paintComponent(Graphics g)
方法在 JPanel 上绘制棋盘。该板可能比绘制它的 JPanel 的尺寸大,因此我计划使用 JScrollPane
以允许用户在板上滚动以查看它。例如,我将电路板制作成一个大矩形,看看是否可以让它滚动,但无济于事。我以前成功使用过 JScrollPane
但我无法弄清楚为什么这种情况与我以前使用它的方式有什么不同。
谁能看出它为什么不能正常工作?
这是游戏的 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();
}
}
}
这是我第一次发布问题,所以如果您需要更多信息来解决这个问题,请告诉我
You need to setPreferredSize
on BoardPanel, that seems to do the trick. Don't ask why ;-)
-@geert3
我正在改编棋盘游戏。将通过重写 paintComponent(Graphics g)
方法在 JPanel 上绘制棋盘。该板可能比绘制它的 JPanel 的尺寸大,因此我计划使用 JScrollPane
以允许用户在板上滚动以查看它。例如,我将电路板制作成一个大矩形,看看是否可以让它滚动,但无济于事。我以前成功使用过 JScrollPane
但我无法弄清楚为什么这种情况与我以前使用它的方式有什么不同。
谁能看出它为什么不能正常工作?
这是游戏的 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();
}
}
}
这是我第一次发布问题,所以如果您需要更多信息来解决这个问题,请告诉我
You need to
setPreferredSize
on BoardPanel, that seems to do the trick. Don't ask why ;-)-@geert3