如何使图形对象在调整大小时保持静态?
下面我附上了代码,它在窗口的中心绘制了一条简单的垂直线,但是当我调整窗口大小时,该线会向调整大小的方向倾斜。
但是当尝试使用两条线时,第一条线倾斜,而第二条线保持固定。
我希望无论给定的大小如何,它们都是固定的。
public class finalPlot{
static JFrame f = new JFrame();
public static void main(final String[] args){
f.setTitle("Plot");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// f.setSize(500,500);
f.setResizable(true);
f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(final WindowEvent e){
System.exit(0);
}
});
f.add(new PlotArray(), BorderLayout.CENTER);
f.pack();
f.show();
}
}
class PlotArray extends Canvas{
public Dimension getPreferredSize(){
return new Dimension(500, 500);
}
public void paint(final Graphics g){
final Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
final Dimension size = getSize();
final Line2D lin =
new Line2D.Float((float) size.width / 2, 90, 250, 250);
final Line2D lin2 = new Line2D.Float(45, 300, 250, 150);
g2.setPaint(Color.blue);
g2.draw(lin);
g2.draw(lin2);
}
}
谢谢
Below I have attached the code, that draws a simple vertical line at the centre of the window, but when I resize the window, the line leans towards the resizing direction.
But when try with two lines, the 1st line leans while the second remain fixed.
I want them to be fixed irrespective of the given size.
public class finalPlot{
static JFrame f = new JFrame();
public static void main(final String[] args){
f.setTitle("Plot");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// f.setSize(500,500);
f.setResizable(true);
f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(final WindowEvent e){
System.exit(0);
}
});
f.add(new PlotArray(), BorderLayout.CENTER);
f.pack();
f.show();
}
}
class PlotArray extends Canvas{
public Dimension getPreferredSize(){
return new Dimension(500, 500);
}
public void paint(final Graphics g){
final Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
final Dimension size = getSize();
final Line2D lin =
new Line2D.Float((float) size.width / 2, 90, 250, 250);
final Line2D lin2 = new Line2D.Float(45, 300, 250, 150);
g2.setPaint(Color.blue);
g2.draw(lin);
g2.draw(lin2);
}
}
Thank You
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
然后不要使用
size.width / 2
因为它是 Canvas 组件的宽度。请改用静态号码。Then don't use
size.width / 2
because it's widht of your Canvas component. Use a static number instead.每次调整窗口大小时都会调用
PlotArray.paint
,并且每次发生时,lin
都会使用不同的 x 值进行绘制,因为PlotArray
具有不同的宽度。为了保持它不变,您可以在第一次调用paint
时将其宽度存储在实例变量中。PlotArray.paint
is called every time the window is resized, and each time that happens,lin
is drawn with a different x value because thePlotArray
has a different width. To keep it constant, you can store its width in an instance variable the first timepaint
is called.