First Java project so this question is probably very amateur. I'm trying to run the method paintComponent for drawing shapes in a class that extends JFRAME I just can't figure out how to call it. Do I need to create a graphics variable to act as the background so I can call paintComponent(background)? Or maybe a new Planel?
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.Graphics.*;
import java.awt.event.*;
import java.text.*;
public class Pythag extends JFrame implements ActionListener
{
JTextField text1,text2;
JLabel label1,label2,label3;
JButton buttonC;
public Pythag(){
super ("Pythagorean Theorem");
// Set up the frame
this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
this.setBounds (300, 300, 200, 350);
//creating objects
JPanel boxY = new JPanel ();
boxY.setLayout(new BoxLayout(boxY,BoxLayout.Y_AXIS));
label1 = new JLabel ("A side length",JLabel.CENTER);
label2 = new JLabel ("B side length",JLabel.CENTER);
label3 = new JLabel ("Type in side lengths to calculate hypotenuse",JLabel.CENTER);
buttonC = new JButton ("Button1");
text1 = new JTextField (10);
text2 = new JTextField (10);
//Nestled flow layouts:
//layout1
JPanel line = new JPanel();
line.add(label1);
line.add(text1);
boxY.add(line);
//layout2
JPanel line2 = new JPanel();
line2.add(label2);
line2.add(text2);
boxY.add(line2);
//layout 3
JPanel line3 = new JPanel();
line3.add(label3);
boxY.add(line3);
//layout 4
JPanel line4 = new JPanel();
line4.add(buttonC);
boxY.add(line4);
//Adding listeners
buttonC.addActionListener (this);
text1.addActionListener (this);
text2.addActionListener (this);
//Setting up
this.setContentPane (boxY);
this.setVisible (true);
this.setSize(450,200);
// this.add(panel);
// Graphics bg = backbuffer.getGraphics();
}
public void actionPerformed (ActionEvent e)
{
if (e.getSource () == buttonC)
{
calculate();
}
}
public void calculate(){
double a,b;
DecimalFormat Formatter = new DecimalFormat("#0.00");
try
{
a = Double.parseDouble (text1.getText());
b = Double.parseDouble (text2.getText());
double hypot=Math.sqrt(a*a + b*b);
label3.setText("The length of the hypotenuse is: " + Formatter.format(hypot));
}
catch (NumberFormatException ex)
{
label3.setText("You're clearly a confused, please use NUMBERS for side lengths.");
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.fillRect(100,100,20,20);
}
public static void main (String[] args)
{
new Pythag ();
} // main method
}