在 Java 中将矩形居中
您尝试在 Java 中绘制矩形并将其以特定尺寸居中可能会面临未对齐问题。出现这种情况是由于框架的装饰(边框和标题栏)侵占了绘画区域。
解决方案涉及在框架的内容区域上绘画。这会将框架的装饰从绘画区域中排除,从而生成正确居中的矩形。
下面是说明正确方法的代码片段:
public class CenterOfFrame { public static void main(String[] args) { new CenterOfFrame(); } public CenterOfFrame() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } new BadFrame().setVisible(true); JFrame goodFrame = new JFrame(); goodFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); goodFrame.setContentPane(new PaintablePane()); goodFrame.pack(); goodFrame.setLocationRelativeTo(null); goodFrame.setVisible(true); } }); } public class BadFrame extends JFrame { public BadFrame() { setSize(800, 400); setDefaultCloseOperation(EXIT_ON_CLOSE); } @Override public void paint(Graphics g) { super.paint(g); paintTest(g, getWidth() - 1, getHeight() - 1); } } public void paintTest(Graphics g, int width, int height) { g.setColor(Color.RED); g.drawLine(0, 0, width, height); g.drawLine(width, 0, 0, height); g.drawRect(50, 50, width - 100, height - 100); } public class PaintablePane extends JPanel { @Override public Dimension getPreferredSize() { return new Dimension(800, 400); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); paintTest(g, getWidth() - 1, getHeight() - 1); } } }
此代码提供了如何绘制的示例考虑到框架的装饰,以框架为中心的矩形。
以上是如何在 Java 框架内正确地将矩形居中?的详细内容。更多信息请关注PHP中文网其他相关文章!