1 回答
TA贡献1887条经验 获得超5个赞
我没有收到您收到的错误。然而,这不是在 Swing 中进行自定义绘画的正确方法。长话短说,你在这种while
情况下尝试的东西是行不通的。相反,让组件根据其父级大小和坐标进行绘制,而不必将它们设置为显式:
/**
* @Overide paint method was a thing in AWT.
* In Swing you must override paintComponent (and call super.paintComponent())
* in order to respect the paint chain.
*
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (getParent() != null) { //Paint according to parent
Graphics g2 = (Graphics2D) g;
//Calculations
int posX = Math.round(getParent().getWidth() / 100) * 20;
int posY = Math.round(getParent().getHeight() / 100) * 20;
int Width = Math.round(getParent().getWidth() / 100) * 80;
int Height = Math.round(getParent().getHeight() / 100) * 80;
g2.drawOval(posX, posY, Width, Height);
}
}
您所做的另一件不必要的事情是:
@Override
public int getWidth() {
return this.Width;
}
重写一个组件的getWidth
andgetSize
不会带你到任何地方。
完整的例子:
public class ClockViewer {
public static void main(String[] args) {
SwingUtilities.invokeLater(()->{
// create frame
JFrame frame = new JFrame();
final int Frame_Width = 110;
final int Frame_Height = 130;
// set frame attributes
frame.setSize(Frame_Width, Frame_Height);
frame.setTitle("A Really Descriptive Title...");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// get pane attributes
System.out.println(frame.getContentPane().getWidth());
System.out.println(frame.getContentPane().getHeight());
// create ellipse
JComponent ellipse = new JComponent() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (getParent() != null) { //Paint according to parent
Graphics g2 = (Graphics2D) g;
//Calculations
int posX = Math.round(getParent().getWidth() / 100) * 20;
int posY = Math.round(getParent().getHeight() / 100) * 20;
int Width = Math.round(getParent().getWidth() / 100) * 80;
int Height = Math.round(getParent().getHeight() / 100) * 80;
g2.drawOval(posX, posY, Width, Height);
}
}
};
frame.add(ellipse);
frame.setVisible(true);
});
}
}
添加回答
举报