Hiding a frame in java upon a button click - java

I am trying to hide a frame once a button is clicked. The "Register" button should open up a frame where a user can register, and that works, but I am trying to hide the previous frame and I can't figure out how to do it.
Here's my code:
MainPage.java
package Practice_1;
import java.awt.*;
import java.awt.Insets;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/**
*
* #author Ivan
*/
public class MainPage extends JPanel
{
JButton regButton, logButton, listButton;
JLabel homeMessage;
GridBagConstraints gbc = new GridBagConstraints();
public MainPage()
{
setLayout(new GridBagLayout());
gbc.insets = new Insets(5,5,5,5);
homeMessage = new JLabel("Please select an option below:");
gbc.gridx = 0;
gbc.gridy = 0;
add(homeMessage, gbc);
regButton = new JButton("Register");
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
regButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
//System.out.println("clicked");
RegisterPage regFrame = new RegisterPage();
JFrame register = new JFrame();
register.setTitle("Registration");
register.setSize(300,200);
register.setVisible(true);
register.add(regFrame);
new MainPage().setVisible(false); / THIS DOES NOT WORK
}
});
add(regButton, gbc);
logButton = new JButton("Log in");
gbc.ipadx = 40;
gbc.gridx = 0;
gbc.gridy = 2;
add(logButton, gbc);
listButton = new JButton("Customer list");
gbc.ipadx = 40;
gbc.gridx = 0;
gbc.gridy = 3;
add(listButton, gbc);
JFrame home = new JFrame();
home.setTitle("Main menu");
home.setSize(300,200);
home.setResizable(false);
home.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
home.setVisible(true);
home.add (mainFrame);
}
public static void main(String[] args) {
// TODO code application logic here
MainPage mainFrame = new MainPage();
}
}
RegisterPage.java
package Practice_1;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* #author Ivan
*/
public class RegisterPage extends JPanel {
//JButton regButton, logButton, listButton;
JLabel homeMessage;
GridBagConstraints gbc = new GridBagConstraints();
public RegisterPage()
{
setLayout(new GridBagLayout());
gbc.insets = new Insets(5,5,5,5);
homeMessage = new JLabel("Register new user:");
gbc.gridx = 0;
gbc.gridy = 0;
add(homeMessage, gbc);
}
}

Acording to your code you are trying to hide JPanel instead of JFrame. My suggestion is to use
public class MainPage extends JFrame
than instantiate your JPanel like this:
JPanel panel = new JPanel();
and to add components on that panel. To hide your MainPage you can call:
this.setVisible(false);
but it would be better if you use:
this.dispose();

Related

How do I move a table to the left if it is in a JPanel?

I am trying to move a table to the left side of a JPanel which is also inside a Window
What I get is this:
What I want is this:
I tried using .setBounds method but it does not work. Does anyone know what to do?
This is my code:
package Modulos;
import paneles.*;
import javax.swing.*;
public class ModuloAdmin extends JFrame {
public ModuloAdmin(){
//Crear tabla
String[][] datosprueba = {
{"001","Carlitos", "Casa","51202011"},
{"001","Carlitos", "Casa","51202011"}
};
String[] TituloColumna = {"Código", "Nombre", "Dirección", "Teléfono"};
JTable TablaSucursales = new JTable(datosprueba,TituloColumna);
//Contenido de las pestañas
JPanel PanelSucursales = new JPanel();
PanelSucursales.add(TablaSucursales);
PanelSucursales.add(new JScrollPane(TablaSucursales));
JPanel PanelProductos = new JPanel();
PanelProductos.add(new JLabel("Panel productos"));
JPanel PanelClientes = new JPanel();
PanelClientes.add(new JLabel("Panel Clientes"));
JPanel PanelVendedores = new JPanel();
PanelVendedores.add(new JLabel("Panel Vendedores"));
//CREACION DE PESTAÑAS
JTabbedPane Pestanias = new JTabbedPane();
Pestanias.setBounds(20,80,700,700);
Pestanias.add("Sucursales",PanelSucursales);
Pestanias.add("Productos",PanelProductos);
Pestanias.add("Clientes", PanelClientes);
Pestanias.add("Vendedores",PanelVendedores);
//vENTANA MODULO DE ADMIN
JFrame VentanaModuloAdmin = new JFrame();
VentanaModuloAdmin.add(Pestanias);
VentanaModuloAdmin.setLayout(null);
VentanaModuloAdmin.setSize(800,850);
VentanaModuloAdmin.setLocationRelativeTo(null);
VentanaModuloAdmin.setTitle("Módulo de administrador");
VentanaModuloAdmin.setVisible(true);
VentanaModuloAdmin.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
Use appropriate layout mangers and container management
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTable table;
public TestPane() {
setBorder(new EmptyBorder(16, 16, 16, 16));
setLayout(new GridLayout(0, 2));
add(new JScrollPane(table));
add(createButtonPane());
}
protected JPanel createButtonPane() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.ipadx = 16;
gbc.ipady = 16;
gbc.fill = gbc.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(new JButton("Clear"), gbc);
gbc.gridx = 1;
panel.add(new JButton("Carga Masiva"), gbc);
gbc.gridy++;
gbc.gridx = 0;
panel.add(new JButton("Actualizar"), gbc);
gbc.gridx = 1;
panel.add(new JButton("Eliminar"), gbc);
gbc.gridy++;
gbc.gridx = 0;
gbc.gridwidth = 2;
gbc.anchor = GridBagConstraints.NORTH;
gbc.weighty = 1;
panel.add(new JButton("Exportar Listado a PDF"), gbc);
return panel;
}
}
}
Seriously, layout managers solve one of the most difficult issues facing UI developers - the variable nature of the output (screen resolutions, font metrics, accessibility modifiers, a whole bunch of different stuff which changes how layouts need to be calculated).
They might seem difficult to start with, but once you get use to using them and learn how to make use of "compound layouts", which is demonstrated above, it will help you make better UIs more quickly

Dynamicly adding JPanels to a JFrame

This is my first question inhere, so please bear with me :)
Im working on a dynamic part of a GUI, and for some reason its teasing me.
The class is opened in a new window after login.
What I want, is for a new JPanel to be built and added to 'container' every time the "add player" button is clicked. It is supposed to put them below eachother, yet all it does is to add one button on the first click, and then the rest of the clicks afterwards does nothing.
Any help is appreciated :)
package Gui;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
//import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
#SuppressWarnings("serial")
public class TeamManagerGUI extends JFrame implements ActionListener
{
// private JLabel pNameLabel = new JLabel("Player Name: "),
// pSchoolLabel = new JLabel("School: ");
// private JTextField pNameField = new JTextField(),
// pSchoolField = new JTextField();
private JButton addButton = new JButton("Add Player"),
removeButton = new JButton("Remove player");
private JPanel container = new JPanel(),
playerContainer = new JPanel();
int frameCounter = 1;
public TeamManagerGUI()
{
super("Team Manager User Interface");
setSize(1200,800);
setDefaultCloseOperation(EXIT_ON_CLOSE);
container.setLayout(new GridBagLayout());
playerContainer.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(3,3,3,3);
addButton.addActionListener(this);
container.add(addButton,gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.insets = new Insets(3,3,3,3);
container.add(removeButton,gbc);
this.add(container);
}
public void playerFrame()
{
GridBagConstraints gbc = new GridBagConstraints();
playerFrameArr.add(new JPanel());
gbc.gridx = 0;
gbc.gridy = 0;
playerContainer.add(new JButton("LABEL"),gbc);
gbc.gridx = 1;
gbc.gridy = 0;
playerContainer.add(new JButton("BUTTON"),gbc);
gbc.gridx = 0;
gbc.gridy = frameCounter+1;
container.add(playerContainer,gbc);
System.out.println(frameCounter);
frameCounter++;
}
public void addPlayerRow()
{
playerFrame();
container.revalidate();
container.repaint();
}
public void removePlayerRow()
{
//Not yet implemented
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == addButton)
{
addPlayerRow();
}
if(ae.getSource() == removeButton)
{
//Not yet implemented
}
}
}
You are adding the playerContainer again and again. I think you should actually use the newly created JPanel. This one should be populated and added to the main container.
Adding a single panel multiple times will not render properly as this screws up the layout. I think you need to keep a reference to the new JPanel and fill this one with your layout and the buttons.
I am thinking something like this:
public void playerFrame()
{
GridBagConstraints gbc = new GridBagConstraints();
JPanel newPanel = new JPanel(new GridBagLayout());
playerFrameArr.add(newPanel);
gbc.gridx = 0;
gbc.gridy = 0;
newPanel.add(new JButton("LABEL"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
newPanel.add(new JButton("BUTTON"), gbc);
gbc.gridx = 0;
gbc.gridy = frameCounter + 1;
container.add(newPanel, gbc);
System.out.println(frameCounter);
frameCounter++;
}

Component not appearing when adding to panel

So I'm trying to create a series of radio buttons and check boxes that are displayed as follows:
Radio Button
Check Box
Radio Button
Check Box
Radio Button
However, I'm still in the learning process for java and I was wondering if anyone could solve this problem. At the moment the buttons and boxes are being displayed in the correct location, however the first radio button ("Courier") is not being displayed for some reason. If you could perhaps describe the reason and a possible solution that'd be great.
Thanks
Updated Code:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class Question2 {
public static void main(String[] args) {
MyFrame f = new MyFrame("Font Chooser");
f.init();
}
}
class MyFrame extends JFrame {
MyFrame(String title) {
super(title);
}
private JPanel mainPanel;
private GridBagConstraints gbc = new GridBagConstraints();
private GridBagLayout gbLayout = new GridBagLayout();
void init() {
mainPanel = new JPanel();
mainPanel.setLayout(gbLayout);
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
this.setContentPane(mainPanel);
gbc.gridx = 0;
gbc.gridy = 1;
JCheckBox cb = new JCheckBox("Bold");
gbLayout.setConstraints(cb, gbc);
mainPanel.add(cb);
gbc.gridy = 3;
gbLayout.setConstraints(cb, gbc);
cb = new JCheckBox("Italic");
mainPanel.add(cb);
gbc.gridx = 1;
gbc.gridy = 0;
JRadioButton rb = new JRadioButton("Times");
gbLayout.setConstraints(rb, gbc);
mainPanel.add(rb, gbc);
gbc.gridy = 2;
rb = new JRadioButton("Helvatica");
mainPanel.add(rb, gbc);
rb = new JRadioButton("Courier");
gbc.gridy = 4;
mainPanel.add(rb, gbc);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
3 issues
Y Coordinate not re-assigned to different value causing last 2 radio buttons to exist at same location
GridBagConstraints not being used for left-hand side components
setConstraints erroneously being used to set constraints
Resultant code:
public class GoodGridBagApp {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Font Chooser");
frame.add(getMainPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private JPanel getMainPanel() {
JPanel mainPanel = new JPanel();
GridBagConstraints gbc = new GridBagConstraints();
mainPanel.setLayout(new GridBagLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
gbc.gridx = 1;
gbc.gridy = 2;
JCheckBox cb = new JCheckBox("Bold");
mainPanel.add(cb, gbc);
gbc.gridy = 4;
cb = new JCheckBox("Italic");
mainPanel.add(cb, gbc);
gbc.gridx = 2;
gbc.gridy = 1;
JRadioButton rb = new JRadioButton("Times");
mainPanel.add(rb, gbc);
gbc.gridy = 3;
rb = new JRadioButton("Helvatica");
mainPanel.add(rb, gbc);
rb = new JRadioButton("Courier");
gbc.gridy = 5;
mainPanel.add(rb, gbc);
return mainPanel;
}
});
}
}
Read: How to Use GridBagLayout

Java GridBagLayout - How to position my components gap-less and one by one?

I'm using GridBagLayout to place my GUI components by the following code, wanting the components lay one by one in a column, without any gaps :
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestGUI extends JFrame{
public TestGUI(){
JPanel bigPanel = new JPanel(new GridBagLayout());
JPanel panel_a = new JPanel();
JButton btnA = new JButton("button a");
panel_a.add(btnA);
JPanel panel_b = new JPanel();
JButton btnB = new JButton("button b");
panel_b.add(btnB);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weighty = 1D;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTH;
bigPanel.add(panel_a, c);
c.gridx = 0;
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
bigPanel.add(panel_b, c);
this.add(bigPanel);
}
public static void main(String[] args) {
TestGUI gui = new TestGUI();
gui.setVisible(true);
gui.pack();
}
}
I wish the panels will be shown one by one in the column. but now i got this :
As i am going to add some more components in the bigPanel, and required some more customization to the layout, so i need to use GridBagLayout instead of other Layout.
You need to add an extra component so that it will fill the rest of the available space and push the two button-panels to the top. When you will add more components, you can of course remove that component.
Another option (without requiring an extra component) would have been to set weighty=1.0 for the panel_b and anchor=NORTH, but then you would have to change that when you add more components.
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestGUI extends JFrame {
public TestGUI() {
JPanel bigPanel = new JPanel(new GridBagLayout());
JPanel panel_a = new JPanel();
JButton btnA = new JButton("button a");
panel_a.add(btnA);
JPanel panel_b = new JPanel();
JButton btnB = new JButton("button b");
panel_b.add(btnB);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1.0;
bigPanel.add(panel_a, c);
bigPanel.add(panel_b, c);
c.weighty = 1.0;
// Temporary panel to fill the rest of the bigPanel
bigPanel.add(new JPanel(), c);
this.add(bigPanel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TestGUI gui = new TestGUI();
gui.pack();
gui.setVisible(true);
}
});
}
}

Java/Swing: Trying to get BorderLayout to play nice with GridBagLayout

I'd like to have a window that has 3 menus, one tied to the left, another tied to the center and the last one tied to the right. Like this:
--------------------------------------------
-toolbar1---------toolbar2---------toolbar3-
--------------------------------------------
- -
- rest of the window does something here -
The problem I'm having is that this is the result I get:
--------------------------------------------
---------toolbar1toolbar2toolbar3-----------
--------------------------------------------
- -
- rest of the window does something here -
Here's some sample code (compiles and shows the problem):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestClass extends JFrame {
public TestClass() {
super("test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
final JPanel upper = new JPanel();
upper.setLayout(new GridBagLayout());
final GridBagConstraints gbc = new GridBagConstraints();
final JButton toolbar1 = new JButton("toolbar1");
final JButton toolbar2 = new JButton("toolbar2");
final JButton toolbar3 = new JButton("toolbar3");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
upper.add(toolbar1, gbc);
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.CENTER;
upper.add(toolbar2, gbc);
gbc.gridx = 2;
gbc.anchor = GridBagConstraints.EAST;
upper.add(toolbar3, gbc);
add(upper, BorderLayout.NORTH);
final JPanel something = new JPanel();
something.setBackground(Color.WHITE);
something.setPreferredSize(new Dimension(600, 600));
something.repaint();
add(something, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
final TestClass test = new TestClass();
}
}
How can I fix it? I thought that by setting the anchor in the GridBagConstraints I'd take care of it, but that didn't work.
You forgot to add :
gbc.weightx = 1.0;
gbc.weighty = 1.0;
Your changed code should look like :
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestClass extends JFrame {
public TestClass() {
super("test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
final JPanel upper = new JPanel();
GridBagLayout gridbag = new GridBagLayout();
upper.setLayout(gridbag);
GridBagConstraints gbc = new GridBagConstraints();
final JButton toolbar1 = new JButton("toolbar1");
final JButton toolbar2 = new JButton("toolbar2");
final JButton toolbar3 = new JButton("toolbar3");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.WEST;
upper.add(toolbar1, gbc);
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.CENTER;
upper.add(toolbar2, gbc);
gbc.gridx = 2;
gbc.anchor = GridBagConstraints.EAST;
gbc.gridwidth = GridBagConstraints.REMAINDER;
upper.add(toolbar3, gbc);
add(upper, BorderLayout.NORTH);
final JPanel something = new JPanel();
something.setBackground(Color.WHITE);
something.setPreferredSize(new Dimension(600, 600));
something.repaint();
add(something, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
final TestClass test = new TestClass();
}
}
It works.
If your toolbar looks like a BorderLayout (WEST, CENTER, EAST), why not use a BorderLayout instead of a GridBagLayout?
Anyway, if you insist on using GridBagLayout, set the weightx constraint for toolbar2 to 1. This tells the layout manager that, if more room is available, it should give it all to toolbar2.
gbc.weightx = 1;
upper.add(toolbar2, gbc);
gbc.weightx = 0;

Categories