我在这里查看了其他示例,但在创建了所有组件之后重新验证了()或重绘()。我也尝试过this.setVisible(this);那不起作用。我尝试在createGUI()方法中创建我的组件,并在try / catch语句中从init()方法运行它。
修改的 我试过你的所有例子,正如你在评论中看到的那样。但是从每个人都说过为什么现在这个有用呢?
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();
}
}
感谢您的帮助!
答案 0 :(得分:4)
原始代码的主要问题是您在不调用super.paint(g)的情况下覆盖了paint()方法。当您将该方法更改为paintComponent()时,代码可以正常工作,因为该方法甚至不会在Applet中退出,因此它是死代码。
您的代码存在问题:
@Override
annontation,以确保正确覆盖该方法。首先阅读Swing tutorial,以获得更好的解释和工作示例。从以下部分开始:
答案 1 :(得分:1)
你应该在TotalGUI上调用repaint()。
调整大小后gui刷新的原因是调整大小会自动为你调用repaint()。但是,如果您希望gui更改立即显示,则应调用repaint();
然而,首选方法是在你的totalGUI的paint(Graphics g)/ paintComponent(Graphics g)方法中使用:
super.paintComponent(g);
如这些帖子所述:
http://www.sitepoint.com/forums/showthread.php?273522-super.paintComponent()