我有一个游戏程序,我想在主菜单中添加一个标题。我添加了图形并添加了要显示的文本字符串,但它不会显示。我添加了一条评论,问题可能是。
我的主代码:
package Main;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game {
public static void main(String[] args) {
JFrame frame = new JFrame("Tennis Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Menu graphics = new Menu();
frame.add(graphics);
frame.setLayout(null);
final JButton b = new JButton("Play");
b.setFocusPainted(false);
b.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));
b.setBounds(110, 100, 80, 40);
b.setForeground(Color.BLACK);
b.addMouseListener(new java.awt.event.MouseAdapter(){
public void mouseEntered(MouseEvent evt) {
b.setForeground(Color.RED);
}
public void mouseExited(MouseEvent evt) {
b.setForeground(Color.BLACK);
}
});
frame.add(b);
frame.setSize(300,400);
frame.setVisible(true);
}
}
我的菜单代码,标题为:
package Main;
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;
public class Menu extends JPanel {
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.yellow);
g.setFont(new Font("Arial", Font.BOLD, 30));
g.setColor(Color.BLACK);
g.drawString("TENNIS GAME", 40, 60);
}
}
当您使用frame.setLayout(null)
时,子组件不会自动调整大小,您需要自己动手:添加graphics.setBounds(0, 0, 300, 100);