Swing: Start second JPanel, when the first JPanel is clicked - java

I'm writing a simple java game and I'm facing this problem:
My different layouts are in different JPanels (1 JPanel for the welcoming page, where I have to press 'start game' and another one with the actuall functionallity)
I start the game from a JFrame
import javax.swing.JFrame;
public class RType extends JFrame {
public RType() {
add(new Welcome());//first panel
add(new Board());//panel with the game
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(100, 100);
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new RType();
}
}
obviuosly, this launches the second panel right after the first, and I cant see the first one.
I've tried some stuff, trying to invoke the second panel in the main method, when the first panel is clicked that way:
RType rt=new RType();
rt.add(new Board()); //in this case add(new Board()); is removed from constructor
but it's doing nothing.
how can I solve it?

As #nachokk has said, you should be using a CardLayout instead. It lets you do things like tabs in a browser, but you don't need to make the tabs visible for your game if you don't want to. You make your welcome "card" visible at first, then when the user clicks you switch to the Board "card".

I don't recommend to add directly to the JFrame components, instead use another container as JPanel . JFrame default layout is BorderLayout, when you add in the way you are adding it always put in the center.
Make something like this:
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new CardLayout());
mainPanel.add(new Welcome(), "Welcome");
mainPanel.add(new Board(),"Board");
frame.add(mainPanel);
Here is a tutorial How to use CardLayout

on first panel of welcome add a button, and apply actionperformed like
JButton myButton = new JButton("Add Component ");
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.remove(welcome);
frame.add(Board, BorderLayout.CENTER);
frame.revalidate();
frame.repaint();
}
});

By default, both panels will fill up the entire Frame's area. To fix this, you will need to use another layout, such as a GridLayout to structure the areas in which the panels will take up the Frame's area.
You can also go with no layout to hard code the pixel values of where you want the panels to fit in your frame.
EDIT: Based on what you're looking to do, the CardLayout is probably what you'll want to use for your Frame's layout.

Related

Why is JPanel not adding any component at Runtime?

public class Create_JFrame extends JFrame{
public Create_JFrame(){
//Create a Frame
JFrame Frame = new JFrame("Bla-Bla");
JPanel Panel_1 = new JPanel();
JPanel Panel_2 = new JPanel();
JButton Option_1 = new JButton("Option-1");
//Layout management for Panels
Frame.getContentPane().add(BorderLayout.WEST, Panel_1);
//Add button to Panel
Panel_1.add(Option_1);
//Registering Listeners for all my buttons
Option_1.addActionListener(new ListenerForRadioButton(Panel_2));
//Make the frame visible
Frame.setSize(500, 300);
Frame.setVisible(true);
}//end of Main
}//end of Class
public class ListenerForRadioButton implements ActionListener{
JPanel Panel_2;
JButton browse = new JButton("Browse");
//Constructor, will be used to get parameters from Parent methods
public ListenerForRadioButton(JPanel Panel){
Panel_2 = Panel;
}
//Overridden function, will be used for calling my 'core code' when user clicks on button.
public void actionPerformed(ActionEvent event){
Panel_2.add(browse);
System.out.println("My listener is called");
}//end of method
}//end of class
Problem Statement:
I have 2 JPanel components in a a given JFrame. Panel_1 is having a Option_1 JButton. When user clicks on that I am expecting my code to add a JButton 'browse' in Panel_2 at runtime.
Runtime Output:
System is not adding any JButton in Panel_2. However, I see my debug message in output, indicating that system was successful in identifying user's click action on 'option-1'.
Question:
Why is JPanel not adding any component at Runtime?
Panel_2.add(browse);
Panel_2.revalidate();
adding a 'revalidate' will solve the problem.
There are some reasons. but:
usually it's because of using unsuitable LayoutManager.
sometimes it's because of adding the JPanel to it's root component in worng way. which any operation (add, remove,...) works but is not visible.
you must refresh the view when you make some changes on it, like adding or removing components to/from it.
try to use Panel_2.revalidate() to refresh.
if it doesn't work properly use it with Panel_2.repaint() method.
see Java Swing revalidate() vs repaint()
see Difference between validate(), revalidate() and invalidate() in Swing GUI
using setSize twice for your jframe is another way.
Frame.setSize(498, 300); then Frame.setSize(500, 300);

Problems with BorderLayout() in Java

I've tried a lot of different ways, but I will explain two and what was happening (no error messages or anything, just not showing up like they should or just not showing up at all):
First, I created a JPanel called layout and set it as a BorderLayout. Here is a snippet of how I made it look:
JPanel layout = new JPanel();
layout.setLayout(new BorderLayout());
colorChoice = new JLabel("Choose your color: ");
layout.add(colorChoice, BorderLayout.NORTH);
colorBox = new JComboBox(fireworkColors);
colorBox.addActionListener(this);
layout.add(colorBox, BorderLayout.NORTH);
In this scenario what happens is they don't show up at all. It just continues on with whatever else I added.
So then I just tried setLayout(new BorderLayout()); Here is a snippet of that code:
setLayout(new BorderLayout());
colorChoice = new JLabel("Choose your color: ");
add(colorChoice, BorderLayout.NORTH);
colorBox = new JComboBox(fireworkColors);
colorBox.addActionListener(this);
add(colorBox, BorderLayout.NORTH);
In this scenario they are added, however, the width takes up the entire width of the frame and the textfield (not shown in the snippet) takes up basically everything else.
Here is what I have tried:
setPreferredSize() & setSize()
Is there something else that I am missing? Thank you.
I also should note that this is a separate class and there is no main in this class. I only say this because I've extended JPanel instead of JFrame. I've seen some people extend JFrame and use JFrame, but I haven't tried it yet.
You created a JPanel, but didn't add it to any container. It won't be visible until it is added to something (a JFrame, or another panel that is in a frame somewhere up the hierarhcy)
You added two components to the same position in the BorderLayout. The last one added is the one that will occupy that position.
Update:
You do not need to extend JFrame. I never do, instead I always extend JPanel. This makes my custom components more flexible: they can be added in another panel, or they can be added to a frame.
So, to demonstrate the problem I will make an entire, small, program:
public class BadGui
{
public static void main(String[] argv)
{
final JFrame frame = new JFrame("Hello World");
final JPanel panel = new JPanel();
panel.add(new JLabel("Hello"), BorderLayout.NORTH);
panel.add(new JLabel("World"), BorderLayout.SOUTH);
frame.setVisible(true);
}
}
In this program I created a panel, but did not add it to anything so it never becomes visible.
In the next program I will fix it by adding the panel to the frame.
public class FixedGui
{
public static void main(String[] argv)
{
final JFrame frame = new JFrame("Hello World");
final JPanel panel = new JPanel();
panel.add(new JLabel("Hello"), BorderLayout.NORTH);
panel.add(new JLabel("World"), BorderLayout.SOUTH);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
Note that in both of these, when I added something to the panel, I chose different layout parameters (one label I put in 'North' and the other in 'South').
Here is an example of a JPanel with a BorderLayout that adds a JPanel with a button and label to the "North"
public class Frames extends JFrame
{
public Frames()
{
JPanel homePanel = new JPanel(new BorderLayout());
JPanel northContainerPanel = new JPanel(new FlowLayout());
JButton yourBtn = new JButton("I Do Nothing");
JLabel yourLabel = new JLabel("I Say Stuff");
homePanel.add(northContainerPanel, BorderLayout.NORTH);
northContainerPanel.add(yourBtn);
northContainerPanel.add(yourLabel);
add(homePanel);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setTitle("Cool Stuff");
pack();
setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(Frames::new);
}
}
The below suggestion is assuming that your extending JFrame.
Testing
First of all, without seeing everything, theres always a numerous amount of things you can try.
First off, after you load everything, try adding this in (Again, assuming your extending JFrame:
revalidate();
repaint();
I add this into my own Swing projects all the time, as it refreshes and checks to see that everything is on the frame.
If that doesn't work, make sure that all your JComponent's are added to your JPanel, and ONLY your JPanel is on your JFrame. Your JFrame cannot sort everything out; the JPanel does that.
JPanel window = new JPanel();
JButton button = new JButton("Press me");
add(window);
window.add(button); // Notice how it's the JPanel that holds my components.
One thing though, you still add your JMenu's and what-not through your JFrame, not your JPanel.

Multiple JPanels in one JFrame not showing top panel

So I'm writing a program in which I wish to have a single JFrame containing a JPanel header in a separate colour and directly underneath have a grid of buttons in a separate JPanel. So far my program works perfectly except for the fact that the header String isn't showing up in the NORTH panel. Instead I'm getting a box containing the set background colour with a small grey box in the centre. I'm wondering if I didn't set the size of the panel correctly?
I have heard this can be accomplished using JLabel, but when I tried to do this, it would not show the background colour that I had set.
So, could anyone please show me how to achieve the following either with the JPanel (preferably because I would like to know how it works and what I'm missing) or with JLabel: filling that little grey box in the middle of the header with a String.
Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Example {
public static void main(String[] args) {
// Initialize a panel for the header, and mainGrid which will contain buttons
JPanel panel = new JPanel();
JPanel header = new JPanel();
JPanel mainGrid = new JPanel();
// Initialize the header
DisplayPanel message = new DisplayPanel();
header.setBackground(Color.ORANGE);
header.add(message);
// Initialize the mainGrid panel
mainGrid.setLayout(new GridLayout(2,2,2,2));
mainGrid.add(new JButton("1"));
mainGrid.add(new JButton("2"));
mainGrid.add(new JButton("3"));
mainGrid.add(new JButton("4"));
// Add the two subpanels to the main panel
panel.setLayout(new BorderLayout());
panel.add(header, BorderLayout.NORTH); // The issue is this panel isn't displaying the String created in DisplayPanel
panel.add(mainGrid, BorderLayout.CENTER);
// Add main panel to JFrame
JFrame display = new JFrame("Test");
display.setContentPane(panel);
display.setSize(200,100);
display.setLocation(500,200);
display.setVisible(true);
display.setResizable(false);
display.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private static class DisplayPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("header" , 20, 20); // The string I want to be displayed
}
}
}
I would very much appreciate anyone's help or input as I have only been studying Java for a few months and this is my first post. Thank you in advance.
Also, any general tips on writing that you may have would be greatly appreciated.
I'm wondering if your problem is that you're nesting your message JPanel inside of the header JPanel, and the container header JPanel uses the JPanel default FlowLayout. Thus the component it holds won't expand on its own and will remain trivially small.
Consider either giving the header JPanel a BorderLayout so that message expands inside of it, or
use a JLabel to show your text, not a JPanel's paintComponent method. The JLabel should size itself to be big enough to show its text. If you do this and want it to show a background color, all you have to do is call setOpaque(true) on your JLabel, and you're set.
Actually, if you nest the JLabel, then there's no need to make it opaque. Just do this:
JPanel header = new JPanel();
JPanel mainGrid = new JPanel();
JLabel message = new JLabel("Header", SwingConstants.CENTER);
header.setBackground(Color.ORANGE);
header.setLayout(new BorderLayout());
header.add(message);
I would highly recommend using a GUI builder WYSIWYG IDE, like NetBeans, where you can easily drag and drop components to where they need to be. If you're doing any sort of complex GUI layout, it can be madness (and in my opinion, nonsensical) trying to write and maintain the code.
The layout your trying to implement would be trivial in NetBeans.

JFrame position three buttons one below another in the center

So I would like to have three JButtons all on top of each other, but not to large in width or height either. I am not too familiar with Java's layouts, and to be honest I am not too keen on them. Please view the image a code below to explain to me how, thanks.
package com.aqagame.harrykitchener;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class Main
{
private JButton playGame, playerNames, exitGame;
public Main()
{
JPanel mainCard = new JPanel(new BorderLayout(8, 8));
playGame = new JButton("Play Game");
playerNames = new JButton("Player Names");
exitGame = new JButton("Exit Game");
mainCard.add(playGame, BorderLayout.NORTH);
mainCard.add(playerNames, BorderLayout.CENTER);
mainCard.add(exitGame, BorderLayout.SOUTH);
JFrame window = new JFrame("Harry's AQA game");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(mainCard);
window.setSize(900, 800);
window.setLocationRelativeTo(null);
window.setVisible(true);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Main();
}
});
}
}
Check out the Java Documentation for the different layout managers. I know you're not familiar with them, which is why you should probably start. Once you get used to them there is no end to their benefits. There is a lot of excellent information in the documentation and I am sure you will learn a lot. Personally, I recommend looking at the Box Layout:
Create JPanel that uses a GridLayout and add all the buttons to the panel. The GridLayout will automactially size the buttons to be the same size.
Set the layout manager of your main window to use a GridBagLayout.
add the panel to the main window using the default GridBagConststraints. Then the panel will automatically be centered both horizontally and vertically.
To not use Box or GridBag, I think a combination such as this may work out:
Have main panel (let's call it A) have a BorderLayout
Create another panel (let's call it B), with a FlowLayout, with constructor aligning components to the center
Create another panel (let's call it C), with a GridLayout, 1 column 3 rows
Add each button to a new JPanel with a FlowLayout (1 JPanel per button, so buttons are wrapped by a FlowLayout), and then add each of those JPanels to C
Add C to B
Add B to A (center position)
I think this should cause buttons to be on top of each other with small amount of padding while not being stretched widthwise and while appearing in the center of the screen.

Setting JPanel layout

(Say) I've created a JPanel with three buttons. I want to place the buttons as follows (I've done this using netbeans GUI editor. But I need to write the whole GUI manually).
Can some one show me a way to achieve this.
(In words, I need to place some buttons right aligned, some other left aligned.)
I guess you want the Configure button to be as far to the left as possible, and the ok and cancel grouped together to the right. If so, I would suggest using a BorderLayout and place the Configure button in WEST, and a flow-layout for Ok, Cancel and place that panel in the EAST.
Another option would be to use GridBagLayout and make use of the GridBagConstrant.anchor attribute.
Since you're taking the time to avoid the NetBeans GUI editor, here's a nice example for you :-)
Code below:
import java.awt.BorderLayout;
import javax.swing.*;
public class FrameTestBase {
public static void main(String args[]) {
// Will be left-aligned.
JPanel configurePanel = new JPanel();
configurePanel.add(new JButton("Configure"));
// Will be right-aligned.
JPanel okCancelPanel = new JPanel();
okCancelPanel.add(new JButton("Ok"));
okCancelPanel.add(new JButton("Cancel"));
// The full panel.
JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.add(configurePanel, BorderLayout.WEST);
buttonPanel.add(okCancelPanel, BorderLayout.EAST);
// Show it.
JFrame t = new JFrame("Button Layout Demo");
t.setContentPane(buttonPanel);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.setSize(400, 65);
t.setVisible(true);
}
}

Categories