我正在尝试创建一个大型游戏板,其中只有一部分在视口中可见,并且希望能够使用箭头键移动视口以查看整个板。现在我有一个 JScrollPane,其中包含一个 JPanel,其中包含图像、文本和其他内容,但这些都是无关紧要的。现在我有一个与 JPanel 大小相同的 ImageIcon 作为背景,我希望有一个选项可以使用按键来移动视口,并且没有任何可见的滚动条。
我尝试在 JPanel 和 JScrollPane 上调用 getViewPort().setViewPosition() ,然后调用 revalidate() 。但它仍然不起作用。我的代码如下
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import java.awt.*;
import java.awt.event.*;
public class Game extends JPanel {
JPanel game = new JPanel();
JScrollPane scrollPane = new JScrollPane(game);
JLabel grass = new JLabel();
private KeyListener keys = new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
System.out.println("Down");
scrollPane.getViewport()
} else if (e.getKeyCode() == KeyEvent.VK_UP) {
System.out.println("up");
}
revalidate();
}
public void keyPressed(KeyEvent e) {
}
};
public void createGame(int turns) {
int gameWidth = 1800;
int gameHeight = 1600;
int viewPortWidth = 800;
int viewPortHeight = 600;
//setLayout(null);
setSize(new Dimension(viewPortWidth, viewPortHeight));
game.setLayout(null);
game.setSize(new Dimension(gameWidth, gameHeight));
//add the background image
ImageIcon background = new ImageIcon("Grass.png");
grass.setIcon(background);
grass.setBounds(0,0, gameWidth, gameHeight);
game.setBackground(Color.GREEN);
game.add(grass);
game.setBounds(0,0, gameWidth, gameHeight);
//key listener
game.addKeyListener(keys);
//add(game);
scrollPane.setPreferredSize(new Dimension(viewPortWidth, viewPortHeight));
add(scrollPane);
}
}
有一个使用的例子scrollRectToVisible() http://download.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#scrollRectToVisible%28java.awt.Rectangle%29 here https://stackoverflow.com/questions/7818387/jscrollpane-with-multiple-jtextareas/7820703#7820703 and here http://download.oracle.com/javase/tutorial/uiswing/components/scrollpane.html。您应该能够根据您的使用情况调整它。
顺便说一句,考虑使用键绑定 https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html, shown here https://sites.google.com/site/drjohnbmatthews/keypad-panel, here https://stackoverflow.com/questions/6887296/how-to-make-an-image-move-while-listening-to-a-keypress-in-java/6887628#6887628 and here http://stackoverflow.com/questions/7201509/mousemotionlistener-in-java-swing-using-it-with-components-inside-components-et/7203419#7203419.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)