【发布时间】:2012-02-04 06:13:57
【问题描述】:
我已经查看了此处的其他示例,但在创建所有组件之后是 revalidate() 或 repaint()。我也试过 this.setVisible(this);那没有用。我尝试在 createGUI() 方法中创建我的组件,并在 try/catch 语句中从 init() 方法运行它。
编辑 正如您在 cmets 中看到的那样,我尝试了所有示例。但是从每个人都说为什么这现在有效?
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();
}
}
感谢您的帮助!
【问题讨论】:
-
如需尽快获得更好的帮助,请发帖 SSCCE。但在此之前,请删除
Graphics g = getGraphics();并将所有对g的引用替换为g2。您还不会看到组件,但它可能会停止闪烁。 -
我发布了代码,并删除了图形 g = getGraphics();不幸的是,这对闪烁没有帮助。
标签: java swing applet components