本文目錄一覽:
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){
}
這樣的一段代碼後 在運行程序 會看到一個藍色邊框的長方形 橘黃色的實體長方形 和粉紅色的
依次橫向排列 但是 經測試 並不是每一次都能正確的初始化 所以建議畫圖操作盡量在上述方法中進行操作
原創文章,作者:ANIW,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/148834.html