9 java swing graphics2d paintcomponent
如何在没有类(扩展JFrame)的情况下绘制对象?我找到了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);
}
}
Run Code Online (Sandbox Code Playgroud)
acd*_*ior 21
如果要更改绘制组件的方式(添加矩形),则需要paintComponent()在该组件中重新定义.在您的代码中,您正在使用 getGraphics().
你不应该调用getGraphics()组件.你做的任何绘画(对于Graphics返回的)将是临时的,并且在下次Swing确定需要重新绘制组件时将丢失.
相反,您应该重写paintComponent(Graphics)方法(of JComponent或JPanel),并使用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
}
}
Run Code Online (Sandbox Code Playgroud)
另一个版本,完全相同,但可能更清楚:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
51238 次 |
| 最近记录: |