MSB MSB
MSB MSB

Reputation: 13

Combining class with buttons and frame - GUI

I want to create menu buttons in Screen class and add menu to frame then. I don't know what is wrong with it. How to create buttons in other class and add it to to the frame?

My frame class:

import java.awt.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;


public class Start extends JFrame {

    public static String title = "Bozenka";
    public static Dimension size = new Dimension(700,500);
    public static String backgroundPath = "/home/alpha_coder/Eclipse/Bozenka/images/bg.jpg";

    public Start(){
        setTitle(title);
        setSize(size);
        setLayout(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(null);
        setResizable(false);
        initialization();
    }

    public void initialization(){
        Screen screen = new Screen();
        screen.setBounds(20, 20, 660, 60);
        add(screen);    
        try {
            setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File(backgroundPath)))));      
            setBackground(Color.WHITE);
        } catch (IOException e) {
            System.out.println("Image doesn't exist");
        }

        setVisible(true);

    }

    public static void main(String[] args){
        Start start = new Start();
    }

}

The class where I want to create a menu:

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

public class Screen extends JPanel{

    public JButton test;

    public Screen(){
        setBackground(Color.pink);
        test = new JButton("test");
        test.setBounds(2, 2, 40, 10);
    }


}

Upvotes: 1

Views: 206

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

  1. Most important: get rid of setLayout(null) and setBounds(...) as that will lead to an extremely difficult to create and adjust GUI. Learn and use the layout managers.
  2. Create your JButtons in your new class, Screen
  3. add them to this, the Screen JPanel but first give it a decent layout manager, such as a GridLayout,
  4. In another class, create an instance of your JFrame class and an instance of the Screen object, and add the Screen JPanel to your JFrame's contentPane in whatever desired location you want, be it BorderLayout.CENTER or one of the other locations.

Again, most important: google and study the layout manager tutorial. Here's the link.

Note, a major problem with your current code is that you add your JButton to nothing. It needs to be added to Screen, to this for your code to work in any way.

Upvotes: 4

Related Questions