【发布时间】:2011-11-10 01:26:15
【问题描述】:
我试图在 JFrame 的内容窗格中显示一个大图像。我想让图像或内容窗格可滚动,因为图像很大。我尝试使用 Jscrollpane 将其添加到内容窗格中,但它不起作用。做了一些寻找解决方案,但最终未能找到一个。有人可以指导我吗?我的代码如下
FinalEnvironment.java
package environment;
import java.awt.*;
import java.net.URL;
import javax.swing.*;
public class FinalEnvironment{
public FinalEnvironment(){
Image Eastlake;
URL EastlakeURL = null;
EastlakeURL = FinalEnvironment.class.getResource("/image1/eastlake_night.png");
Eastlake = Toolkit.getDefaultToolkit().getImage(EastlakeURL);
JFrame frame = new JFrame("UniCat World");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
JMenuBar yellowMenuBar = new JMenuBar();
Map map = new Map(800, 550, Eastlake);
yellowMenuBar.setOpaque(true);
yellowMenuBar.setBackground(Color.YELLOW);
yellowMenuBar.setPreferredSize(new Dimension(800, 50));
frame.setJMenuBar(yellowMenuBar);
JScrollPane scroller = new JScrollPane(map);
scroller.setAutoscrolls(true);
scroller.setPreferredSize(new Dimension(800, 550));
frame.getContentPane().add(scroller, BorderLayout.CENTER);
frame.setSize(800, 600);
frame.setVisible(true);
}
public static void main(String[] args){
FinalEnvironment fe = new FinalEnvironment();
}
}
这是我的 map.java
package environment;
import java.awt.*;
import javax.swing.*;
public class Map extends JPanel{
private int width;
private int height;
private Image img;
public Map(int width, int height, Image img){
this.width = width;
this.height = height;
this.img = img;
}
protected void paintComponent(Graphics g)
{
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(img,0,0,2624,1696,null);
}
}
最后,我想在这张图片上放置 Jbuttons。我应该调用一个 Rectangle 并将其放在内容窗格中的图像顶部,然后我使用 Point 来定位我的按钮,还是应该立即使用图像或组件本身来完成它?我需要按钮能够在滚动而不是内容窗格中的静态图像时与图像同步。
谢谢
【问题讨论】:
-
不,这是我在项目中尝试编写的众多代码之一。
-
试试我自己的建议。那么如果你还有问题,我可以发一个代码示例。
-
@noble,不要重新发明轮子,只需使用 JLabel。
标签: java image swing jscrollpane