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);
? ? ? ? });
? ? }
}
添加回答
舉報