我有以下代码。
package lab1;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.plaf.metal.DefaultMetalTheme;
import javax.swing.plaf.metal.MetalLookAndFeel;
public class Snake extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel jp;
private JFrame jf;
public Snake() {
initlookandfeel();
jf = new JFrame();
jf.setVisible(true);
jf.setBounds(200, 200, 500, 500);
jp = new JPanel();
jp.setVisible(true);
jf.setContentPane(jp);
jp.setLayout(null);
jp.setBounds(0, 0, jf.getWidth(), jf.getHeight());
jf.setTitle("NIRAV KAMANI");
jp.repaint();
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
Snake sn = new Snake();
}
public void paint(Graphics g) {
g.setColor(Color.red);
g.drawString("NIRAV KAMANI", 50, 50);
}
public void initlookandfeel() {
String lookandfeel;
lookandfeel = "javax.swing.plaf.metal.MetalLookAndFeel";
try {
UIManager.setLookAndFeel(lookandfeel);
MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme());
UIManager.setLookAndFeel(new MetalLookAndFeel());
} catch (Exception e) {
System.out.println("" + e);
}
}
}
我知道我犯了一些与 JPanel 或 JFrame 相关的错误。但我无法理解我在做什么错误?为什么?我认为有一个层被另一个覆盖,所以字符串不会显示。但是如果我想在 JPanel 中显示字符串,我必须做什么?