匿名使用者
匿名使用者 發問時間: 電腦與網際網路程式設計 · 1 0 年前

[JAVA]小程式問題

有人能簡單寫出~原圖是圓形 然後按數字鍵1會變成三角形

2會變成正方形 3會變成菱形 4會變成長方形 5會變成星形 嗎??

拜託了~

1 個解答

評分
  • Samuel
    Lv 5
    1 0 年前
    最佳解答

    import java.awt.event.*;

    import java.awt.*;

    import javax.swing.*;

    import java.awt.geom.*;

    import java.applet.*;

    public class graph extends Applet implements KeyListener {

    int keyNow = KeyEvent.VK_0; // 儲存按下之數字鍵, 初始值為數字鍵 0

    public static void main(String args[]) {

    graph gra = new graph();

    JFrame f = new JFrame("圖形");

    f.addKeyListener(gra);

    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    f.getContentPane().add(gra, BorderLayout.CENTER);

    f.setBounds(0, 0, 300, 200);

    f.setVisible(true);

    }

    public void paint(Graphics g) {

    drawgraph(g); // 呼叫以下繪圖函式

    }

    private void drawgraph(Graphics g) {

    Graphics2D g2d = (Graphics2D)g;

    switch (keyNow) {

    case KeyEvent.VK_0 : // 圓型

    g2d.setPaint(Color.red);

    g2d.fill(new Ellipse2D.Double(10.0d, 10.0d, 110.0d, 110.0d));

    break;

    case KeyEvent.VK_1 : // 三角形

    g2d.setPaint(Color.orange);

    g2d.fill(new Polygon(new int [] {10, 60, 110}, new int [] {110, 10, 110}, 3));

    break;

    case KeyEvent.VK_2 : // 正方形

    g2d.setPaint(Color.yellow);

    g2d.fill(new Rectangle2D.Double(10.0d, 10.0d, 110.0d, 110.0d));

    break;

    case KeyEvent.VK_3 : // 菱形

    g2d.setPaint(Color.green);

    g2d.fill(new Polygon(new int [] {10, 60, 110, 60}, new int [] {60, 10, 60, 110}, 4));

    break;

    case KeyEvent.VK_4 : // 長方形

    g2d.setPaint(Color.blue);

    g2d.fill(new Polygon(new int [] {10, 110, 110, 10}, new int [] {35, 35, 85, 85}, 4));

    break;

    case KeyEvent.VK_5 : // 星形

    g2d.setPaint(Color.magenta);

    g2d.fill(new Polygon(new int [] {10, 60, 110}, new int [] {85, 10, 85}, 3));

    g2d.fill(new Polygon(new int [] {10, 110, 60}, new int [] {35, 35, 110}, 3));

    break;

    }

    g2d.setPaint(Color.black);

    g2d.drawString("0:圓,1:三角,2:正方,3:菱形,4:長方,5:星形", 10, 140);

    }

    public void keyTyped(KeyEvent e) { // 不處理

    }

    public void keyPressed(KeyEvent e) { // 處理鍵盤按下時

    int keycode = e.getKeyCode();

    // 只處理數字鍵0~5

    if (keycode == KeyEvent.VK_0 || keycode == KeyEvent.VK_1 || keycode == KeyEvent.VK_2 ||

    keycode == KeyEvent.VK_3 || keycode == KeyEvent.VK_4 || keycode == KeyEvent.VK_5) {

    keyNow = keycode; // 將按下之鍵碼存入變數 keyNow

    repaint();// 系統會呼叫 paint, 不應該直接呼叫 paint

    }

    }

    public void keyReleased(KeyEvent e) { // 不處理

    }

    }

    • Commenter avatar登入以對解答發表意見
還有問題?馬上發問,尋求解答。