2011-09-30 103 views
1

编写一个使用椭圆大小填充窗口的程序。即使窗口被调整大小,椭圆也会触摸窗口边界。如何在框架内调整大小和绘制组件

我有以下代码:

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.geom.Ellipse2D; 
import javax.swing.JComponent; 

public class EllipseComponent extends JComponent { 
    public void paintComponent(Graphics g) 
    { 
     Graphics2D g2 = (Graphics2D) g; 

     Ellipse2D.Double ellipse = new Ellipse2D.Double(0,0,150,200); 
     g2.draw(ellipse); 
     g2.setColor(Color.red); 
     g2.fill(ellipse); 
    } 
} 

和主类:

import javax.swing.JFrame; 

public class EllipseViewer { 
    public static void main(String[] args) 
    { 
     JFrame frame = new JFrame(); 
     frame.setSize(150, 200); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     EllipseComponent component = new EllipseComponent(); 
     frame.add(component); 

     frame.setVisible(true); 
    } 
} 
+0

回答你的问题:“我怎么可以调整内部的的paintComponent框架“是**不要做**。欲了解更多信息,请参阅我的答案。另请注意,JFrame没有paintComponent方法,但其绘制方法或JComponent的paintComponent方法也是如此。 –

回答

6

在EllipseComponent你做:

Ellipse2D.Double ellipse = new Ellipse2D.Double(0,0,getWidth(),getHeight());

我还建议气垫船充满了鳗鱼的变化。在这种简单的情况下,它可能不是一个问题,但随着paintComponent方法的复杂性增长,您希望尽可能少地使用paintComponent方法计算。

+0

+1用于检测和修复问题的核心(尺寸椭圆到组件大小vs硬编码),-1用于解决怀疑的性能瓶颈 – kleopatra

2

不要调整paintComponent中的组件大小。实际上,不要在该方法中创建对象或执行任何程序逻辑。该方法需要尽可能的精简,尽可能快地绘制,并且就是这样。您必须明白,您无法完全控制何时甚至是否调用此方法,并且您肯定不希望向其添加代码,从而可能会降低速度。

你应该在类的构造函数中创建你的椭圆。要根据JComponent中的大小和尺寸的变化调整其大小,使用的ComponentListener:

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.geom.Ellipse2D; 
import javax.swing.JComponent; 

public class EllipseComponent extends JComponent { 
    Ellipse2D ellipse = null; 

    public EllipseComponent { 
     ellipse = new Ellipse2D.Double(0,0,150,200); 
     addComponentListener(new ComponentAdapter() { 
      public void componentResized(ComponentEvent e) { 
       // set the size of your ellipse here 
       // based on the component's width and height 
      } 
     }); 
    } 

    public void paintComponent(Graphics g) 
    { 
     Graphics2D g2 = (Graphics2D) g; 
     g2.draw(ellipse); 
     g2.setColor(Color.red); 
     g2.fill(ellipse); 
    } 
} 

警告:代码无法运行,也不测试

+1

形状很便宜:-)或换句话说:无需增加复杂性。即使你坚持以椭圆作为领域(尽管Swing的工程师在表现偏执狂的高度,在引入持久的痛苦时表现出了这种效果,但我不会这么做),但不要调整它的状态在听众中,只需在绘画方法中进行。 – kleopatra

相关问题