学习Java还是挺有意思的,但是花的时间也太长了点,代码的调试也好费劲啊。 努力努力吧!!! 来个动图感受一下本篇的运行结果。 通过上方的选择,来决定画的是空心圆还是实心圆,半径由文本框输入,颜色也可以选择,点画图按钮,即可根据选择输出对应的圆的图形。 其完整代码如下: (代码其实也不算长,中间未加注释,如有兴趣的朋友可直接复制并运行) import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Circle_Button extends JFrame implements ActionListener{ private JTextField radius; private JButton button; private Circle_can circle; private JComboBox type; private JButton colorchoose; private int r; private Color c; public Circle_Button() { super("画圆"); this.setBounds(100,100,600,600); this.setVisible(true); JPanel top=new JPanel(); top.add(new JLabel("请选择类型")); type=new JComboBox(); type.addItem("空心圆"); type.addItem("实心圆"); type.addActionListener(this); top.add(type); top.add(new JLabel("请输入半径")); radius=new JTextField(10); top.add(radius); colorchoose=new JButton("请选择颜色"); colorchoose.addActionListener(this); top.add(colorchoose); button=new JButton("画图"); button.addActionListener(this); top.add(button); this.getContentPane().add(top,"North"); circle=new Circle_can(); this.getContentPane().add(circle); } public int get_r() { if(radius.getText().equals("")) r=20; else r=Integer.parseInt(radius.getText()); return r; } public void actionPerformed(ActionEvent arg0) { // TODO Auto-generatedmethod stub if(arg0.getSource()==colorchoose){ c=JColorChooser.showDialog(this, "颜色对话框", Color.red); circle.set_color(c); circle.repaint(); } if(arg0.getSource()==button){ circle.set_type(type.getSelectedIndex()); circle.set_color(c); circle.set_r(this.get_r()); circle.repaint(); } } public static void main(String args[]) { new Circle_Button(); } class Circle_can extends Canvas{ private Color color; private int r; private int t; public void set_color(Color c){ this.color=c; } public void set_r(int r){ this.r=r; } public void set_type(int t){ this.t=t; } public void paint(Graphics g) { g.setColor(color); if(t==0) g.drawOval(this.getWidth()/2-r,this.getHeight()/2-r, 2*r, 2*r); else g.fillOval(this.getWidth()/2-r,this.getHeight()/2-r, 2*r, 2*r); } } |
|
来自: pythonjava学习 > 《待分类》