当我运行这个类时,它在框架的北中心打印图形,我无法弄清楚如何使它居中。我试过用很多不同的方法来调整x值,并注意到抛物线在正确的区域内移动。
class FunctionPlotPanel extends JPanel
{
protected void paintComponent(Graphics g){
super.paintComponent(g);
int x1=0;
int y1=100;
int x2=200;
int y2=100;
g.drawLine( x1, y1, x2, y2);
int x11=100;
int y11=0;
int x22=100;
int y22=200;
g.drawLine(x11, y11, x22, y22);
Polygon p = new Polygon();
double scalefactor = 0.1;
for(int x=-100;x<=100;x++)
{
p.addPoint(x+100,100-(int)(scalefactor*x*x));
}
int[] xPoints=p.xpoints;
int[] yPoints=p.ypoints;
int nPoints=p.npoints;
g.drawPolyline(xPoints,yPoints,nPoints);
}
}
答案 0 :(得分:1)
中心位置是可见空间与图表大小之间的差异。
使用您组件的getWidth
和getHeight
来确定当前可见区域,并计算您需要的左上角像素数...
在可能的情况下,不要依赖幻数
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class CenterGraphics {
public static void main(String[] args) {
new CenterGraphics();
}
public CenterGraphics() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - 100) / 2;
int y = (getHeight() - 100) / 2;
g2d.drawRect(x, y, 100, 100);
g2d.dispose();
}
}
}