我有以下类是一个简单的gui,我想把它变成一个小程序,以便它可以在浏览器中显示。我知道如何将代码嵌入到html页面中(完成了)...但是如何才能使我的类成为applet?另外,我假设我不需要Web服务器只是为了在我的浏览器中显示applet ...
package tester1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class PanelTest implements ActionListener {
JFrame frame;
JLabel inputLabel;
JLabel outputLabel;
JLabel outputHidden;
JTextField inputText;
JButton button;
JButton clear;
JButton about;
public PanelTest() {
frame = new JFrame("User Name");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3, 2, 10, 10));
//creating first row
JPanel row1 = new JPanel();
inputLabel = new JLabel("Your Name");
inputText = new JTextField(15);
// FlowLayout flow1 = new FlowLayout(FlowLayout.CENTER, 10, 10);
// row1.setLayout(flow1);
row1.add(inputLabel);
row1.add(inputText);
frame.add(row1);
//creating second row
JPanel row2 = new JPanel();
button = new JButton("Display");
clear = new JButton("Clear");
about = new JButton("About");
button.addActionListener(this);
clear.addActionListener(this);
about.addActionListener(new displayAbout());
row2.add(button);
row2.add(clear);
row2.add(about);
frame.add(row2);
//creating third row
JPanel row3 = new JPanel();
outputLabel = new JLabel("Output:", JLabel.LEFT);
outputHidden = new JLabel("", JLabel.RIGHT);
// FlowLayout flow2 = new FlowLayout(FlowLayout.CENTER, 10, 10);
// row3.setLayout(flow2);
row3.add(outputLabel);
row3.add(outputHidden);
frame.add(row3);
frame.pack();
frame.setVisible(true);
}
//same method listen for two different events
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("Display")) {
outputHidden.setText(inputText.getText());
}
if(command.equals("Clear")) {
outputHidden.setText("");
inputText.setText("");
}
}
//another way to listen for events
class displayAbout implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Username 1.1 \n by Jorge L. Vazquez");
}
}
public static void main(String[] args) {
PanelTest frameTest = new PanelTest();
}
}
答案 0 :(得分:0)
使用JApplet
而不是JFrame
。请务必阅读the relevant Java Tutorial,其中涵盖了init
,start
,stop
和destroy
等applet生命周期方法。
作为旁注,您应该不在事件派发线程之外构建您的UI。
答案 1 :(得分:0)
使用JApplet
而不是像JFrame
那样,但您还必须删除frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
,frame.pack();
和frame.setVisible(true);
另外,将main(String[] args)
替换为init()
。