-1

我有以下类,它是一个简单的 gui,我想让它成为一个小程序,以便它可以显示在浏览器中。我知道如何将代码嵌入到 html 页面中(完成)......但是如何让我的课程成为一个小程序?另外,我假设我不需要一个网络服务器来在我的浏览器中显示小程序......

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();
    }

}
4

2 回答 2

0

使用 aJApplet而不是 a JFrame。确保您阅读了相关的 Java 教程,其中涵盖了 applet 生命周期方法,如initstartstopdestroy.


作为旁注,您应该在事件调度线程之外构建您的 UI。

于 2012-08-15T20:50:25.670 回答
0

使用 aJApplet而不是JFrame像 veer 所说的那样,但您还必须删除frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);,frame.pack();frame.setVisible(true);

另外,替换main(String[] args)init().

于 2012-08-15T20:53:12.473 回答