Re: [J2SE] canvas物件顯示圖片的問題
※ 引述《yuntechvb (雲寶寶)》之銘言:
: 各位大大好
: 小弟是剛接觸swing的新手
: 想請問一下
: canvas物件
: 利用方法paint將圖片載入
: 但是圖片大過視窗大小
: 圖片就會被剪掉
: 有何方法可以避免這個問題呢?
: 補上一些漏掉的訊息
: 因為我是要做類似地圖的功能
: 所以會有拖曳的作動
: 在拖曳的事件下有加入repaint的動作
: 不過還是無法讓被裁掉的部份復原
我個人覺得這是 sun JRE 1.6 增加 swing top-level container 優化的 bug 之一。
你提供的程式只有在 sun JRE 1.6(甚至只有在 JRE for Windows)才會出現你描述
的情況。移動 Canvas object 後不只是外觀無法完整呈現,canvas 外觀沒有正確呈現
的部分也無法收到 mouse event(即使你點擊的部分的確是落在 canvas 內)。
使用 Visual Studio 附的 Spy++,以 find window 功能來觀察 Canvas 所產生的
native window,可以看出這個 native window 所登記的 size 有符合 Canvas
object 所設定的 size,但是 find window 的標把移到 Canvas 產生的 native
window 區域內時,Spy++ 會畫出 native window 的邊框,看起來又只有佔據
JFrame 的 content pane 的區域。
目前可以朝兩個方向:
1. 不使用 swing top-level container 改用 AWT 對應的元件(JFrame => Frame)。
2. 使用 swing component 來實做繪製地圖的部分。
考慮到你的應用中視窗裡可能不會是只有顯示地圖的這個元件,那麼會建議你採
後者的作法。
使用 swing component 來替代你原來使用 Canvas 實做的元件,實做上的困難度
應該是差不多的。
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class j5_test {
ImageIcon temp = new ImageIcon(getClass().getResource("bg.jpg"));
JFrame f_main = new JFrame("");
int x1, y1, newx, newy;
float scale = 1f;
j5_test() {
f_main.getContentPane().setLayout(null);
f_main.setBounds(0, 0, 300, 300);
f_main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JComponent canvas1 = new JComponent() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(temp.getImage(), 0, 0, this);
}
};
canvas1.setBounds(0, 0, temp.getIconWidth(), temp.getIconHeight());
f_main.getContentPane().add(canvas1);
f_main.setVisible(true);
canvas1.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
x1 = evt.getX();
y1 = evt.getY();
}
});
canvas1.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent evt) {
final Container parentOfCanvas = canvas1.getParent();
final int iconWidth = temp.getIconWidth();
final int iconHeight = temp.getIconHeight();
newx = Math.min(0, evt.getX() - x1 + canvas1.getX());
newx = Math.max(newx, -iconWidth + parentOfCanvas.getWidth());
newy = Math.min(0, evt.getY() - y1 + canvas1.getY());
newy = Math.max(newy, -iconHeight + parentOfCanvas.getHeight());
canvas1.setLocation(newx, newy);
}
});
}
public static void main(String[] args) {
j5_test Test = new j5_test();
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 218.173.143.248
※ 編輯: sbrhsieh 來自: 218.173.143.248 (07/18 16:48)
推
07/21 09:24, , 1F
07/21 09:24, 1F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):