我想在JFrame的內容窗格中顯示大圖像。我想讓圖像或內容面板可以滾動,因爲圖像很大。我試圖用Jscrollpane來做,並將其添加到內容窗格中,但它不起作用。有沒有尋找解決方案,但最終沒有找到一個。有人可以指導我嗎?我的代碼都低於使圖像在JFrame內容窗格中滾動
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並將它放在contentpane中的圖像的頂部,然後使用Point來定位我的按鈕,或者我應該直接使用圖像或組件本身來執行它?我需要該按鈕能夠與圖像同步,而不是在內容窗格中進行靜態滾動。
感謝
這是功課嗎? – Boro
不是,它是我嘗試在我的項目中編碼的許多事情之一。 – Noble
嘗試我爲自己建議的內容。那麼如果你還有一些問題,我可以發佈代碼示例。 – Boro