在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中文網其他相關文章!