JPanel didn't show rest of it's component - java

I have frame with a button and a JPanel as I named panel, I want after I clicked the button add an inner panel to my panel. But this but there is a problem with this! because after adding second panel it didn't add any other panel.
Code
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import javax.swing.JTextField;
public class DrawImages extends JFrame{
int i;
public DrawImages() {
JButton btnNewButton = new JButton("New button");
i = 0;
getContentPane().add(btnNewButton, BorderLayout.SOUTH);
setMinimumSize(new Dimension(1000,150));
final JPanel panel = new JPanel();
panel.setSize(995, 145);
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
final JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(0, 0, 46, 14);
panel.add(lblNewLabel);
btnNewButton.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent paramActionEvent) {
JPanel panel_1 = new JPanel();
//getContentPane().add(panel_1, BorderLayout.NORTH);
panel_1.setLayout(null);
JLabel imagelable = new JLabel(new ImageIcon("c:\\good.jpg"));
imagelable.setBounds(70, 5, 105, 65);
panel_1.add(imagelable);
JLabel lblNewLabel_4 = new JLabel("Up Label");
lblNewLabel_4.setBounds(5, 5, 65, 35);
panel_1.add(lblNewLabel_4);
JLabel lblNewLabel_2 = new JLabel("Down Label");
lblNewLabel_2.setBounds(5, 25, 65, 65);
panel_1.add(lblNewLabel_2);
lblNewLabel.setText(""+i);
panel_1.setBounds(5+170*i, 5, 170+170*i, 70);
panel.add(panel_1);
i++;
}
});
panel.setMinimumSize(new Dimension(995,150));
}
public static void main(String[]args)
{
DrawImages drawImages = new DrawImages();
drawImages.setVisible(true);
}
}

The problem is with the statement:
panel_1.setLayout(null);
panel_1 doesn't have any preferred size so will not appear (or will appear as a tiny dot).
Swing was designed to use layout managers. You could use GridLayout in this particular case.
Read: Doing Without a Layout Manager

I agree with Reimeus. Just to test your code, I used
panel_1.setLayout(new FlowLayout());
And I could see the panels being added without calling repaint() on the parent panel.

Thanks for your answers but my problem is I added third arguman in every circle:
panel_1.setBounds(5+170*i, 5, 170+170*i, 70);
so my panel get bigger and bigger (event biger than my monitor) so the correct is:
panel_1.setBounds(5+170*i, 5, 170, 70);

Related

How to refresh JInternalFrame or JPanel form on button click where JPanel is a separate class and used in JInternalFrame

Iam trying to build a desktop application with multiple screens inside one single JFrame.
So each button click event will take us to the separate screen with refreshed components in the screen. So far this approach is working for me but the problem I am facing is even after using ".dispose(), .repaint(), .revalidate(), .invalidate()" functions. JInternalFrame or Jpanel seems to not refresh its components.
Which works something like below gif.
Tabbed Style
I do know JtabbedPane exists but for my method JtabbedPane is not viable.
Below I am posting minified code by replicating the problem I am facing.
MainMenu.Java(file with Main Class)
package test;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JInternalFrame;
public class MainMenu extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainMenu frame = new MainMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainMenu() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 841, 522);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 10, 807, 63);
contentPane.add(panel);
panel.setLayout(new GridLayout(1, 0, 0, 0));
JButton Tab1 = new JButton("Tab1");
panel.add(Tab1);
JButton Tab2 = new JButton("Tab2");
panel.add(Tab2);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 88, 807, 387);
contentPane.add(scrollPane);
JInternalFrame internalFrame1 = new JInternalFrame();
JInternalFrame internalFrame2 = new JInternalFrame();
Tab1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Panel1 panel1 = new Panel1();
if(internalFrame1 !=null) {
internalFrame1.dispose();
panel1.invalidate();
panel1.revalidate();
panel1.repaint();
}
internalFrame1.setTitle("Panel 1");
scrollPane.setViewportView(internalFrame1);
internalFrame1.getContentPane().add(panel1);
internalFrame1.setVisible(true);
}
});
Tab2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Panel2 panel2 = new Panel2();
if(internalFrame2 !=null) {
internalFrame2.dispose();
panel2.invalidate();
panel2.revalidate();
panel2.repaint();
}
internalFrame2.setTitle("Panel 2");
scrollPane.setViewportView(internalFrame2);
internalFrame2.getContentPane().add(panel2);
internalFrame2.setVisible(true);
}
});
}
}
and the corresponding Jpanel class files where JInternal Frames
Panel1.java
package test;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
public class Panel1 extends JPanel {
private JTextField textField;
/**
* Create the panel.
*/
public Panel1() {
setLayout(null);
textField = new JTextField();
textField.setBounds(10, 60, 430, 19);
add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Example Button");
btnNewButton.setBounds(10, 156, 430, 21);
add(btnNewButton);
}
}
Panel2.java
package test;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
public class Panel2 extends JPanel {
private JTextField textField;
/**
* Create the panel.
*/
public Panel2() {
setLayout(null);
textField = new JTextField();
textField.setBounds(10, 60, 430, 19);
add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button2");
btnNewButton.setBounds(21, 157, 419, 21);
add(btnNewButton);
}
}
P.S: This is my first time asking question in Stackoverflow so forgive me and if possible guide me if i miss anything
Thank you :)
Edit:
The problem I am facing is on the surface it looks like the Jpanel has been refreshed but the components like JtextField Still hides the previously written text in it and only show the text when i click on that JTextField
Below I am Attaching another gif which show highlights the issue. I have highlighted the part where I am facing issue.
Issue I am Facing
The dispose() method does not remove components so you keep adding components to the internal frame when you use the following:
internalFrame1.getContentPane().add(panel1);
Instead you might do something like:
Container contentPane = internalFrame1.getContentPane();
contentPane.removeAll();
contentPane.add( panel1 );
contentPane.revalidate();
contentPane.repaint();
You can use the JPanels in the Jframes and then use the CardLayout to change the panel ( which could than act like the different screens )

How do I change the size of my JButton?

I have to design a swing game where one side is a grid and the other side is somewhat of a display panel where I have several JLabels and a JButton. But no matter if I use setSize(); or setPrefferedSize (); or setBounds(); or even setPrefferedSize(new Dimension()); it will not become smaller but instead stretches the entirety of that section. Any JLabel/JButton aligned in the center takes up the entire center. How do I fix this?
This is the code to my class referencing to another class in the project containing the grid:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class Scoreboard extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel scoreLabel;
JLabel coord;
JLabel title;
JButton quit;
public Scoreboard (int score){
setLayout(new BorderLayout());
setSize(490,400);
setPreferredSize(getSize());
setBackground(Color.BLUE);
title = new JLabel();
title.setIcon(new ImageIcon("C:\\Users\\Rachel\\Workspace\\Assignment2\\Planet1.png"));
title.setSize(200,200);
title.setHorizontalAlignment(SwingConstants.CENTER);
add (title,BorderLayout.NORTH);
scoreLabel = new JLabel("Score: "+Integer.toString(score));
scoreLabel.setSize(200,200);
scoreLabel.setBackground(Color.BLUE);
scoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
scoreLabel.setFont(new Font("Source Sans Pro", Font.BOLD, 40));
scoreLabel.setForeground(Color.WHITE);
add(scoreLabel, BorderLayout.CENTER);
coord = new JLabel ("Click the aliens!");
coord.setSize(200,400);
coord.setBackground(Color.RED);
coord.setHorizontalAlignment(SwingConstants.CENTER);
coord.setFont(new Font("Source Sans Pro", Font.BOLD, 20));
coord.setForeground(Color.WHITE);
add(coord,BorderLayout.SOUTH);
JButton quit = new JButton ("Quit Game");
quit.setBounds(20,30,50,30);
quit.setHorizontalAlignment(SwingConstants.CENTER);
add(quit, BorderLayout.CENTER);
}
}
The following code does not solve the problem. Instead it shows some tips related to your question, as well as some others.
In general try to avoid "manually control" components layout, but use the right layout managers.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
public class Scoreboard extends JPanel{
JLabel scoreLabel;
JLabel coord;
JLabel title;
JButton quit;
private final int W = 490;
private final int H = 400;
public Scoreboard (int score){
setLayout(new BorderLayout());
setPreferredSize(new Dimension(W, H));
setBackground(Color.BLUE);
title = new JLabel("My Title");
//if you use images in your SO posted code use web links
//title.setIcon(new ImageIcon("C:\\Users\\Rachel\\Workspace\\Assignment2\\Planet1.png"));
//title.setSize(200,200); run the code without it and see it has no effect
title.setHorizontalAlignment(SwingConstants.CENTER);
add (title,BorderLayout.NORTH);
scoreLabel = new JLabel("Score: "+Integer.toString(score));
scoreLabel.setSize(200,200);
scoreLabel.setBackground(Color.BLUE);
scoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
scoreLabel.setFont(new Font("Source Sans Pro", Font.BOLD, 40));
scoreLabel.setForeground(Color.WHITE);
//this is directly related to your question. You can't add 2 components
//to the center.
//instead add a JPanel to the center, apply a layout manager to it,
//and add scorelabel and quit button to that JPanel
add(scoreLabel, BorderLayout.CENTER);
coord = new JLabel ("Click the aliens!");
//coord.setSize(200,400); run the code without it and see it has no effect
coord.setBackground(Color.RED);
coord.setOpaque(true); //if you want the color show
coord.setHorizontalAlignment(SwingConstants.CENTER);
coord.setFont(new Font("Source Sans Pro", Font.BOLD, 20));
coord.setForeground(Color.WHITE);
add(coord,BorderLayout.SOUTH);
JButton quit = new JButton ("Quit Game");
//no need to set bounds. That is what the layout manager does
//quit.setBounds(20,30,50,30);
quit.setHorizontalAlignment(SwingConstants.CENTER);
add(quit, BorderLayout.CENTER);
}
//add main to your questions to make it runnable
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
JPanel panel = new Scoreboard(50);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}

When I use the WindowBuilder preview function, the code appears as it should, but not when I press "run"

When I use the WindowBuilder preview, the code appears as it should, but when I run the program, it just brings up a blank frame. It looks fine in the preview, but as soon as I run it, it just brings up a blank frame.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import java.awt.GridLayout;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
public class Frame extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel teamSelect;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrame frame = new JFrame();
frame.setForeground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(new Point(100, 50));
frame.setSize(1800, 900);
frame.setTitle("Hockey");
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Frame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
teamSelect = new JPanel();
teamSelect.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(teamSelect);
teamSelect.setLayout(new CardLayout(0, 0));
JPanel divisionGrid = new JPanel();
teamSelect.add(divisionGrid, "name_3885325667274");
divisionGrid.setLayout(new GridLayout(2, 2, 0, 0));
JPanel metroDivision = new JPanel();
divisionGrid.add(metroDivision);
metroDivision.setLayout(new BorderLayout(0, 0));
JLabel lblMetropolitanDivision = new JLabel("Metropolitan Division");
lblMetropolitanDivision.setHorizontalAlignment(SwingConstants.CENTER);
lblMetropolitanDivision.setFont(new Font("Eras Bold ITC", Font.PLAIN, 16));
metroDivision.add(lblMetropolitanDivision, BorderLayout.NORTH);
JPanel atlanticDivision = new JPanel();
divisionGrid.add(atlanticDivision);
atlanticDivision.setLayout(new BorderLayout(0, 0));
JLabel lblAtlanticDivision = new JLabel("Atlantic Division");
lblAtlanticDivision.setHorizontalAlignment(SwingConstants.CENTER);
lblAtlanticDivision.setFont(new Font("Eras Bold ITC", Font.PLAIN, 16));
atlanticDivision.add(lblAtlanticDivision, BorderLayout.NORTH);
JPanel centralDivision = new JPanel();
divisionGrid.add(centralDivision);
centralDivision.setLayout(new BorderLayout(0, 0));
JLabel lblNewLabel = new JLabel("Central Division");
lblNewLabel.setFont(new Font("Eras Bold ITC", Font.PLAIN, 16));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
centralDivision.add(lblNewLabel, BorderLayout.NORTH);
JPanel pacificDivision = new JPanel();
divisionGrid.add(pacificDivision);
pacificDivision.setLayout(new BorderLayout(0, 0));
JLabel lblNewLabel_1 = new JLabel("Pacific Division");
lblNewLabel_1.setFont(new Font("Eras Bold ITC", Font.PLAIN, 16));
lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER);
pacificDivision.add(lblNewLabel_1, BorderLayout.NORTH);
}
Replace
new JFrame();
by
new Frame();
And call pack() before setVisible(true).
Note that just adding a System.out.println() or using the debugger to step through your code would have allowed you to find this simple mistake. A debugger is a wonderful tool. use it.

CardLayout showing blank JPanel in Java

I've searched up different tutorials and looked at the Class Profile for CardLayout and JPanel but I can't seem to get my window to show up. Currently it opens a frame with the proper dimensions and title but nothing in the actual container.
This is the code I have(P.S. I know it's a hot mess)
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
public class Casino extends JFrame implements ActionListener {
private JButton start, settings, scenario, music;
/**
* Constructor method
*/
public Casino(){
JPanel mainUI, startUI, settingsUI, scenarioUI, blackjackUI, oddorevenUI, tcmUI, overorunderUI, slotsUI;
JPanel menus = new JPanel(new CardLayout());
CardLayout GUI = (CardLayout) menus.getLayout();
mainUI = new JPanel();
getContentPane().add(mainUI);
mainUI.setBackground(new Color(53, 9, 9));
//Background items
JLabel title = new JLabel(new ImageIcon("title.png"));
title.setBounds(0,-280,780,700);
mainUI.add(title);
JLabel border = new JLabel(new ImageIcon("mainscreenborder.png"));
border.setBounds(0, 180, 780, 700);
mainUI.add(border);
//Main menu buttons
settings = new JButton();
ImageIcon s = new ImageIcon("settings-button.png");
settings.setBounds(320, 200, 122, 63);
settings.setIcon(s);
mainUI.add(settings);
music = new JButton();
ImageIcon m = new ImageIcon("music-button.png");
music.setBounds(320, 268, 122, 63);
music.setBackground(new Color(53, 9, 9));
music.setIcon(m);
mainUI.add(music);
scenario = new JButton();
ImageIcon sc = new ImageIcon("scenario-button.png");
scenario.setBounds(320, 336, 122, 63);
scenario.setBackground(new Color(53, 9, 9));
scenario.setIcon(sc);
mainUI.add(scenario);
start = new JButton();
ImageIcon st = new ImageIcon("start-button.png");
start.setBounds(320, 404, 122, 63);
start.setBackground(new Color(53, 9, 9));
start.setIcon(st);
mainUI.add(start);
menus.add(mainUI, "Main Menu");
GUI.show(menus, "Main Menu");
setSize(780, 700);
setResizable(false);
setLayout(GUI);
setTitle("White Lily Casino");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Casino wlc = new Casino();
}
}
Note: It worked before when I was using the Container c method instead of using a JPanel and CardLayout. I am trying to switch it to card layout now because I want to use buttons to navigate to multiple screens
Try adding the mainUI to the JFrame
getContentPane().add(mainUI)
or
add(mainUI)

JSpinner Arrows in odd positioning when used with JLabel

Hello So i have created a JFrame with a JSpinner inside (as you can see in the picture). Right now, the BorderLabel is showing in the Jspinner (as it should) but the arrows on the JSpinner are there as a part of the entire thing instead of just the JSpinner field. I would like help to find out how to put the JSpinner arrows on the bar. Thank you.
For you who asked for code,
Also I miss stated JLabel Earlier. I meant TitledBorder
import java.awt.ComponentOrientation;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class ex extends JFrame{
public static void main(String[] args){
new ex();
}
ex(){
super("test");
setSize(200,100);
SpinnerModel sm = new SpinnerNumberModel(3,1,25,1);
JSpinner shiftIn = new JSpinner(sm);
JPanel p = new JPanel();
shiftIn.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
shiftIn.setBorder(new CompoundBorder(new TitledBorder(new EmptyBorder(0,
0, 0, 0), "Shift Key"), shiftIn
.getBorder()));
p.add(shiftIn);
add(p);
setVisible(true);
}
}
shiftIn.setBorder(new CompoundBorder(
new TitledBorder(new EmptyBorder(0, 0, 0, 0), "Shift Key"),
shiftIn.getBorder()));
This is not the sort of thing that a titled border was made for!
Use a JLabel and put it in the PAGE_START of a BorderLayout, put the JSpinner in the PAGE_END. Add that container (the panel) where the spinner is currently added. (Then add a mnemonic for the label and make it the 'label for' the spinner.)
This is how to use that idea inside another layout (GridLayout in this example)..
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class ex extends JFrame {
public static void main(String[] args) {
new ex();
}
ex() {
super("test");
// imagine this is actually using GridBagLayout
JPanel ui = new JPanel(new GridLayout(0, 3,4,4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
SpinnerModel sm = new SpinnerNumberModel(3, 1, 25, 1);
JSpinner shiftIn = new JSpinner(sm);
JLabel l = new JLabel("Shift Key");
JPanel p = new JPanel(new BorderLayout());
p.add(l, BorderLayout.PAGE_START);
p.add(shiftIn, BorderLayout.PAGE_END);
add(ui);
for (int ii=0; ii<9; ii++) {
if (ii==4) {
ui.add(p);
} else {
ui.add(new JButton("Button"));
}
}
pack();
setVisible(true);
}
}
You appear to be running into risk by messing with the JSpinner's border. Myself, I would wrap my JSpinner in a JPanel and then give that wrapper JPanel the desired border. For example:
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
#SuppressWarnings("serial")
public class Ex extends JFrame {
public static void main(String[] args) {
new Ex();
}
Ex() {
super("test");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
SpinnerModel sm = new SpinnerNumberModel(3, 1, 25, 1);
JSpinner shiftIn = new JSpinner(sm);
JPanel spinnerWrapper = new JPanel(new BorderLayout());
spinnerWrapper.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEmptyBorder(0, 0, 0, 0), "Shift Key"));
spinnerWrapper.add(shiftIn);
shiftIn.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
add(spinnerWrapper);
pack();
setVisible(true);
}
}

Categories

Resources