我目前停留在有關JScrollPane和子組件的困境。實質上,我需要嚴格控制JScrollPane中子組件的大小調整,以便鎖定到JScrollPane的大小(以便不出現滾動條)或保持固定爲預定義大小(並且讓JScrollPane在適當時顯示滾動條) 。該控件必須能夠動態切換(特別是通過另一個JFrame窗口中的togglebox)。 JScrollPane被定向鎖定到父JFrame窗口(完全填充並通過BorderLayout鎖定到它的大小)。Java ScrollPane和畫布 - 鎖定畫布到JScrollPane大小
由於其三重緩衝功能(createBufferStrategy(3);),目前我使用Canvas對象作爲JScrollPane的子組件。我曾在很多地方看到Canvas和JScrollPane沒有很好的融合,因此可以解決上述問題並廢除使用Canvas的答案將受到高度讚賞。
我的部件的佈局如下:
的JFrame(自定義類) - > JScrollPane的 - >畫布
不知道這是否幫助,但畫布渲染代碼如下:
//This is a method from a nested class inside the JFrame class.
public void run() {
long MaxFrameTime;
long Time;
//This is the Canvas Object
RXDisplayCanvas.createBufferStrategy(3);
BufferStrategy BS = RXDisplayCanvas.getBufferStrategy();
Graphics2D G2D;
while(isVisible()){
MaxFrameTime = Math.round(1000000000.0/FPSLimit);
Time = System.nanoTime();
//Render Frame from a source from another thread via a AtomicReference<BufferedImage> named 'Ref'
BufferedImage Frame = Ref.get();
if(Frame != null){
G2D = (Graphics2D)BS.getDrawGraphics();
int X0 = 0;
int Y0 = 0;
int W = RXDisplayCanvas.getWidth();
int H = RXDisplayCanvas.getHeight();
double Width = Frame.getWidth();
double Height = Frame.getHeight();
double ImgW = Width;
double ImgH = Height;
if(ImgW > W){
ImgW = W;
ImgH = ImgW/(Width/Height);
}
if(ImgH > H){
ImgH = H;
ImgW = ImgH * (Width/Height);
}
int CenterX = (int)Math.round((W/2.0) - (ImgW/2.0)) + X0;
int CenterY = (int)Math.round((H/2.0) - (ImgH/2.0)) + Y0;
G2D.setBackground(Color.BLACK);
G2D.clearRect(0, 0, W, H);
G2D.drawImage(Frame, CenterX, CenterY, (int)Math.round(ImgW), (int)Math.round(ImgH), null);
//Additional Drawing Stuff Here
G2D.dispose();
if(!BS.contentsLost()){
BS.show();
}
}
Time = System.nanoTime() - Time;
if(Time < MaxFrameTime){
try{
Thread.sleep(Math.round((MaxFrameTime - Time)/1000000.0));
}catch(InterruptedException N){}
}
}
}
我的當前實現我的問題不很好地工作(不「重新鎖定」與父JScrollPane的;「FixedDim」是預先設定的維對象):
/**
* Sets whether to lock the size of the canvas object to a predefined dimension.
* @param b If true, the canvas becomes non-resizable and scrollbars will appear when appropriate.
* If false, the canvas will resize with the enclosing scrollpane.
*/
public void setLockResize(boolean b){
CurrentlyLocked = b;
if(b){
RXDisplayCanvas.setMinimumSize(FixedDim);
RXDisplayCanvas.setMaximumSize(FixedDim);
RXDisplayCanvas.setPreferredSize(FixedDim);
}else{
RXDisplayCanvas.setMinimumSize(Min);
RXDisplayCanvas.setMaximumSize(Max);
RXDisplayCanvas.setPreferredSize(FixedDim);
}
}
查看['Scrollable'](http://docs.oracle.com/javase/7/docs/api/javax/swing/Scrollable.html) – MadProgrammer
遵循標準Java命名約定。變量名稱不應以大寫字符開頭。 – camickr
@camickr是的,我知道,私人項目(我正在這樣做),所以它並不重要,但謝謝你的提示。 – initramfs