本文目录一览:
java绘图代码问题
我随手写了一个,你自己看看,注释我就不写了
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestDraw implements ActionListener {
private JButton b1,b2,b3;
JFrame frame;
MyPanel panel;
public void init() {
frame = new JFrame();
frame.setBounds(100, 100, 400, 300);
frame.setTitle("画");
frame.setLayout(new GridLayout(2, 1));
JPanel p1 = new JPanel();
b1 = new JButton("直线");
b2 = new JButton("矩形");
b3 = new JButton("椭圆");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
p1.add(b1);
p1.add(b2);
p1.add(b3);
panel = new MyPanel();
frame.add(p1);
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == b1) {
panel.setFlag(0);
panel.repaint();
}else if(e.getSource() == b2) {
panel.setFlag(1);
panel.repaint();
}else if(e.getSource() == b3) {
panel.setFlag(2);
panel.repaint();
}
}
public static void main(String[] args) {
new TestDraw().init();
}
class MyPanel extends JPanel {
int flag = -1;
public MyPanel() {
this.setSize(400, 400);
this.setBackground(Color.white);
this.setVisible(true);
}
//画直线
public void drawL(Graphics g) {
g.drawLine(100, 20, 200, 20);
}
//画矩形
public void drawR(Graphics g) {
g.drawRect(100, 20, 200, 100);
}
//画椭圆
public void drawO(Graphics g) {
g.drawOval(100, 20, 200, 100);
}
@Override
public void paint(Graphics g) {
super.paint(g);
if(flag == 0) {
drawL(g);
}else if(flag == 1) {
drawR(g);
}else if(flag == 2) {
drawO(g);
}
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
}
}
java中在JFrame绘图问题
按照你的要求定义一个新方法,在JFrame上绘图的Java程序如下
import java.awt.Graphics;
import javax.swing.JFrame;
public class C extends JFrame{
static int x,y,width,height;
public void paint(Graphics g){
super.paint(g);
g.drawOval(x, y, width, height);
}
public static void drawCircle(int i, int j, int k, int l) {
x=i;y=j;width=k;height=l;
}
public static void main(String[] args) {
C c=new C();
c.setTitle("画圆");
c.setSize(300,300);
drawCircle(100,200,50,50);
c.repaint();
c.setLocationRelativeTo(null);
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c.setVisible(true);
}
}
运行结果
Java绘图问题,图像出不来
Java绘图应该用paint函数
把public void draw(Graphics g)改成public void paint(Graphics g)就行了.
java画图问题
因为程序初始化的时候会自动调用paint()方法 而你没有进行重写 在加入
public void paint(Graphics g){
}
这样的一段代码后 在运行程序 会看到一个蓝色边框的长方形 橘黄色的实体长方形 和粉红色的
依次横向排列 但是 经测试 并不是每一次都能正确的初始化 所以建议画图操作尽量在上述方法中进行操作