我开发了一个应用程序来产生以下输出: -
我覆盖了JPanel的getPrefferredSize,但是为什么我在更改大小时没有观察到输出的任何变化。即使我将大小设置为0,0图表根本没有翻译,我得到的输出与显示的相同上面。
这是我的完整代码: -
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Skeleton extends JFrame{
Skeleton()
{
super("Donut");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400);
add(new Board());
setVisible(true);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable(){public void run(){new Skeleton();}});
}
}
class Board extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2=(Graphics2D)g;
RenderingHints rh=new RenderingHints(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
//the following statement has no noticeable effect.
rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHints(rh);
Ellipse2D e=new Ellipse2D.Double(0, 0, 80, 130);
g2.setStroke(new BasicStroke(1));
g2.setColor(Color.RED);
for(int deg=0;deg<360;deg+=5)
{
AffineTransform at=AffineTransform.getTranslateInstance(getWidth()/2,getHeight()/2);
at.rotate(Math.toRadians(deg));
//returns a new Shape object after it has been undergone the 'at' transformation.
g2.draw(at.createTransformedShape(e));
}
}
public Dimension getPreferredSize()
{
return new Dimension(100,100);
}
}
答案 0 :(得分:5)
由于您的布局管理器。默认情况下,BorderLayout
会忽略首选大小,但会填充所有可用空间。使用例如FlowLayout
和yu会看到差异。