簡體   English   中英

如何使它作為Java小程序而不是Java應用程序運行?

[英]How do I make this run as a Java applet instead of a Java application?

我不知道如何使它作為applet運行,請幫助我嘗試了很多事情,但沒有任何效果。 我相信我必須讓class extend Applet但是我不確定這樣做之后要更改什么

編輯:沒關系,我已經解決了問題! :D

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class HowMany {

   private JFrame mainJFrame;
   private JLabel headerJLabel;
   private JLabel statusJLabel;
   private JPanel controlJPanel;

   public HowMany() {
      prepareGUI();
   }

   public static void main(String[] args){ /* The main part of the code */
      HowMany HowMany = new HowMany();  
      HowMany.showEventDemo();       
   }

   private void prepareGUI() {
      mainJFrame = new JFrame("Click the Button!"); /*Sets the applet title */
      mainJFrame.setSize(400,400); /* Sets the size of the applet */
      mainJFrame.setLayout(new GridLayout(3, 1));

      headerJLabel = new JLabel("",JLabel.CENTER ); //Centers the header JLabel
      statusJLabel = new JLabel("",JLabel.CENTER); //Centers the status JLabel    

      statusJLabel.setSize(350,100); //Sets the size of the status JLabel
      mainJFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlJPanel = new JPanel();
      controlJPanel.setLayout(new FlowLayout());

      mainJFrame.add(headerJLabel); //adds all the stuff to the applet
      mainJFrame.add(controlJPanel);
      mainJFrame.add(statusJLabel);
      mainJFrame.setVisible(true);  
   }

   private void showEventDemo() {
      headerJLabel.setText("Click the Button to add to the bottom text!");     /* Tells you to click */
      /* Click button */
      JButton clickButton = new JButton("Click Me!");

      clickButton.setActionCommand("Click Me!");

      clickButton.addActionListener(new ButtonClickListener()); 
      /* Adds the buttons to the JFrame */
      controlJPanel.add(clickButton);     

      mainJFrame.setVisible(true);  
   }

   private class ButtonClickListener implements ActionListener {
      int x = 0; //Sets the starting value of the # of times the button was clicked to 0
      public void actionPerformed(ActionEvent e) {
         String command = e.getActionCommand();  
         /* Displays how many times the button was clicked */
         if( command.equals( "Click Me!" ))  {
             x = x + 1;
             String m = Integer.toString(x);
            statusJLabel.setText("Times clicked: " + m);
         }
      }     
   }
}

要運行Java applet,您需要在Web服務器上運行它。

該鏈接顯示了有關如何制作applet的oracle示例,您應該可以輕松地使用它們來處理示例:

https://docs.oracle.com/javase/tutorial/deployment/applet/

您還可以在該頁面上看到,如果您嘗試將其作為本地小程序運行,並且將Java安全性設置為高或非常高,則將無法使用。 要記住的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM