我想将Simple Java程序转换为Applet程序。我已经寻找了不同的教程,但一般来说大部分内容都没有谈到GUI到Applet。
这是我的简单程序,如果您可以指示我这样做或评论我会非常感激的更改行。
以下是代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test_Exam_091 {
public static void main(String[] args) {
new MyFrame();
}
}
class MyFrame extends JFrame implements MouseListener {
public MyFrame() {
setTitle("Playing With The Mouse!");
setSize(400, 400);
setResizable(false);
setVisible(true);
addMouseListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
show();
}
public void mouseEntered(MouseEvent me) {
System.out.println("Mouse entered at: ("
+ me.getX() + ", " + me.getY() + ")");
}
public void mouseExited(MouseEvent me) {
System.out.println("Mouse exited at: ("
+ me.getX() + ", " + me.getY() + ")");
}
public void mouseClicked(MouseEvent me) {
System.out.println("Mouse clicked at: ("
+ me.getX() + ", " + me.getY() + ")");
}
public void mousePressed(MouseEvent me) {
System.out.println("Mouse pressed at: ("
+ me.getX() + ", " + me.getY() + ")");
}
public void mouseReleased(MouseEvent me) {
System.out.println("Mouse released at: ("
+ me.getX() + ", " + me.getY() + ")");
}
} // End of MyFrame class
答案 0 :(得分:2)
JApplet是java.awt.Panel的后代,它也充当Swing容器,因此几乎可以与JFrame
和JPanel
等其他容器互换使用。
答案 1 :(得分:1)
一些提示:构造函数的大多数行与applet无关。
setTitle("Playing With The Mouse!"); // An applet has no title
// (Though it might have an ID/name in HTML)
setSize(400, 400); // Set in HTML
setResizable(false); // An applet is usually fixed size
setVisible(true); // Not relevant to an applet (visible by default)
addMouseListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Not allowed in an applet
show(); // Deprecated for components around 1.2, for TLCs around 1.5, ..
// ..and redundant
在监听器方法中..
System.out.println("Mouse pressed at: (" + me.getX() + ", " + me.getY() +")");
会导致问题,因为该输出将最终出现在Java控制台中,这对最终用户(以及大多数开发人员)通常是不可见的。 JFrame
形式也不是特别合适。有必要在GUI中添加JLabel
或类似的内容,以显示结果。