Я посмотрел другие примеры здесь, но revalidate () или repaint () после создания всех моих компонентов.Я также попробовал this.setVisible (this);и это не сработало.Я попытался создать свои компоненты в методе createGUI () и запустить его из метода init () в инструкции try / catch.
РЕДАКТИРОВАТЬ Я испробовал все ваши примеры, как вы можете видеть в комментариях.Но из того, что все сказали, почему это сейчас работает?
package basic;
import java.awt.*;
//import java.applet.*;
import java.applet.Applet;
import javax.swing.*;
import java.awt.event.*;
public class Shapes extends Applet implements ActionListener
{
JButton rectBtn = new JButton("Rectangle");
JButton circBtn = new JButton("Circle");
JLabel rectLbl = new JLabel("Rectangle"), circLbl = new JLabel("Circle");
JLabel widthLbl = new JLabel("Width"), heightLbl = new JLabel("Height");
JTextField widthTF = new JTextField(6), heightTF = new JTextField(6), colorTF;
boolean rectOn;
boolean circOn;
int x,y, width, height;
String xcord, ycord, widthSize, heightSize;
public void init()
{
JPanel TotalGUI = new JPanel(new GridLayout(2,0));
TotalGUI.add(rectLbl); TotalGUI.add(rectBtn);
rectBtn.addActionListener(this);
TotalGUI.add(circLbl); TotalGUI.add(circBtn);
circBtn.addActionListener(this);
TotalGUI.add(widthLbl); TotalGUI.add(widthTF);
TotalGUI.add(heightLbl); TotalGUI.add(heightTF);
add(TotalGUI, BorderLayout.WEST);
//this.setVisible(true);
TotalGUI.repaint();
//pack();
}
//@Override
public void paintComponent(Graphics g)
{
//super.paintComponent(g);
//Graphics g2 = getGraphics();
if(rectOn)//if Rectangle has been pressed
{
g.drawRect(x,y, width,height);
}
if(circOn)//if Circle has been pressed
{
g.drawOval(x,y, width, height);
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == rectBtn)
{
rectOn = true;
}
if(e.getSource() == circBtn)
{
circOn = true;
}
//Reads coordinates and sizes as Strings and converts to integers
try{
widthSize = widthTF.getText();
width = Integer.parseInt(widthSize);
heightSize = heightTF.getText();
height = Integer.parseInt(heightSize);
}
catch(Exception err) { JOptionPane.showMessageDialog(null, "Enter a number!"); }
repaint();
}
}
Спасибо за помощь!