Adding a public class that extends JPanel to JFrame - java

Basically as the title says, I'm having a bit of an issue working out how to add a class that extends JPanel to a JFrame.
I've looked on here and on other forums, but no answer that I've tried out has work.
I've also got 3 separate files, my main.java my frame.java and panel.java (abbreviated for convenience)
Apparently it's good practice to have public classes in different files(?) or so I've been told!
I'd appreciate any help on how to actually add the JPanel to the JFrame, even just a link to some documentation I may not have seen. Also I'm open to any constructive criticisms that anyone has about the way I've entered/laid out my code.
Thanks!
main.java
public class MyGuiAttempt {
public static void main(String[] args) {
new mainFrame();
}
}
frame.java
public class mainFrame extends JFrame {
public mainFrame() {
setVisible(true);
setTitle("My Game");
setSize(800, 600);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(mainScreenMenu); //This is where I'm clearly going wrong.
}
}
panel.java
public class mainScreenMenu extends JPanel {
public mainScreenMenu() {
JLabel homeMenuBackground = new JLabel(new ImageIcon("images/my_image.jpg"));
setPreferredSize(new Dimension(800,600));
add(homeMenuBackground);
setVisible(true);
}
}

You need to create a new instance of your class
add(new mainScreenMenu());

You're confusing classes and objects. JFrame, JPanel and mainScreenMenu (which should be named MainScreenMenu) are classes. To have a concrete frame, you need to create an object of type JFrame. To have a concrete panel of type MainScreenMenu, you need to create an object of type MainScreenMenu:
MainScreenMenu theMenu = new MainScreenMenu();
add(theMenu);

Related

JButton not appearing on JFrame

Following is the code in which the jbutton is not showing on the frame. I have also set visible to true. Even then the button doesn't appear.
class gui{
public static void main(String args[]){
layoutBorder lb=new layoutBorder("check");
}
}
class layoutBorder extends JFrame{
layoutBorder(String title){
super(title);
setLayout(null);
setSize(200, 200);
JButton jb=new JButton("JB");
add(jb);
setVisible(true);
}
}
Don't use a null layout!!!
Swing was designed to be used with layout managers.
Read the section from the Swing tutorial o Layout Managers for more information.
I suggest you download the working examples and play with them. The example will also show you how to better structure your code. Maybe start with the code from How to Use Buttons, which has a simple example that adds 3 buttons to a panel and then the panel to the frame.
Also, class names should start with an upper case character. Have you even seen a class in the API that doesn't??? Learn Java conventions and follow them.
camickr is right. Also, always use the AWT event dispatching thread when an application thread needs to update the GUI.
import javax.swing.*;
import java.awt.*;
import java.lang.*;
public class Gui {
public static void main(String args[]) {
SwingUtilities.invokeLater(() -> {
MyFrame frame = new MyFrame("check");
});
}
}
class MyFrame extends JFrame {
MyFrame(String title){
super(title);
setLayout(new BorderLayout());
setSize(200, 200);
JButton jb = new JButton("JB");
add(jb);
setVisible(true);
}
}
If you want null layouts then you need to set sizes and position by yourself. Using the setLocation and setSize methods.
class gui{
public static void main(String args[]){
layoutBorder lb=new layoutBorder("check");
}
}
class layoutBorder extends JFrame{
layoutBorder(String title){
super(title);
setLayout(null);
setSize(200, 200);
JButton jb=new JButton("JB");
jb.setLocation(10, 10);
jb.setSize(40, 30);
add(jb);
setVisible(true);
}
}

Undefined Type for JFrame

so i was getting a error in Eclipse for my java program to make a new JFrame and i couldnt quiet figure out my it wouldnt load the correct data to set it to be visable and to set the title, location, size, and what it should do when someone closes the JFrame so id like some help if i could please
import javax.swing.*;
import java.awt.*;
public class JFrame
{
public static void main(String[] args)
{
JFrame JF = new JFrame();
JF.setTitle("Test");
JF.setSize(400, 200);
JF.setLocation(200, 300);
JF.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
JF.setVisible(true);
}
}
Thanks for the help in advance
You named your own class JFrame, thus hiding the standard javax.swing.JFrame class.
Choose another name for your class.

Java JPanel Drawing rectangle drawRect(); what to do next, or which component of Java will suit better?

I have drawn a rectangle using a JPanel
My main objective is to store my Requirement Engineering chapter into a JPanel or a JFrame
import java.awt.*;
import javax.swing.*;
class RequirementEngineering extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent();
g.drawRect(10,10,60,60);
g2.drawString("Feasibility study", 20, 20); //rectangle is my main objective, I will look after the string later
}
public static void main(String[] args)
{
}
}
how do I display the JPanel? I know, JApplet doesn't require a main method, but how do we represent JPanel in main() method?
I have this doubt for long, and other posts are confusing me further, Could I have a direct question
My main question being "How to add JFrame to JPanel" pertaining my current coding
thanks in advance
see if you need to use a Window based app, you can do as:
JPanel customPanel = new RequirementEngineering();
JFrame frame = new JFrame("my window");
frame.getContentPane().add(customPanel );
frame.setSize(300,200);
frame.setVisible(true);
If you need in Applet,
public class JAppletExample extends JApplet {
public void init() {
Container content = getContentPane();
JPanel customPanel = new RequirementEngineering();
content.add(customPanel );
}
And you can run it using appletViewer or in any Web Browser such as IE.

Java actionlistener doesn't work

I just started learning Java 1 week ago, and I'm a 100% totally beginner. In this code, I can't seem to be able to put an actionlistener/get one to work. I don't even know where/how/in what way to put it, despite reading dozens of tutorials. I've created a JFrame with a JPanel in it, and on the JPanel there's a button. So far so good (and working). But then, I want it to be so that if the button is clicked, another button appears. Thank you sooo much in advance!
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class Skeleton extends JFrame implements ActionListener {
public static void main(String[] args) {
//------------------------------------------------
JFrame frame = new JFrame("Skeleton");
JPanel panel = new JPanel();
frame.setContentPane(panel);
frame.setSize(600,600);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JButton button = new JButton("This is a button.");
JButton button2 = new JButton("Hello");
panel.setLayout(null);
button.setBounds(20,20,200,25);
button2.setBounds(20,70,200,25);
panel.add(button);
//-------------------------------------------
button.addMouseListener(this);
}
public void ActionPerformed(ActionEvent e) {
System.out.println("Hello");
}
}
i will give you some advice
1) Don't implement ActionListener in top classes, use anonymous classes or private classes instead.
Example :
Anonymous class (also call Swing Actions)
myComponent.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
//code here
}
})
or
//inner class
public class Skeleton{
// in some part
private class MyActionListener implements ActionListener{
public void actionPerformed(ActionEvent evt){
//code here
}
}
}
2) Your code won't compile cause you are not implementing ActionListener interface
public void actionPerformed(ActionEvent evt) is the signature.
You have to addActionListener to your component
button.addActionListener(this);
3) Don't use null layout, cause you'll have a lot of problem if you want to add more components or resize windows cause you have to setBounds manually and it will be frustrating instead use [Layout Manager][1].
4) Try to not extends JFrame if is not necesary instead have a reference in your class, for example.
public class Skeleton{
private JFrame frame;
}
You need to add the actionlistener.
Register an instance of the event handler class as a listener on one or more components. For example:
yourdesiredcomponent.addActionListener(this);
For more details check the doc

Java JFrame Not Displayed (Just Titlebar)

I know this is something very simple, but as a complete Java newbie I'm missing it and someone pointing it out would be infinitely helpful. I've stared at the screen and moved things around and still nothing.
Screenshot:
http://i.imgur.com/dwH60.png
This is all that comes up when this is run.
fullGUI.java:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
public class fullGUI extends JFrame
{
JFrame frame = new JFrame(); //creates frame
public fullGUI() // constructor
{
//setLayout(new BorderLayout());
//add(new shipGrid(), BorderLayout.NORTH);
//add(new shipGrid(), BorderLayout.NORTH);
add(new JRadioButton("Horizontal"), BorderLayout.WEST);
add(new JRadioButton("Vertical"), BorderLayout.WEST);
add(new JTextArea("Instructions to player will go here"), BorderLayout.CENTER);
frame.setSize(400,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Battleship!");
frame.pack(); //sets appropriate size for frame
frame.setVisible(true);
}
}
...called by...
test.java
public class test
{
public static void main(String[] args)
{
new fullGUI();
}
}
name classes in Java from a capital letter
FullGUI already extends JFrame, so no need to create another JFrame inside it
call getContentPane.add() to add to JFrame
use SwingUtilities.invokeLater
So overall something like this
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
public class FullGUI extends JFrame
{
public FullGUI() // constructor
{
getContentPane().add(new JRadioButton("Horizontal"), BorderLayout.WEST);
getContentPane().add(new JRadioButton("Vertical"), BorderLayout.WEST);
getContentPane().add(new JTextArea("Instructions to player will go here"), BorderLayout.CENTER);
setSize(400,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Battleship!");
pack(); //sets appropriate size for frame
setVisible(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new FillGU();
}
});
}
Problem is that you are extending JFrame in your class and creating new object "frame". You're adding components such as JRadioButton or JTextArea into fullGUI and other settings of the JFrame are applicable to frame object. It's up to you which approach you're going to choose, but pick one of them. You can extend JFrame and your class will be a child of JFrame which means you can call all public or protected methods from parent class, no need to create new instance of JFrame. Other way is to not extend JFrame and you have to create new JFrame object instead.
frame.pack() is causing your JFrame to resize according to its contents.
If you have frame.setSize(400,600), even if you don't add anything to its content pane,
the frame will be displayed with size 400x600.
But when you call frame.pack(), the frame will resize. In your case, your frame's content pane does not contain anything. Therefore the pack() method resizes it to only your title bar.
As Nikolay Kuznetsov said in earlier answer, you have extended Jframe in fullGUI so no need to create new Jframe in that class, because every instance of FullGUI will be a new frame.
With you code what happened is that you have created a Frame, say frame1 and instance of fullGUI(In main Method) say frame2, these are two different frames. In the Constructor you have added those controls to the frame2 (add()==this.add()) and said frame1.setvisible(true);
Adding controls to one frame and displaying altogether different frame is the reason why you were unable to see anything on output scree though you would have maximized the screen.

Categories

Resources