使用getGraphics()绘制对象而不扩展JFrame

我如何绘制一个没有类的对象(它扩展了JFrame )? 我find了getGraphics方法,但它不绘制对象。

 import javax.swing.*; import java.awt.*; public class Main { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setSize(600, 400); JPanel panel = new JPanel(); frame.add(panel); Graphics g = panel.getGraphics(); g.setColor(Color.BLUE); g.fillRect(0, 0, 100, 100); } } 

如果你想改变你的组件的绘制方式(你正在添加矩形),你需要重新定义该组件中的paintComponent() 。 在你的代码中,你正在使用getGraphics()

您不应该在组件上调用getGraphics() 。 您所做的任何绘画(返回的Graphics )都将是临时的,并且在下一次Swing确定组件需要重新绘制时将会丢失。

相反,您应该重写paintComponent(Graphics)方法( JComponentJPanel ),并使用接收的Graphics对象作为参数在此方法中进行绘制。

检查这个链接进一步阅读。

下面是你的代码,更正。

 import javax.swing.*; import java.awt.*; public class Main { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setSize(600, 400); JPanel panel = new JPanel() { @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.BLUE); g.fillRect(0, 0, 100, 100); } }; frame.add(panel); // Graphics g = panel.getGraphics(); // g.setColor(Color.BLUE); // g.fillRect(0, 0, 100, 100); frame.validate(); // because you added panel after setVisible was called frame.repaint(); // because you added panel after setVisible was called } } 

另一个版本,是完全一样的东西 ,但可能会更清楚你:

 import javax.swing.*; import java.awt.*; public class Main { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setSize(600, 400); JPanel panel = new MyRectangleJPanel(); // changed this line frame.add(panel); // Graphics g = panel.getGraphics(); // g.setColor(Color.BLUE); // g.fillRect(0, 0, 100, 100); frame.validate(); // because you added panel after setVisible was called frame.repaint(); // because you added panel after setVisible was called } } /* A JPanel that overrides the paintComponent() method and draws a rectangle */ class MyRectangleJPanel extends JPanel { @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.BLUE); g.fillRect(0, 0, 100, 100); } } 

您必须重写JPanel类中的paintComponent方法。 所以你应该创build一个扩展JPanel并在子类中重写paintComponent方法的类

java.awt.image.BufferedImage中


为什么不使用java.awt.image.BufferedImage的实例? 例如

 BufferedImage output = new BufferedImage(600, 400, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = output.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(Color.WHITE); g2.fillRect(0, 0, output.getWidth(), output.getHeight()); g2.setColor(Color.BLUE); g2.fillRect(0, 0, 100, 100); JOptionPane.showMessageDialog(null, new ImageIcon(output));