import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
class DrawPanel extends JPanel{
int diameter;
public DrawPanel() {
super();
}
public void updateDia(int dia){
this.diameter = dia ;
this.updateUI();
}
public void paint(Graphics g){
g.setColor(Color.RED);
int x = Math.max(0, (getWidth() - diameter)/2);
int y = Math.max(0, (getWidth() - diameter)/2);
g.drawOval(x,y,diameter,diameter);
}
}
public class CircleFrame extends JFrame{
public static void main(String[] args){
new CircleFrame().setVisible(true);
}
JTextField diameterField = new JTextField();
JButton submit = new JButton("提交");
JLabel diameterLabel = new JLabel("直径 :");
DrawPanel drawPanel = new DrawPanel();
public static final int BLANK = 30;
public static final int INIT_SIZE = 200;
public static final int INFO_HEIGHT = 30;
public CircleFrame() {
super("Draw Circle");
initPanel();
this.setSize(INIT_SIZE ,INIT_SIZE + INFO_HEIGHT);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void initPanel() {
diameterField.setText("0");
drawPanel.setSize(INIT_SIZE,INIT_SIZE);
submit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
updateDrawPanel();
}
});
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new BorderLayout());
infoPanel.add(diameterLabel,BorderLayout.WEST);
infoPanel.add(diameterField,BorderLayout.CENTER);
infoPanel.add(submit,BorderLayout.EAST);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(infoPanel,BorderLayout.NORTH);
getContentPane().add(drawPanel,BorderLayout.CENTER);
}
private void updateDrawPanel(){
int dia;
try {
dia = Integer.parseInt(diameterField.getText());
} catch(Exception e){
JOptionPane.showMessageDialog(this,"wrong diameter !","wrong",JOptionPane.OK_OPTION);
return;
}
if(dia < 0 ){
JOptionPane.showMessageDialog(this,"wrong diameter !","wrong",JOptionPane.OK_OPTION);
return;
}
int nowSize = Math.max(dia+BLANK, INIT_SIZE);
drawPanel.updateDia(dia);
drawPanel.setSize(nowSize,nowSize);
setSize(new Dimension(nowSize,nowSize+INFO_HEIGHT));
this.validate();
}
}
我以前的一个程序,你先运行下这个,看看效果,然后在这个基础上改一下,应该不难!