Java程序可以通過(guò)按鈕方便地選擇畫(huà)矩形和圓。在Java中,可以通過(guò)兩個(gè)不同的類來(lái)實(shí)現(xiàn)這兩種圖形。Rectangle類處理矩形,Circle類處理圓形。下面是一個(gè)示例程序,通過(guò)按鈕可以選擇要畫(huà)的形狀。
import java.awt.*; import java.awt.event.*; import javax.swing.*; class DrawShapes extends JPanel implements ActionListener { JButton rectButton, circleButton; int shapeSelected; public DrawShapes() { rectButton = new JButton("矩形"); circleButton = new JButton("圓"); rectButton.addActionListener(this); circleButton.addActionListener(this); add(rectButton); add(circleButton); shapeSelected = 0; } public void actionPerformed(ActionEvent e) { if (e.getSource() == rectButton) shapeSelected = 1; else if (e.getSource() == circleButton) shapeSelected = 2; repaint(); } public void paintComponent(Graphics g) { super.paintComponent(g); if (shapeSelected == 1) { g.drawRect(10, 10, 100, 100); } else if (shapeSelected == 2) { g.drawOval(10, 10, 100, 100); } } } public class TestDrawShapes { public static void main(String[] args) { JFrame frame = new JFrame("畫(huà)圖形"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 300); DrawShapes drawShapes = new DrawShapes(); frame.add(drawShapes); frame.setVisible(true); } }
在上面的代碼中,我們定義了一個(gè)DrawShapes類,該類繼承了JPanel類。在DrawShapes類中,我們創(chuàng)建了兩個(gè)按鈕和一個(gè)用于存儲(chǔ)所選形狀的整數(shù)變量shapeSelected。我們使用addActionListener()方法將按鈕添加到DrawShapes類的實(shí)例中。當(dāng)點(diǎn)擊其中一個(gè)按鈕時(shí),我們?cè)赼ctionPerformed()方法中設(shè)置shapeSelected變量的值,并調(diào)用repaint()方法,以便刷新面板并顯示所選圖形。
在paintComponent()方法中,我們使用Graphics類的drawRect()和drawOval()方法分別繪制矩形和圓形。