I'm new to Java GUI and I'm trying to get this program to display a square when a button is clicked. Nothing happens because repaint() does not work on paintComponent(Graphics g). I have searched and some said to use an Event dispatch thread but I am still very confused
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class Ham extends JFrame implements ActionListener
{
JPanel p1;
JButton b1;
public Ham(){
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1 = new JPanel();
b1 = new JButton("Check");
b1.addActionListener(this);
p1.add(b1);
add(p1, BorderLayout.NORTH);
setVisible(true);
}
public void actionPerformed (ActionEvent e){
if(e.getSource() == b1){
repaint();
}
}
public void paintComponent(Graphics g){
g.setColor(Color.BLUE);
g.fillRect(100,100,50,50);
}
}
JFrame does not have a paintComponent() method.
Custom painting is done by overriding the paintComponent()
method of a JPanel
(or JComponent). You should also override the getPreferredSize()
method of the panel to return a reasonable value. Then you add the panel to the frame.
You can then invoke repaint()
on the panel and the paintComponent() method will be invoked.
Read the section from the Swing tutorial on Custom Painting for more information and examples.