[英]My JComponent will only repaint() once I manually resize the window, how do I get it to work as it should?
我已盡力閱讀有關該主題的內容,但是我找不到/不了解如何將答案應用於我的片段代碼(而我所應用的答案無效)
我使用了“ Ivor Horton的Java 2 JDK入門書”中的示例,這是我第一次使用repaint()
但除非調整窗口大小,否則它似乎無法正常工作。 它嘗試重新繪制,但屏幕空白。
這是代碼,如果我做錯了什么,請告訴我。
public class CurveDrawings extends JFrame{
public CurveDrawings (String title){
setTitle(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pane = new CurvePane(); //Create pane containing curves
Container content = getContentPane(); //Get the content pane
//Add the pane containing the curves to the content pane for the applet
content.add(pane);
MouseHandler handler = new MouseHandler();
pane.addMouseListener(handler);
pane.addMouseMotionListener(handler);
}
//Class defining pane on which to draw
class CurvePane extends JComponent{
public CurvePane(){
quadCurve = new QuadCurve2D.Double(
startQ.x, startQ.y, control.x, control.y, endQ.x, endQ.y
);
cubicCurve = new CubicCurve2D.Double(
startC.x, startC.y, controlStart.x, controlStart.y,
controlEnd.x, controlEnd.y, endC.x, endC.y
);
}
}
class Marker{//not needed for my problem}
class MouseHandler extends MouseInputAdapter{
public void mousePressed(MouseEvent e){
if(ctrlQuad.contains(e.getX(),e.getY())){
selected = ctrlQuad;}
else if(ctrlCubic1.contains(e.getX(),e.getY())){
selected = ctrlCubic1;}
else if(ctrlCubic2.contains(e.getX(),e.getY())){
selected = ctrlCubic2;}
}
public void mouseReleased (MouseEvent e){
selected = null;
}
public void mouseDragged (MouseEvent e){
System.out.println("DRAGGED");
if(selected != null){
//Set the marker to current cursor position
selected.setLocation(e.getX(),e.getY());
pane.validate();
pane.repaint();
}
}
Marker selected = null;
}
public void paint (Graphics g){
Graphics2D g2D = (Graphics2D)g; //Get a 2D device context
//Code to draw each component
}
//Points for quadratic curve
//Points for cubic curve
//More unnecessary code}
如果有什么幫助,這里是應用程序的“啟動器”類
提前致謝。
您需要致電
super.paint(g);
在CurveDrawings
類的paint
方法中使用JFrame
超級類中已經提供的繪畫功能。
注意,在Swing中使用自定義繪畫的標准方法是使用基於javax.swing.JComponent
自定義組件,這些組件使用並覆蓋paintComponent
。 這種方法將利用Swing的優化繪畫模型。
請參閱: 執行自定義繪畫
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.