使用swing绘制java网格

我想用java绘制一个网格(10×10),但我们必须在JFrame使用drawRectMethod来实现它,这是我的程序到目前为止

 import java.awt.*; import javax.swing.*; public class Grid extends JFrame { public Grid() { setSize(500, 500); setVisible(true); } // draw grid public void paint(Graphics g) { for (int x = 30; x <= 300; x += 30) for (int y = 30; y <= 300; y += 30) g.drawRect(x, y, 30, 30); } public static void main(String args[]) { Grid application = new Grid(); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } 

这段代码正在运行。

只需删除25

 import java.awt.*; import javax.swing.*; public class Grid extends JFrame { public Grid() { setSize( 500, 500 ); setVisible( true ); } public void paint( Graphics g ) { for ( int x = 30; x <= 300; x += 30 ) for ( int y = 30; y <= 300; y += 30 ) g.drawRect( x, y, 30, 30 ); } public static void main( String args[] ) { Grid application = new Grid(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } 

我不确定你的问题是什么,但你的实施稍微偏离……

  • 不要从JFrame扩展,你没有在类中添加任何新function,并且它不适合执行自定义绘制,因为它不是双缓冲的,并且它在框架表面和用户之间有一个JRootPanecontentPane 。 此外,你冒着在框架装饰下绘画的风险。 看看我如何设置在中间? 以及如何获得精确的屏幕中间部分,即使重新resize以获得更多细节。
  • 不要覆盖顶级容器(或一般)的paint ,请参阅前一点。 相反,从一个从JPanel扩展的组件开始,然后覆盖paintComponent 。 另外不要忘记调用paint方法的super方法以保持paint chain合约。 有关更多详细信息,请参阅AWT和Swing中的 绘画以及执行自定义绘画
  • 不要依赖幻数,而是使用已知值来决定你想做什么。

格

 import java.awt.*; import javax.swing.*; public class Grid { public static void main(String[] args) { new Grid(); } public Grid() { 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 size = Math.min(getWidth() - 4, getHeight() - 4) / 10; int width = getWidth() - (size * 2); int height = getHeight() - (size * 2); int y = (getHeight() - (size * 10)) / 2; for (int horz = 0; horz < 10; horz++) { int x = (getWidth() - (size * 10)) / 2; for (int vert = 0; vert < 10; vert++) { g.drawRect(x, y, size, size); x += size; } y += size; } g2d.dispose(); } } }