close
參考答案:
import java.awt.event.*; import javax.swing.*; import java.awt.*; class JDD01 { public static void main(String[] args) { new MyFrame(); } } class MyFrame extends JFrame { Color curColor; MyFrame() { Panel toolbar; Button redBtn, blueBtn; //設定視窗標題、大小、位置、排版方式 this.setTitle("繪製圓形"); this.setSize(640,480); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setLayout(new BorderLayout()); // 加入自訂容器至中央區塊 this.add(new MyPanel(this),BorderLayout.CENTER); toolbar = new Panel(); curColor = Color.red; //預設繪製顏色為紅色 redBtn = new Button("Red"); blueBtn = new Button("Blue"); //按下RED按鈕時,設定目前顏色為紅色 redBtn.addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e){ MyFrame.this.curColor=Color.red; } }); //按下BLUE按鈕時,設定目前顏色為藍色 blueBtn.addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e){ MyFrame.this.curColor=Color.blue; } }); //配置下方的工具按鈕 toolbar.setLayout(new FlowLayout()); toolbar.add(redBtn); toolbar.add(blueBtn); this.add(toolbar, BorderLayout.SOUTH); setVisible(true); } } class MyPanel extends Panel { MyFrame parent; public MyPanel(MyFrame p) { parent = p; this.setSize(600,480); this.setBackground(Color.WHITE); //當滑鼠按下時,在目前位置以繪圖顏色畫一個20x20的圓形 addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e){ Graphics g = MyPanel.this.getGraphics(); g.setColor(parent.curColor); g.fillOval(e.getX()-10, e.getY()-10, 20, 20); } }); } }
執行結果:
全站熱搜
留言列表