I want to draw a line on a JFrame
by clicking on pushButton
.
I wrote this code bellow, but it doesn't work. I would appreciate very much if anyone could help me solve this problem.
Rubin
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class testDrawing {
int x = 0;
int y = 0;
int x1 = 0;
int y1 = 0;
JFrame frame=new JFrame();
DrawPanel draw=new DrawPanel();
public testDrawing() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
frame.setVisible(true);
JButton btntest = new JButton("Draw a line");
btntest.setBounds(380, 100, 100, 20);
frame.add(btntest);
btntest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
x = 100;
y = 100;
x1 = 150;
y1 = 130;
executeAction();
}
});
}
public void executeAction(){
frame.getContentPane().add(draw);
x = 100;
y = 100;
x1 = 150;
y1 = 170;
draw.repaint();
try{
Thread.sleep(30);
}catch(Exception e)
{}
}
class DrawPanel extends JPanel{
public void paintComponent(Graphics g)
{
g.drawLine(x, y, x1, y1);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
testDrawing test = new testDrawing();
// test.executeAction(); with this line uncommented the drawing is performed,
// but the pushBotton event doesn't work
}
});
}
}