Positioning of a JLabel on a JPanel - java

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.

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

How to set java application to adopt the varying screensizes?

I am trying to run my application in full screen size. It contains a frame fully covered by panel. I have tried this code
Toolkit tk=this.getDefaultToolkit();
this.setSize(tk.getScreenSize.getWidth(),tk.getScreenSize.getHeight());
I also tried MAXIMIZED_BOTH in setExtendedState. That too doesn't work. I think the problem is with jPanel but not sure. Its only half visible in small screen sizes but the Frame is acquiring full size in all screen sizes. I have enabled autoresizing for the panel.
Here the images of application in larger screen and in smaller screen
and
The proper use of a variety of layout managers can greatly increase the ability for a UI to be dynamically sized
Based on the screen shots in your question, I see a BorderLayout, GridLayout and possibly a GridBagLayout as the primary choices
The window "packed"
The window "maximised"
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;
public class JavaApplication170 {
public static void main(String[] args) {
new JavaApplication170();
}
public JavaApplication170() {
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 TopPane(), BorderLayout.NORTH);
frame.add(new LeftPane(), BorderLayout.WEST);
frame.add(new JScrollPane(new FieldsPane()));
frame.pack();
//frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TopPane extends JPanel {
public TopPane() {
setLayout(new GridLayout(1, 0));
add(new JLabel("Some title"));
add(new JButton("One"));
add(new JButton("Two"));
add(new JButton("Three"));
add(new JButton("Four"));
}
}
public class LeftPane extends JPanel {
public LeftPane() {
setLayout(new GridLayout(0, 1));
add(new JButton("One"));
add(new JButton("Two"));
add(new JButton("Three"));
add(new JButton("Four"));
add(new JButton("Five"));
add(new JButton("Six"));
add(new JButton("Seven"));
}
}
public class FieldsPane extends JPanel {
public FieldsPane() {
setLayout(new GridBagLayout());
addField("Field one", 0);
addField("Field two", 1);
addField("Field three", 2);
addField("Field four", 3);
addField("Field five", 4);
addField("Field six", 5);
addField("Field seven", 6);
addField("Field eight", 7);
addField("Field nine", 8);
addField("Field ten", 9);
addField("Field eleven", 10);
addField("Field tweleve", 11);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridheight = 3;
gbc.gridx = 2;
gbc.gridy = 1;
//gbc.weightx = 1;
add(makeProfileLabel(), gbc);
gbc.gridheight = 1;
gbc.gridy += 3;
add(new JButton("Some button"), gbc);
}
protected void addField(String text, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = row;
gbc.insets = new Insets(4, 4, 4, 4);
add(new JLabel(text), gbc);
gbc.gridx++;
add(new JTextField(10), gbc);
}
protected JLabel makeProfileLabel() {
JLabel label = new JLabel();
label.setPreferredSize(new Dimension(50, 50));
label.setBorder(new LineBorder(Color.BLACK));
return label;
}
}
}
Now, this is a relatively simple example intended to demonstrate the concept of using multiple layouts.
For example, I might be tempted to use another GridBagLayout to layout the "main" layout, which would give me more control over the "some title" label
Layouts can be a bit of a (black magic) art form, but if you start with the "base" requirements, look at the functionality the UI is trying to produce and break those requirements down, it will be easier then trying to dump all the content into a single component
I'm guessing that this is a JFrame. At some point you add your main panel to the frame.
this.add(panel);
Instead, wrap the panel in a JScrollPane and add() that to the frame.
JScrollPane scrollPane = new JScrollPane(panel);
this.add(scrollPane);
this.pack();
this.setExtendedState(getExtendedState() | MAXIMIZED_BOTH);
this.setVisible(true);
It would be better if we resized the components to fit screen size rather than using a scrollPane.
Here's some other ideas:
Use a size variant where it's possible.
Decrease any gaps in the registration panel, e.g. setHgap() and setVgap() for GridLayout.
Make just the registration panel Scrollable.

Make JLabel text breaks in gridbaglayout

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);
}
}

how to design panel from tabbedpane and make panel to center

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

How can I align the JLabel to the left of the panel

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);
}
}
}

Categories