I\'m looking for the most basic description of how to draw text within a JPanel. I know there are a billion tutorials out there but none of them are clicking with me and I h
Create an inner class that extends JPanel inside your Main class:
class MyPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(Integer.toString(avg), 75, 75);
}
}
Then you need to call repaint on that panel after calling computeAverage() in actionPerformed:
//event handling
public void actionPerformed(ActionEvent e) {
if (e.getSource() == avgBtn) {
computeAverage();
panel.repaint();
}
}
I think you should not be subclassing JFrame. Make an instance of JFrame an instance
variable of Main class and add the JPanel etc. to it.
1) A JFrame doesn't have a paintComponent() method so the code you posted won't do anything. You need to create a custom JPanel and override its paintComponent() method to do your custom painting.
2) Even if you do the above, the painting will still not display because a panel by default has a zero size. So you will then need to set the preferred size of the panel to make sure it is visible.
3) Why are you even doing this. All you need to do is use a JLabel and set the text of the JLabel.
I find it hard to believe you looked at other tutorials. The Swing tutorial on Custom Painting has a 20 line program that shows the basics.
Add a JLabel to the JPanel.
Call setText(String) on the JLabel and your text will be drawn within the JPanel.