1 Bài 1- Buổi 4 Mon Nov 12, 2012 9:00 am
Admin
Admin
Do sử dụng đệ quy, nên các bác test nhẹ khoảng <=10 vì nhiều quá tội nghiệp máy các bác@@
- Code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
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.JPanel;
import javax.swing.JTextField;
public class Bai1 {
JFrame frame;
JLabel top_lb,lb;
JTextField tf;
JButton bt;
JPanel bot;
myPane tritan;
int x1,y1,x2,y2,x3,y3;
Bai1(){
frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setTitle("Tam giac");
frame.setSize(new Dimension(410, 350));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(200, 200);
tritan = new myPane();
lb = new JLabel("Enter number of oder: ");
top_lb = new JLabel();
top_lb.setSize(new Dimension(410, 350));
tf = new JTextField(6);
bot = new JPanel(new FlowLayout());
bt = new JButton("Show");
bt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int num = Integer.parseInt(tf.getText());
if (num>=0){
x1=0; y1=250;
x2=200; y2=0;
x3=400; y3=250;
tritan.setL(num);
tritan.repaint();
}
}
});
bot.add(lb);
bot.add(tf);
bot.add(bt);
frame.add(tritan,BorderLayout.CENTER);
frame.add(bot,BorderLayout.SOUTH);
frame.setVisible(true);
}
public static void main(String[] args) {
Bai1 obj = new Bai1();
}
}
class myPane extends JPanel{
int x1,y1,x2,y2,x3,y3,n;
public void setL(int n){
this.n=n;
this.x1=0; this.y1=250;
this.x2=200; this.y2=0;
this.x3=400; this.y3=250;
}
public void create(int x1,int y1,int x2,int y2,int x3,int y3,int n,Graphics g){
g.drawLine((int)(x1+x2)/2,(int)(y1+y2)/2,(int)(x2+x3)/2,(int)(y2+y3)/2);
g.drawLine((int)(x3+x2)/2,(int)(y3+y2)/2,(int)(x1+x3)/2,(int)(y1+y3)/2);
g.drawLine((int)(x1+x3)/2,(int)(y1+y3)/2,(int)(x2+x1)/2,(int)(y2+y1)/2);
if (n==1) return;
create(x1,y1,(int)(x2+x1)/2,(int)(y2+y1)/2,(int)(x1+x3)/2,(int)(y1+y3)/2,n-1,g);
create(x2,y2,(int)(x2+x1)/2,(int)(y2+y1)/2,(int)(x3+x2)/2,(int)(y3+y2)/2,n-1,g);
create(x3,y3,(int)(x1+x3)/2,(int)(y1+y3)/2,(int)(x3+x2)/2,(int)(y3+y2)/2,n-1,g);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawLine(x1, y1, x2, y2);
g.drawLine(x2, y2, x3, y3);
g.drawLine(x3, y3, x1, y1);
if (n>0)
create(x1,y1,x2,y2,x3,y3,n,g);
}
}