java绘制图形的问题

2024-11-28 01:22:31
推荐回答(3个)
回答1:

简单的例子:repaint就行,不能new Graphics()

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ImageDemo {

private JPanel panel;
private boolean isDrawRect = false;// 是否绘制矩形携棚,默认不绘制

public ImageDemo(){

JFrame frame = new JFrame("Test");
frame.setVisible(true);// 显示
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();// 屏幕大小
frame.setBounds((d.width - 800) / 2, (d.height - 600) / 2, 800, 600);//简侍 大小,定位
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 关闭方式
frame.setLayout(null);

JButton b1 = new JButton("绘制矩形");
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
isDrawRect = true;
panel.repaint();
}
});
b1.setBounds(2, 2, 150, 30);

JButton b2 = new JButton("绘制辩咐则圆形");
b2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
isDrawRect = false;
panel.repaint();
}
});
b2.setBounds(200, 2, 150, 30);

setPanel();
panel.setBounds(5, 50, 400, 450);

frame.add(b1);
frame.add(b2);
frame.add(panel);
frame.validate();
}

private void setPanel(){
panel = new JPanel(){
private static final long serialVersionUID = 1L;
@Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
super.paint(g);
if(isDrawRect){
g.drawRect(100, 100, 200, 300);
} else {
g.drawOval(100, 100, 200, 200);
}
}
};
}

public static void main(String[] args) throws IOException {
new ImageDemo();
}
}

回答2:

repaint()方法就OK了

回答3:

Graphics g = this.getGraphics();