Reputation: 13
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
Reputation: 285430
setLayout(null)
and setBounds(...)
as that will lead to an extremely difficult to create and adjust GUI. Learn and use the layout managers.this
, the Screen JPanel but first give it a decent layout manager, such as a GridLayout,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