The function and the code for drawing lines are not responded by an ActionListener
from the code inside public void actionPerformed(ActionEvent e)
. Why cannot I draw lines inside the ActionListener
? Why cannot I call a function that draws a line.
MainClass.java
import javax.swing.SwingUtilities;
public final class MainClass {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new CreateFrame();
System.out.println("GUI created Successfully");
}
});
}
}
//CreateFrame.java
import javax.swing.JFrame;
public class CreateFrame {
CreateFrame(){
createFrame();
}
public void createFrame(){
JFrame frame = new JFrame("Drawing Lines");
frame.setSize(400, 300);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//calling a class and adding in the frame
frame.add(new CreateDrawings());
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
//CreateDrawings.java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class CreateDrawings extends JPanel {
private static final long serialVersionUID = 1L;
JButton drawButton;
JPanel panel;
CreateDrawings() {
setLayout(null);
drawButton = new JButton("Draw");
drawButton.setBounds(150, 220, 120, 30);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
add(drawButton);
g.setColor(Color.blue);
g.drawLine(10, 50, 200, 50);
drawButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
g.setColor(Color.red); //NOT WORKING
g.drawLine(10, 100, 200, 100); //NOT WORKING
drawSomething(g); //NOT WORKING
JOptionPane.showMessageDialog(null, "This is called though!");
}
});
}// PaintComponent
private void drawSomething(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawLine(10, 150, 200, 150);
}
}