Java编译错误:类Appletprac是公共的,应该在名为Appletprac.java的文件中声明

当我编译java程序时,我收到此错误:类Appletprac是公共的,应该在名为Appletprac.java的文件中Appletprac.java

这是我的java代码:

 import java.applet.*; import java.awt.*; // Graphics Class import javax.swing.*; import java.awt.event.*; /* */ public class Appletprac extends JApplet implements ActionListener { JButton OK; JRadioButton Font_Style1,Font_Style2,Font_Style3; ButtonGroup bg; JCheckBox Font_Family_Name; JTextField jt; int i; String s=""; public void init() { OK=new JButton("OK"); Font_Family_Name=new JCheckBox("Serif"); Font_Style1=new JRadioButton("Plain"); Font_Style2=new JRadioButton("Bold"); Font_Style3=new JRadioButton("BoldItalic"); bg=new ButtonGroup(); jt=new JTextField(20); this.setLayout(new FlowLayout()); bg.add(Font_Style1); bg.add(Font_Style2); bg.add(Font_Style3); this.add(jt); this.add(OK); this.add(Font_Family_Name); this.add(Font_Style1); this.add(Font_Style2); this.add(Font_Style3); OK.addActionListener(this); Font_Style1.addActionListener(this); Font_Style2.addActionListener(this); Font_Style3.addActionListener(this); } public void start() {} public void stop() {} public void paint(Graphics g) { g.clearRect(50,50,500,300); g.draw3DRect(50,50,500,300,false); g.setFont(new Font(s,i,30)); g.setColor(Color.BLUE); g.drawString(jt.getText(),100,100); } public void actionPerformed(ActionEvent e) { if(e.getSource()==Font_Style1) i=Font.PLAIN; if(e.getSource()==Font_Style2) i=Font.BOLD; if(e.getSource()==Font_Style3) { i=Font.ITALIC; int j=Font.BOLD; i=i+j; } if(e.getSource()==Font_Family_Name || e.getSource()==OK) { if(Font_Family_Name.isSelected()) s="Serif"; else s="Tall paul"; } repaint(); } } 

Java允许每个文件使用一个公共类,公共类名称应与文件名相同。 对你来说,你应该创建文件名Appletprac.java

您可以看到此链接为什么Java中的文件名与类名相同?

写一个像这样的html文件:

的test.html

     

将已编译的.class文件放在同一文件夹中,并在cmd中输入appletviewer test.html

如果您的外部类具有public修饰符,则它应该在具有相同类名和.java扩展名的文件中。 这是一个简单的java约定,用于构造文件系统中的类和包。