我有一个带有java杯图像的applet,可以通过单击5个按钮将其重新定位,以便在applet窗口的主区域中移动它。 我有的问题是按钮没有显示在im applet中唯一显示的是我在蓝色背景上的cup.gif,任何人都可以看到代码的问题,我希望按钮显示和工作 是的,我知道AWT已经老了,但我必须为我的课程学习...任何帮助都会非常感谢大家!
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class moveIt extends Applet implements ActionListener
{
private Image cup;
private Panel Keypad = new Panel();
public int top = 15;
public int left = 15;
private Button Keyarray[] = new Button[5];
public void init ()
{
cup=getImage(getDocumentBase(), "cup.gif");
Canvas myCanvas= new Canvas();
Keyarray[0] = new Button ("Up");
Keyarray[1] = new Button ("Left");
Keyarray[2] = new Button ("Down");
Keyarray[3] = new Button ("Right");
Keyarray[4] = new Button ("Center");
setBackground(Color.BLUE);
Panel frame = new Panel();
frame.setLayout(new BorderLayout());
frame.add(myCanvas, BorderLayout.NORTH);
frame.add(Keypad, BorderLayout.SOUTH);
Keypad.setLayout(new BorderLayout());
Keypad.add(Keyarray[0], BorderLayout.NORTH);
Keypad.add(Keyarray[1], BorderLayout.WEST);
Keypad.add(Keyarray[2], BorderLayout.SOUTH);
Keypad.add(Keyarray[3], BorderLayout.EAST);
Keypad.add(Keyarray[4], BorderLayout.CENTER);
Keyarray[0].addActionListener(this);
Keyarray[1].addActionListener(this);
Keyarray[2].addActionListener(this);
Keyarray[3].addActionListener(this);
Keyarray[4].addActionListener(this);
}//end of method init
public void paint(Graphics g)
{
g.drawImage(cup, left, top, this);
}
public void actionPerformed(ActionEvent e)
{
String arg= e.getActionCommand();
if (arg.equals("Up"))
top -= 15;
if (arg.equals("down"))
top += 15;
if (arg.equals("Left"))
left -= 15;
if (arg.equals("Right"))
left += 15;
if (arg.equals("Center"))
{
top=60;
} left=125;
repaint();
}//end paint method
}//end of class
答案 0 :(得分:2)
frame
添加到小程序this.add(frame)
setOpaque(false)
到frame
所以你可以看到背景重要的备注:
您应该直接在JPanel
上绘画并覆盖它的paintComponent
方法,而不是直接在Applet上绘画。
您需要在paint方法中调用super.paint(g)
或super.paintComponent(g)
(对于JPanel),以免破坏绘制链并查看各种奇怪的绘制工件
我刚注意到AWT组件。 AWT已经过时了。你应该把它移到使用Swing。请参阅Swing Tutorials
使用Java命名约定。变量以小写字母开头,使用camelCasing,例如Keyarray
→keyArray
。类名以大写字母开头,使用CamelCasing,例如moveIt
→MoveIt