【问题标题】:Using Applets With TextField使用带有 TextField 的小程序
【发布时间】:2014-01-26 20:39:51
【问题描述】:

我使用小程序中的绘图方法制作了一个小型宇宙飞船。 我正在使用 x 和 y 来移动小程序框周围的船。 所以我想我会进一步改善自己并尝试添加textfield 和一个动态更改 x n y 的按钮,但是当我单击按钮时 飞船静止不动。这是我的代码:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

import java.applet.*;

public class SpaceshipInAJApplet extends Applet implements ActionListener {
    int x = 65;
    int y = 100;

    TextField x1,y1;
    Button enter;

    public void init() {

        setBackground(new Color(0xabcdef));
        x1 = new TextField("X : " + x, 5);
        y1 = new TextField("Y : " + y, 5);
        add(x1);
        add(y1);
        setSize(500, 500);
        enter = new Button("Enter");
        add(enter);
        enter.addActionListener(this);
    }

    // Creates Class Called paint to draw objects into the applet
    public void paint(Graphics g) {

        int []flameX = {x+65,x+75,x+55};
        int []flameY = {y+185,y+161,y+161};
        int []wingX = {x+65,x+120,x+15};
        int []wingY = {y+50,y+150,y+150};
        super.paint(g);
     // Draw Wing
        g.setColor(Color.LIGHT_GRAY);
        g.fillPolygon(wingX, wingY, 3);
        // Draw Wing Border
        g.setColor(Color.BLACK);
        g.drawPolygon(wingX, wingY, 3);
        // Draw Body    
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(x+50, y+85, 30, 65);
        // Draw Border
        g.setColor(Color.BLACK);
        g.drawRect(x+50, y+85, 30, 65);
        // Draw Rocket
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(x+55, y+150, 20, 10);
        // Draw Border
        g.setColor(Color.BLACK);
        g.drawRect(x+55, y+150, 20, 10);
        // Draw Rocket Flame
        g.setColor(Color.ORANGE);
        g.fillPolygon(flameX, flameY, 3);

    }
    public void actionPerformed(ActionEvent ae)
    {
        try {
            int tempX = Integer.parseInt(x1.getText());
            int tempY = Integer.parseInt(y1.getText());


        }
        catch(NumberFormatException ex)
        {
            System.out.println("Exception : "+ex);
        }
    }
}

【问题讨论】:

  • 是的。除了创建和设置两个整数的值之外,您在 actionPerformed 中什么也不做。和他们一起做你想做的事?
  • 1) 为什么要编写小程序?如果是由于规范。老师请发给Why CS teachers should stop teaching Java applets。 2) 为什么选择 AWT 而不是 Swing?请参阅我在 Swing extras over AWT 上的回答,有很多放弃使用 AWT 组件的充分理由。

标签: java applet textfield


【解决方案1】:

actionPerformed()方法中添加This.repaint()

【讨论】:

  • 我不敢相信一点代码就修复了我的程序哈哈绝对疯狂。
  • 非常感谢 java-love
猜你喜欢
  • 1970-01-01
  • 2020-02-24
  • 2015-06-07
  • 2019-11-09
  • 1970-01-01
  • 1970-01-01
  • 2020-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多