1

I have a game program and I want to add a title to my main menu. I added the graphics and added a string of text to be displayed but it won't show up. I added a comment were the problem may be.

My main code:

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




 }
 }

My menu code with the title:

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


}


}
  • I don't see the comment in your code where you say the problem lies. Doesn't `frame.setTitle("Name of the menu");` work? – WonderWorld Feb 28 '15 at 20:14
  • 1
    You shouldn't be using `null` layouts when working with Swing. That is probably what is causing the issue. Swing has a variety of layout managers that you can work with. – TNT Feb 28 '15 at 20:24
  • Also i would use `JMenu` instead of `Menu` since you are also using `JFrame`. Check out this tutorial about How to use Menu's, might be helpfull. http://docs.oracle.com/javase/tutorial/uiswing/components/menu.html – WonderWorld Feb 28 '15 at 20:29

1 Answers1

-1

When you use frame.setLayout(null), sub-Components aren't automatically sized, you'll need to do it yourself: Add graphics.setBounds(0, 0, 300, 100);

Adrian Leonhard
  • 7,040
  • 2
  • 24
  • 38
  • Java GUIs have to work on different OS', screen size, screen resolution etc. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Feb 28 '15 at 23:37