I have following code to add panels dynamically to container with GridBagLayout.
It should grow and display vertical scrollbar, not horizontal.
But when I add too long text in JLabel in parent JPanel, it displays horizontal scrollbar, I want JLabel to break text as container shrinks, and also grows as the container grows.
I've tried setting maximum width but the GridBagLayout not using it.
I've also tried using something like but it makes the label's not growing when I resize the parent.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.border.MatteBorder;
/**
*
* #author MethoD
*/
public class DynamicPanelList extends JPanel {
private JPanel mainList;
public DynamicPanelList() {
setLayout(new BorderLayout());
mainList = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.weighty = 1;
mainList.add(new JPanel(), gbc);
add(new JScrollPane(mainList));
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JLabel lbl = new JLabel("<html>Hello world items lorem ipsum dolor sit amei blast it");
//lbl.setMaximumSize(new Dimension(100, 100));
panel.add(lbl, BorderLayout.CENTER);
panel.setBorder(new MatteBorder(0, 0, 1, 0, Color.GRAY));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
mainList.add(panel, gbc, 0);
validate();
repaint();
}
});
add(add, BorderLayout.SOUTH);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DynamicPanelList tp = new DynamicPanelList();
frame.add(tp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Related
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
i want to make a bigger resolution/fullscreen but i dont know what layout should i use, can u guys help me to choose a better layout
this is the first code for first pic
tp = new JTabbedPane();
tp.setBounds(0,0,250,400);
panel = new JPanel();
panel.setPreferredSize(new Dimension(250, 480));
tp.addTab("Mahasiswa",panel);
panel.setLayout(new FlowLayout());
label_insert = new JLabel("NIM : ");
label_insert2 = new JLabel("ID Jurusan : ");
tf_insert1 = new JTextField(15);
tf_insert2 = new JTextField(15);
Insert = new JButton(" Insert ");
//panel add
this one i want to make it on middle of frame and all of them already on panel, how can i move it to the middle ?
this is code for the second picture
public void mainform(){
main = new JPanel();
main.setLayout(new FlowLayout(FlowLayout.CENTER));
label_main = new JLabel("ID");
label_main2 = new JLabel("Password");
tf_main = new JTextField(15);
tf_main2 = new JPasswordField(15);
login = new JButton("LOGIN");
login.addActionListener(this);
main.add(label_main);
main.add(tf_main);
main.add(label_main2);
Following this guide here I would suggest the following:
yourFrame = new JFrame();
yourFrame.setLayout(new BorderLayout());
tp = new JTabbedPane();
yourFrame.add(tp, BorderLayout.CENTER);
Then fiddle with GridLayout, GridBagLayout, or GroupLayout for the tabs in your tabbedpane.
I would consider using a GridBagLayout which will give you greater flexibility in how the components are laid out
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2, 2, 2, 2);
add(new JLabel("ID"), gbc);
gbc.gridx++;
add(new JTextField(20), gbc);
gbc.gridx = 0;
gbc.gridy++;
add(new JLabel("Password"), gbc);
gbc.gridx++;
add(new JTextField(20), gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.CENTER;
add(new JButton("Login"), gbc);
}
}
}
See Laying Out Components Within a Container and How to Use GridBagLayout for more details
From my code I expect my JTextArea to fill the top left border seen below:
But as you can see its taking up a tiny section in the middle.
I am using GridBagConstraints on the panel which contains the components.
There is a main class which calles up a class called frame. This class creates the JFrame and sets the size as well as other things. This is then called from the MainFrame.java which has extended the jframe which creates 3 panels and sets their layout. this is seen below
import javax.swing.*;
import java.awt.*;
public class MainFrame extends JFrame
{
private Panel1 storyPanel;
private Panel2 statsPanel;
private Panel3 commandsPanel;
public MainFrame(String title)
{
super(title);
// Setting Layout
GridBagConstraints gbc = new GridBagConstraints();
storyPanel = new Panel1();
storyPanel.setLayout(new GridBagLayout());
statsPanel = new Panel2();
commandsPanel = new Panel3();
Container p = getContentPane();
p.add(storyPanel, BorderLayout.WEST);
p.add(statsPanel, BorderLayout.EAST);
p.add(commandsPanel, BorderLayout.SOUTH);
}
}
The panel in questions is Panel1 or storyPanel. I have set the layout and the code calls the Panel1.java as seen below:
import javax.swing.*;
import java.awt.*;
public class Panel1 extends JPanel
{
public Panel1()
{
GridBagConstraints gbc = new GridBagConstraints();
//Set size of Panel1
int xsizeP1 = (Frame.xsize() / 2);
int ysizeP1 = (Frame.ysize() / 3 * 2);
setPreferredSize(new Dimension(xsizeP1, ysizeP1));
setBorder(BorderFactory.createLineBorder(Color.black));
//Adding JTextArea and adding settings to it
JTextArea storyLine = new JTextArea(" test ");
storyLine.setLineWrap(true);
storyLine.setWrapStyleWord(true);
storyLine.setEditable(false);
//Adding JScrollPane to the JTextArea and making it have a vertical scrollbar
JScrollPane scroll = new JScrollPane(storyLine);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
//GridBagConstraints setup for components
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.fill = GridBagConstraints.VERTICAL;
add(scroll, gbc);
}
}
I don't understand why my gbc.fill isnt making the JTextArea fill the top left border of the screen shot.
Thanks in advance for any reply's
-Tom T
changing the layout to border layout
import javax.swing.*;
import java.awt.*;
public class Panel1 extends JPanel
{
public Panel1()
{
//GridBagConstraints gbc = new GridBagConstraints();
//gbc.weightx = 0.1;
//gbc.weighty = 0.1;
BorderLayout b = new BorderLayout();
//Set size of Panel1
int xsizeP1 = (Frame.xsize() / 2);
int ysizeP1 = (Frame.ysize() / 3 * 2);
setPreferredSize(new Dimension(xsizeP1, ysizeP1));
setBorder(BorderFactory.createLineBorder(Color.black));
//Adding JTextArea and adding settings to it
JTextArea storyLine = new JTextArea(" test ");
storyLine.setLineWrap(true);
storyLine.setWrapStyleWord(true);
storyLine.setEditable(false);
//Adding JScrollPane to the JTextArea and making it have a vertical scrollbar
JScrollPane scroll = new JScrollPane(storyLine);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
//gbc.gridx = 0;
//gbc.gridy = 0;
//gbc.weightx = 1;
//gbc.weighty = 1;
//gbc.fill = GridBagConstraints.BOTH;
add(scroll, b.CENTER);
}
}
Don't set the layout of storyPanel, as it's contents have already been added and laid out, so changing the layout manager here will discard any properties you applied. Instead, set the layout in Panel1's constructor before you add any components.
Use GridBagConstraints.BOTH for the fill property. The fill property can only have one specified value
Use weightx and weighty to specify how much of the available space the component should use
For example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MainFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new MainFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private Panel1 storyPanel;
// private Panel2 statsPanel;
// private Panel3 commandsPanel;
public MainFrame(String title) {
super(title);
storyPanel = new Panel1();
Container p = getContentPane();
p.add(storyPanel, BorderLayout.WEST);
p.add(new JLabel("East"), BorderLayout.EAST);
p.add(new JLabel("South"), BorderLayout.SOUTH);
}
public class Panel1 extends JPanel {
public Panel1() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
//Set size of Panel1
setBorder(BorderFactory.createLineBorder(Color.black));
//Adding JTextArea and adding settings to it
JTextArea storyLine = new JTextArea(20, 20);
storyLine.setLineWrap(true);
storyLine.setWrapStyleWord(true);
storyLine.setEditable(false);
//Adding JScrollPane to the JTextArea and making it have a vertical scrollbar
JScrollPane scroll = new JScrollPane(storyLine);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
//GridBagConstraints setup for components
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
add(scroll, gbc);
}
}
}
Having said all that, a BorderLayout would be simpler
public class Panel1 extends JPanel {
public Panel1() {
setLayout(new BorderLayout());
//Set size of Panel1
setBorder(BorderFactory.createLineBorder(Color.black));
//Adding JTextArea and adding settings to it
JTextArea storyLine = new JTextArea(20, 20);
storyLine.setLineWrap(true);
storyLine.setWrapStyleWord(true);
storyLine.setEditable(false);
//Adding JScrollPane to the JTextArea and making it have a vertical scrollbar
JScrollPane scroll = new JScrollPane(storyLine);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
add(scroll);
}
}
i tried a border layout and set it to center expecting it to resize but that failed as well
Would suggest that you're making a fundamental mistake some where, as it works fine for me. Remember, set the layout BEFORE you add any components to the container
I'm coding a GUI by hand and I've run into difficulty positioning a JLabel on a JPanel. I'm trying to put it in the top left hand side above the JTextField but it's defaulting to the middle even though I'm settings the bounds:
Relevant code:
JPanel mainPanel = new JPanel();
JLabel myFleetLabel = new JLabel("My Fleet");
myFleetLabel.setBounds(1,1, 10, 10);
mainPanel.add(myFleetLabel);
add(mainPanel);
Here's what it looks like:
There are a few ways you might be able achieve this, one might be to use a GridBagLayout as the primary layout manager, for example
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.NORTHWEST;
JLabel label = new JLabel("My Fleet: ");
add(label, gbc);
JTextArea ta = new JTextArea(10, 20);
gbc.gridx++;
add(new JScrollPane(ta), gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(new JScrollPane(new JTextArea(5, 10)), gbc);
JPanel actions = new JPanel();
actions.add(new JButton("Create Ship"));
actions.add(new JButton("Flip Coins"));
gbc.gridy++;
add(actions, gbc);
}
}
}
See Laying Out Components Within a Container and How to Use GridBagLayout for more details.
Remember, it's unlikely that a single layout manager will solve all your problems and some times you will need to use two or more to accomplish the overall effect
Typically you need to use layouts to place objects in a containter. You should get acquainted with layouts to really code properly in swing.
The being said, the reason your code isn't working as is, is because containers have a layout by default. You CAN remove the layout as follows
mainPanel.setLayout(null);
but this is very bad practice and should be avoided always.
I want to align all the JLabels to the left side of the panel. Following is my code, but it doesnt work properly, I dont know why.
JFrame frame1 = new JFrame("Register a passenger");
frame1.setVisible(true);
frame1.setSize(550, 200);
JPanel panel = new JPanel();
frame1.add(panel);
JLabel label1 = new JLabel("Name",SwingConstants.LEFT);
JLabel label2 = new JLabel("Activities",SwingConstants.LEFT);
JButton jbtReg = new JButton("Register");
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(jbtReg);
Based on your example, you could use
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
But this will align all your components to the left.
You could also consider using a different layout manager or combination of layout managers?
Take a look at A Visual Guide to Layout Managers for more ideas
Updated
FlowLayout (which is the default layout manager for JPanel) doesn't give you a lot of options, instead consider trying to use a different layout manager or combination of layout managers, for example...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class LayoutExample {
public static void main(String[] args) {
new LayoutExample();
}
public LayoutExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
add(new JLabel("Name:"), gbc);
gbc.gridy++;
add(new JLabel("Activity:"), gbc);
gbc.gridx++;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.NONE;
add(new JTextField(10), gbc);
gbc.gridy++;
add(new JTextField(20), gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = 2;
add(new JButton("Register"), gbc);
}
}
}