8-1使用按钮选择绘制不同图形
编写一个程序,实现如下的界面,当点击不同按钮时绘制相应的图形。点击“椭圆”,绘制一个椭圆形;点击“矩形”,绘制一个矩形;点击“直线”,绘制一条直线。实现图形绘制即可,图形位置和大小自定。
参考代码
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class b{
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
ChangeGraphFrame frame = new ChangeGraphFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class ChangeGraphFrame extends JFrame {
private GraphComponent graphComponent;
public ChangeGraphFrame() {
setSize(250, 200);
setTitle("绘制图形");
graphComponent = new GraphComponent();
add(graphComponent, BorderLayout.CENTER);
JButton elipseButton = new JButton("椭圆");
elipseButton.addActionListener(new ChangeGraphAction(1));
JButton rectButton = new JButton("矩形");
rectButton.addActionListener(new ChangeGraphAction(2));
JButton lineButton = new JButton("直线");
lineButton.addActionListener(new ChangeGraphAction(3));
JPanel buttonPanel = new JPanel();
buttonPanel.add(elipseButton);
buttonPanel.add(rectButton);
buttonPanel.add(lineButton);
add(buttonPanel, BorderLayout.SOUTH);
}
private class ChangeGraphAction implements ActionListener {
private int choice;
public ChangeGraphAction(int choice) {
this.choice = choice;
}
public void actionPerformed(ActionEvent event) {
graphComponent.setGraphChoice(choice);
repaint();
}
}
}
class GraphComponent extends JComponent {
private int graphChoice = 0;
public int getGraphChoice() {
return graphChoice;
}
public void setGraphChoice(int graphChoice) {
this.graphChoice = graphChoice;
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Ellipse2D elipse = new Ellipse2D.Double(70, 10, 100, 100);
Rectangle2D rect = new Rectangle2D.Double(70, 10, 100, 100);
Line2D line = new Line2D.Double(10, 10, 200, 100);
switch (graphChoice) {
case 1:
g2.draw(elipse);
break;
case 2:
g2.draw(rect);
break;
case 3:
g2.draw(line);
break;
}
}
}