Java程序可以通過按鈕方便地選擇畫矩形和圓。在Java中,可以通過兩個不同的類來實現(xiàn)這兩種圖形。Rectangle類處理矩形,Circle類處理圓形。下面是一個示例程序,通過按鈕可以選擇要畫的形狀。
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("畫圖形"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 300); DrawShapes drawShapes = new DrawShapes(); frame.add(drawShapes); frame.setVisible(true); } }
在上面的代碼中,我們定義了一個DrawShapes類,該類繼承了JPanel類。在DrawShapes類中,我們創(chuàng)建了兩個按鈕和一個用于存儲所選形狀的整數(shù)變量shapeSelected。我們使用addActionListener()方法將按鈕添加到DrawShapes類的實例中。當點擊其中一個按鈕時,我們在actionPerformed()方法中設(shè)置shapeSelected變量的值,并調(diào)用repaint()方法,以便刷新面板并顯示所選圖形。
在paintComponent()方法中,我們使用Graphics類的drawRect()和drawOval()方法分別繪制矩形和圓形。