Java CardLayout not displaying - java

I have a game that already runs and works and I want to add a title screen to it. I'm trying to add a CardLayout for easy switching between game and titlescreen. My current issue is that nothing is being displayed. Here is an image: http://i.imgur.com/kVIXYQ7.png . I simply get a blank JPanel when I run it. What am I doing wrong?
public class UI
{
private static JPanel cards;
private static CardLayout cardLayout;
public static void main(String args[])
{new UI();}
public UI()
{
JFrame frame = new JFrame("Scrolling Shooter");
frame.setResizable(false);
Toolkit tk = Toolkit.getDefaultToolkit();
int width = ((int) tk.getScreenSize().getWidth());
int height = ((int) tk.getScreenSize().getHeight());
frame.setSize(width, height);
TitleScreen title = new TitleScreen(frame);
ScrollingShooter game = new ScrollingShooter(frame);
cards = new JPanel(new CardLayout());
cards.add(title, "title");
cards.add(game, "game");
cards.setOpaque(true);
frame.getContentPane().add(cards);
cardLayout = (CardLayout) cards.getLayout();
cardLayout.first(cards);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
/**
* Switches to the next screen
*/
public static void nextScreen()
{cardLayout.next(cards);}
/**
* Returns to the first screen
*/
public static void firstScreen()
{cardLayout.first(cards);}
}

You haven't added Cards to anything.
Try adding Cards to frame and then make the frame visible
For example...
JFrame frame = new JFrame("Scrolling Shooter");
TitleScreen title = new TitleScreen(frame);
ScrollingShooter game = new ScrollingShooter(frame);
cards = new JPanel(new CardLayout());
cards.add(title, "title");
cards.add(game, "game");
cards.setOpaque(true);
cardLayout = (CardLayout) cards.getLayout();
cardLayout.first(cards);
frame.add(cards);
//...
frame.setResizable(false);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
FYI: You should come setResizable before setting the frame size as setResizable can change the frames border insets

Related

Panel is not showing on frame in Java Swing

I've made a HallOfFame class which is subclass of JPanel and i want to add a label writing "Hall OF Fame" on this panel.In the MainWindow class (frame) i have added the HallOfFame (Panel) to the content pane but nothing shows up. The same happens with every component i am trying to add on the frame (MainWindow) except the top (placed North with the BorderLayout) panel with 3 buttons.
public class HallOfFame extends JPanel{
JLabel hofLabel;
public HallOfFame() {
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setBorder(new LineBorder(Color.GRAY, 1));
this.setAlignmentX(CENTER_ALIGNMENT);
hofLabel = new JLabel("Hall OF Fame");
add(hofLabel);
}
}
public class MainWindow extends JFrame{
/*Size of main window*/
public static final Dimension winSize = new Dimension(1200, 800);
public static final int TOP_HEIGHT = 80;
public static final int PLAYER_WIDTH = 300;
private GameBoard gameBoard;
private HallOfFame hallOfFame;
private BannerPanel bannerPanel;
private PlayerPanel playerPanel;
public MainWindow() {
//Initializing the frame.
Container c = this.getContentPane();
c.setPreferredSize(winSize);
this.setTitle("TucTacToe");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*Hall of fame*/
hallOfFame = new HallOfFame();
/*GameBoard*/
gameBoard = new GameBoard();
/*Banner Panel*/
bannerPanel = new BannerPanel();
/*PlayerPanel*/
playerPanel = new PlayerPanel();
/*Adding the components to the window*/
c.add(bannerPanel, BorderLayout.NORTH);
c.add(hallOfFame, BorderLayout.CENTER);
//add(gameBoard, BorderLayout.CENTER);
c.add(playerPanel);
this.pack();
this.setVisible(true);//setting visible the frame.
}
}
Here is the window of the project
c.add(hallOfFame, BorderLayout.CENTER);
c.add(playerPanel)
You are adding the "playerPanel" to the CENTER of the frame. When you don't specify the constraint it defaults to the CENTER when using BorderLayout.
Only the last component added will be visible. So it appears your playerPanel doesn't have any components added to it.
For a simple test just use:
c.add(hallOfFame, BorderLayout.CENTER);
//c.add(playerPanel)
Now you should see the hallOfFame panel.

How do I make this GUI?

I've been tasked to make a GUI in Java by using "swing" which is an exact replica of the image below. It doesn't have to have any functionality, it's just for looks. However, there's this one part of this image I can't find or make, which is the top right corner "gender" box. How do I make that transparent-looking box that has an outline? Please help me out, and thank you!
That is called a TitledBorder.
Example:
public class SwingTester {
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("Swing Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(JFrame frame){
//Create a border
Border blackline = BorderFactory.createTitledBorder("Title");
JPanel panel = new JPanel();
LayoutManager layout = new FlowLayout();
panel.setLayout(layout);
JPanel panel1 = new JPanel();
String spaces = " ";
panel1.add(new JLabel(spaces + "Title border to JPanel" + spaces));
panel1.setBorder(blackline);
panel.add(panel1);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
For your case, update this line with your own title:
Border blackline = BorderFactory.createTitledBorder("Title"); //change to gender
Source: https://www.tutorialspoint.com/swingexamples/add_title_to_border_panel.htm

Java Swing 13 GridLayout does not exist?

I can't seem to get a swing GridLayout to work in java 13. The error is that GridLayout cannot be resolved to a type in the following code:
import javax.swing.*;
public class GameFrame extends JFrame {
public static final void NewFrame() {
new GameFrame();
}
public GameFrame() {
this.setSize(1600, 800);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("The Game");
this.setVisible(true);
this.setResizable(false);
JPanel MainPanel = new JPanel();
MainPanel.setLayout(new GridLayout());
}
}
The issue is caused by the class not being imported.
import java.awt.GridLayout;
Since it is not in the swing package it doesn't get imported with the star import.
Also it is better to use explicit imports.
This might be related to the fact that panel is empty. Try running this code and it should work.
public class GridLayoutTest {
private static JButton[] arrayBtn;
public static void main(String[] args) {
// the frame that contains the components
JFrame frame = new JFrame("GridLayoutTest from JCG");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set the size of the frame
frame.setSize(350, 350);
// set the rows and cols of the grid, as well the distances between them
GridLayout grid = new GridLayout(5, 3, 10, 10);
// what layout we want to use for our frame
frame.setLayout(grid);
// add a text field with a specified text to the frame
JTextArea text = new JTextArea();
text.setText("Result");
text.setEditable(false);
frame.add(text);
// add buttons to the frame
frame.add(new JButton("+"));
frame.add(new JButton("="));
arrayBtn = new JButton[10];
// add JButtons dynamically
for(int i=0; i < arrayBtn.length; i++) {
arrayBtn[i] = new JButton(Integer.toString(i));
frame.add(arrayBtn[i]);
}
frame.setVisible(true);
}
}

JFrame strange white stripe on top of background image

I have a strange white stripe (see below) appearing on top of my background image. The code is quite simple. How to get rid of the white stripe?
//Graphics side of the game
public class GUI extends JFrame {
private final int larghezza = 1280;
private final int altezza = 720;
private final String name = "Sette e Mezzo";
private final ImageIcon backgroundImage;
private JLabel bgImageLabel;
private JPanel backgroundPanel, borderLayoutPanel, topGridLayout, botGridLayout;
public GUI () {
backgroundImage = new ImageIcon ("assets/background.png");
bgImageLabel = new JLabel (backgroundImage);
//Panels
borderLayoutPanel = new JPanel (new BorderLayout ());
topGridLayout = new JPanel (new GridLayout (1, 3));
botGridLayout = new JPanel (new GridLayout (1, 3));
backgroundPanel = new JPanel ();
backgroundPanel.add (bgImageLabel);
//Frame
this.setName (name);
this.setPreferredSize (new Dimension(larghezza, altezza));
this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
//Adding to frame and panels
borderLayoutPanel.add (topGridLayout, BorderLayout.NORTH);
borderLayoutPanel.add (botGridLayout, BorderLayout.SOUTH);
this.add (borderLayoutPanel);
this.add (backgroundPanel);
this.pack ();
this.setLocationRelativeTo (null);
this.setVisible (true);
}
}
Don't use setPreferredSize() when you really mean to override getPreferredSize(). In this case, the specified Dimension probably doesn't quite match the size of "assets/background.png". This allows some portion of another panel to show, perhaps backgroundPanel.
In the example below,
The default layout of JPanel is FlowLayout, which has a "default 5-unit horizontal and vertical gap." A touch of Color.blue makes the gap stand out; resize the enclosing frame to see the behavior.
As the default layout of JFrame is BorderLayout, you may not need borderLayoutPanel at all.
Because the two GridLayout panels have no content, they remain invisible. Add content to each or override getPreferredSize() in each to see the effect.
Construct and manipulate Swing GUI objects only on the event dispatch thread.
import java.awt.*;
import java.net.URL;
import javax.swing.*;
public class GUI {
private static final String TITLE = "Title";
private static ImageIcon IMAGE_ICON;
private void display() {
//Panels
JPanel topGridLayout = new JPanel(new GridLayout(1, 3));
JPanel botGridLayout = new JPanel(new GridLayout(1, 3));
JPanel backgroundPanel = new JPanel();
backgroundPanel.setBackground(Color.blue);
backgroundPanel.add(new JLabel(IMAGE_ICON));
//Frame
JFrame f = new JFrame(TITLE);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add components
f.add(topGridLayout, BorderLayout.NORTH);
f.add(backgroundPanel);
f.add(botGridLayout, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) throws Exception {
IMAGE_ICON = new ImageIcon(new URL("http://i.imgur.com/mowekvC.jpg"));
EventQueue.invokeLater(new GUI()::display);
}
}

How can I align elements in JPanels / JFrames?

I'm completely new to using the GUI in java, so I'm having a bit of trouble figuring out how to align everything that I need to. I have to panels in my JFrame that I need to align (One to the left, one to the right) and a few buttons in one of the panels that I need to be centered in the panel. Here is my code.
package application;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.nio.*;
import java.util.*;
public class Main extends JPanel
{
public static void main(String[] args)
{
//set the ui to the native OS
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e)
{
}
JFrame frame = new JFrame("Application Name");
Menu menu = new Menu();
JPanel iconPanel = new JPanel();
final JPanel grid = new JPanel(new FlowLayout());
JButton firewallButton = new JButton("Firewall");
JButton networkButton = new JButton("Network");
JButton printerButton = new JButton("Printer");
int iconPanelSizeX;
int iconPanelSizeY;
int gridSizeX;
int gridSizeY;
int gridPosition;
//frame setting
frame.setSize(800, 600);
frame.setMinimumSize(new Dimension(800, 600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
//add grid and iconPanel JPanels to the frame
frame.add(iconPanel);
iconPanel.add(firewallButton);
iconPanel.add(networkButton);
iconPanel.add(printerButton);
frame.add(grid);
//iconPanel settings
iconPanel.setBorder(BorderFactory.createLoweredSoftBevelBorder());
iconPanel.setBackground(Color.gray);
iconPanel.setLayout(new FlowLayout());
iconPanel.setSize(new Dimension(100, 600));
iconPanel.setVisible(true);
//grid setting
grid.setBackground(Color.red);
grid.setSize(new Dimension(700, 600));
grid.setVisible(true);
//this is for resizing components when the user resizes the window
int counter = 0;
while(counter == 0)
{
firewallButton.setSize(new Dimension(iconPanel.getWidth(), 50));
networkButton.setSize(new Dimension(iconPanel.getWidth(), 50));
printerButton.setSize(new Dimension(iconPanel.getWidth(), 50));
iconPanelSizeX = frame.getWidth() / 10;
iconPanelSizeY = frame.getHeight();
gridSizeX = (frame.getWidth() / 10) * 9;
gridSizeY = frame.getHeight();
iconPanel.setSize(new Dimension(iconPanelSizeX, iconPanelSizeY));
grid.setSize(new Dimension(gridSizeX, gridSizeY));
}
}
}
As you can see, the second JPanel (grid) doesn't line up with the right side of the frame, and the buttons inside iconTray don't center either. I realize these are both probably simple layout fixes, but I have no clue where to start.
For simple splitting of JFrame you can use GridLayout with 1 row and 2 colums.
frame.setLayout(new GridLayout(1,2,3,3)); //3,3 are gaps
frame.add(grid);
frame.add(iconPanel);
For centering components in panels you can use FlowLayout which is by default set on JPanels:
Doing it manualy:
grid.setLayout(new FlowLayout()); //Centered components
grid.setLayout(new FlowLayout(FlowLayout.LEFT,3,3)); //Components aligned to left
grid.setLayout(new FlowLayout(FlowLayout.RIGHT,3,3)); //Components aligned to right
This is how it looks:
Also, few observations:
Never call setXXXSize() methods for your components;
Try to avoid calling setSize(); for JFrame, call pack(); instead;
Call setVisible(true); in the end of code;
All your huge code can be "stripped" to this:
import javax.swing.*;
import java.awt.*;
public class Main extends JPanel
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Application Name");
JPanel iconPanel = new JPanel();
JPanel grid = new JPanel(new FlowLayout());
JButton firewallButton = new JButton("Firewall");
JButton networkButton = new JButton("Network");
JButton printerButton = new JButton("Printer");
frame.add(iconPanel);
iconPanel.add(firewallButton);
iconPanel.add(networkButton);
iconPanel.add(printerButton);
grid.setBackground(Color.GREEN);
frame.setLayout(new GridLayout(1,2,3,3));
frame.add(grid);
frame.add(iconPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
how to align buttons vertically?
This example uses a vertical Box in the WEST area of the frame's default BorderLayout:
import java.awt.*;
import javax.swing.*;
/** #see http://stackoverflow.com/a/14927280/230513 */
public class Main {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
display();
}
});
}
private static void display() throws HeadlessException {
JFrame frame = new JFrame("Application Name");
JButton firewallButton = new JButton("Firewall");
JButton networkButton = new JButton("Network");
JButton printerButton = new JButton("Printer");
//iconPanel settings
Box iconPanel = new Box(BoxLayout.Y_AXIS);
iconPanel.add(firewallButton);
iconPanel.add(networkButton);
iconPanel.add(printerButton);
iconPanel.setBackground(Color.gray);
iconPanel.setVisible(true);
frame.add(iconPanel, BorderLayout.WEST);
//grid setting
JPanel grid = new JPanel() {
#Override
// arbitrary placeholder size
public Dimension getPreferredSize() {
return new Dimension(320, 230);
}
};
grid.setBackground(Color.red);
frame.add(grid, BorderLayout.CENTER);
//frame setting
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
I suggest you take some time going through A Visual Guide to Layout Managers. This will help you become familiar with the layout managers which are available with the Standard API. It takes some experience and hard work to figure out which of these is the right tool to get the exact look you want. Once you become comfortable with what is available from the Standard API, you should also look around for third-party Layout Manager APIs which provide other options.
I have to panels in my JFrame that I need to align (One to the left,
one to the right) and a few buttons in one of the panels that I need
to be centered in the panel. Here is my code.
I realize these are both probably simple layout fixes, but I have no
clue where to start.
Use more complex layout than simple FlowLayout which you actually using. I suggest to you use
GridBagLayout
BoxLayout
Check references here

Categories