positionnig myJTextField beside JComboBox - java

I want to creat a palet with many JComboBox. like that :
for(int x=0; x<MAX; x++){
box[x] = new JComboBox(new String[]{"op1", "op2", "op3");
}
at the right of each JComboBox i want to create many JTextField. So, in my palet i will have some think like that:
myJComboBox1 myJTextField
anotherJTextField
anotherJTextField
myJComboBox2 myJTextField
anotherJTextField
anotherJTextField
...
How can i do that please ? I tried by setBounds and other layout like FlowLayout and GridLayout but without success.

GridBagLayout is the best solution. However, if you are new to Swing, it might be a bit over complicated. In that case:
Use GridLayout(0, 2) for the main panel.
Wrap the combobox in a Panel with a border layout and add it to north. Add it to the main panel.
Use another panel with GridLayout(0,1) add your text fields to it and add it to the main panel.
and loop...
Adding sample code:
package snippet;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class BorderLayoutTest extends JFrame {
static private int MAX = 10 ;
public BorderLayoutTest() {
super(BorderLayoutTest.class.getName());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
}
private void initComponents() {
setLayout(new GridLayout(0, 2));
for(int i = 0; i < MAX; i++) {
add(createComboPanel());
add(createPanelWithTextFields());
}
pack();
}
public Component createComboPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JComboBox<>(new String[] { "First Option", "Second Option", "Third Option" }), BorderLayout.NORTH);
return panel;
}
private Component createPanelWithTextFields() {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(new JTextField(30));
panel.add(new JTextField(30));
panel.add(new JTextField(30));
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
new BorderLayoutTest().setVisible(true);
}
});
}
}

Take a look at GridBagLayout. You can use your window like a table.
myPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
JLabel lbl = new JLabel("bla");
myPanel.add(lbl, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 3;
JTextField tf = new JTextField();
myPanel.add(tf, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 3;
JTextField othertf = new JTextField();
myPanel.add(othertf, gbc);
You can even set weights and so on for the GridBagConstraints. It is completly adjusted as table. That will result in something like that:
label textfield
textfield
Just re-read the question. Just replace the JLabels with JComboBoxes and it answers your question a little bit better ;)

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

This GUI is displaying nothing after setting BoxLayout

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI_Borrower extends JFrame implements ActionListener {
JPanel panel = new JPanel();
JLabel lblName = new JLabel("Name:");
JLabel lblProg = new JLabel("Program:");
JLabel lblId = new JLabel("Library ID: ");
JLabel lblTitle = new JLabel("Add Borrower");
JTextField txtName = new JTextField(10);
JTextField txtProg = new JTextField(10);
JTextField txtId = new JTextField(10);
static int counter = 19000;
JButton btnSubmit = new JButton("Submit");
public GUI_Borrower() {
super("Add Borrower");
makeFrame();
showFrame();
}
public void makeFrame() {
lblTitle.setFont(new Font("Forte", Font.PLAIN, 40));
lblTitle.setForeground(Color.BLUE);
add(lblTitle);
add(lblName);
add(txtName);
add(lblProg);
add(txtProg);
add(lblId);
add(txtId);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(btnSubmit);
btnSubmit.addActionListener(this);
}
public void showFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (ae.getActionCommand().equals("Confirm")) {
txtName.setText("");
txtProg.setText("");
btnSubmit.setText("Submit");
} else if (source == btnSubmit) {
if (txtName.getText().equals("") && txtProg.getText().equals("")) {
txtId.setText("No entry of both");
} else if (txtName.getText().equals("")) {
txtId.setText("No entry of Name");
} else if (txtProg.getText().equals("")) {
txtId.setText("No entry of Program");
} else {
counter++;
txtId.setText("" + counter);
btnSubmit.setText("Confirm");
}
}
}
public static void main(String[] args) {
new GUI_Borrower();
}
}
I tried adding BoxLayout because all the text fields and labels are on one line. So I tried box Layout and failed.
Can anyone show me how to make it like the title one line, label Different line, button different line?
Like this:
As camickr says in his comment, you generally use a GridBagLayout to create a form.
I reworked your code because I hope to show a better way to code a GUI panel.
Here's the GUI.
The major changes I made include:
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that all Swing components are created and executed on the Event Dispatch Thread.
I organized the GUI code into three methods so I could focus on one part of the GUI at a time. The JFrame is created in the run method. The title JPanel is created in the createTitlePanel method. The form JPanel is created in the createFormPanel method. The code for the JFrame will rarely change from Swing application to Swing application.
I use Swing components. I don't extend Swing components, or any Java class, unless I intend to override one of the class methods.
The createFormPanel class uses the GridBagLayout to organize the labels and text fields in columns. You can think of the GridBagLayout as a flexible grid. The cells of the grid don't have to be the same size. The Oracle tutorial, How to Use GridBagLayout, has another example.
I put the ActionListener in a separate class. I made it an inner class in this example so I could paste the code as one file. Generally, you should put separate classes in separate files. It makes each class shorter and easier to understand.
Here's the runnable, example code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class BorrowerGUI implements Runnable {
private static int ID_COUNTER = 19000;
public static void main(String[] args) {
SwingUtilities.invokeLater(new BorrowerGUI());
}
private JButton btnSubmit;
private JTextField txtName;
private JTextField txtProg;
private JTextField txtId;
#Override
public void run() {
JFrame frame = new JFrame("Add Borrower");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTitlePanel(), BorderLayout.BEFORE_FIRST_LINE);
frame.add(createFormPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createTitlePanel() {
JPanel panel = new JPanel(new FlowLayout());
JLabel lblTitle = new JLabel("Add Borrower");
lblTitle.setFont(new Font("Forte", Font.PLAIN, 40));
lblTitle.setForeground(Color.BLUE);
panel.add(lblTitle);
return panel;
}
private JPanel createFormPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.gridx = 0;
gbc.gridy = 0;
JLabel lblName = new JLabel("Name:");
panel.add(lblName, gbc);
gbc.gridx++;
txtName = new JTextField(20);
panel.add(txtName, gbc);
gbc.gridx = 0;
gbc.gridy++;
JLabel lblProg = new JLabel("Program:");
panel.add(lblProg, gbc);
gbc.gridx++;
txtProg = new JTextField(20);
panel.add(txtProg, gbc);
gbc.gridx = 0;
gbc.gridy++;
JLabel lblId = new JLabel("Library ID:");
panel.add(lblId, gbc);
gbc.gridx++;
txtId = new JTextField(20);
txtId.setEditable(false);
panel.add(txtId, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = 2;
btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new SubmitListener());
panel.add(btnSubmit, gbc);
return panel;
}
public class SubmitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (ae.getActionCommand().equals("Confirm")) {
txtName.setText("");
txtName.requestFocus();
txtProg.setText("");
txtId.setText("");
btnSubmit.setText("Submit");
} else if (source == btnSubmit) {
if (txtName.getText().equals("") &&
txtProg.getText().equals("")) {
txtId.setText("No entry of both");
} else if (txtName.getText().equals("")) {
txtId.setText("No entry of Name");
} else if (txtProg.getText().equals("")) {
txtId.setText("No entry of Program");
} else {
ID_COUNTER++;
txtId.setText("" + ID_COUNTER);
btnSubmit.setText("Confirm");
}
}
}
}
}
Edited to add: If you want the title JLabel to be right-justified, you'll have to switch to a BorderLayout. I added an empty border so the text wouldn't be on the right edge of the JFrame.
Here's the changed method.
private JPanel createTitlePanel(String title) {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 10));
JLabel lblTitle = new JLabel(title);
lblTitle.setFont(new Font("Forte", Font.PLAIN, 40));
lblTitle.setForeground(Color.BLUE);
panel.add(lblTitle, BorderLayout.AFTER_LINE_ENDS);
return panel;
}

Why JTextArea is small?

I try to make a simple app in SWING: using BorderLayout layout on the JFrame, i put on SOUTH an executing button, on WEST a panel that contains a combobox and on EAST a panel that contains 2 JTextAreas. The problem is, both JTextArea are damn small. Any help and explanation will be welcomed.
This is the code for the panel with the 2 text areas
package cipher;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.Border;
class TextPanel extends JPanel {
private JTextArea inputArea, outputArea;
public TextPanel() {
initSize();
initTextArea();
initBorder();
initLayout();
packing();
}
private void packing() {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
add(inputArea,gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1;
gbc.weighty = 1;
add(outputArea,gbc);
}
private void initBorder() {
Border outer = BorderFactory.createEmptyBorder(5, 5, 5, 5);
Border inner = BorderFactory.createTitledBorder("Text");
setBorder(BorderFactory.createCompoundBorder(outer,inner));
}
private void initLayout() {
setLayout(new GridBagLayout());
}
private void initTextArea() {
inputArea = new JTextArea();
inputArea.setPreferredSize(new Dimension(385,400));
outputArea = new JTextArea();
outputArea.setPreferredSize(new Dimension(385,400));
}
private void initSize() {
Dimension size = getPreferredSize();
size.width = 390;
setPreferredSize(size);
}
}
I've tried using setSize(x,y) but without success. I've tried using JTextArea(rows,columns) but without success. I've used even setPreferredSize with a Dimension but no succeed.
The probable cause of your issue is the container area is smaller than the preferred size of the text area, GridBagLayout will then default to the minimum size instead.
This is a good example of why you should avoid setting these properties directly and instead make use of the layout manager and the components properties.
To start with, make use of the JTextArea's column and rows properties. This will make a better "guess" at the amount of space it needs to display text to fit within these confines.
Second, use GridBagConstraints#fill to override GridBagLayout and force it to make use of the available space
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
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 TextPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TextPanel extends JPanel {
private JTextArea inputArea, outputArea;
public TextPanel() {
initTextArea();
initBorder();
initLayout();
packing();
}
private void packing() {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(inputArea, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(outputArea, gbc);
}
private void initBorder() {
Border outer = BorderFactory.createEmptyBorder(5, 5, 5, 5);
Border inner = BorderFactory.createTitledBorder("Text");
setBorder(BorderFactory.createCompoundBorder(outer, inner));
}
private void initLayout() {
setLayout(new GridBagLayout());
}
private void initTextArea() {
// The borders are just here so you can see the different text areas
inputArea = new JTextArea(10, 20);
inputArea.setBorder(new LineBorder(Color.BLACK));
outputArea = new JTextArea(10, 20);
outputArea.setBorder(new LineBorder(Color.BLACK));
}
}
}
I'd also change...
inputArea = new JTextArea(10, 20);
inputArea.setBorder(new LineBorder(Color.BLACK));
outputArea = new JTextArea(10, 20);
outputArea.setBorder(new LineBorder(Color.BLACK));
and make use of JScrollPanes instead of LineBorder

How to get my JButtons to be on the left and not in the middle

I'm a little lost here, when I run the program the buttons are in the middle of the input and not directly on the bottom aligned with it. I'm not sure what I'm doing wrong. I'm also trying to find out how to get statistics for my input like min and max value, and average word size. I'm a little lost, thanks!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.util.Arrays;
public class CopyTextPanel extends JPanel
{
private JTextField input;
private JLabel output, inlabel, outlabel;
private JButton compute, clear;
private JPanel panel, panel1, panel2;
public CopyTextPanel()
{
setLayout (new BoxLayout(this, BoxLayout.Y_AXIS));
inlabel = new JLabel("Input: ");
outlabel = new JLabel("Text Statistics Result: ");
input = new JTextField (50);
output = new JLabel();
compute = new JButton("Compute Statistics");
compute.addActionListener (new ButtonListener());
clear = new JButton("Clear Text");
clear.addActionListener (new ButtonListener());
panel = new JPanel();
panel1 = new JPanel();
panel2 = new JPanel();
output.setMaximumSize (new Dimension(500, 30));
output.setMinimumSize (new Dimension(500, 30));
panel.setMaximumSize (new Dimension(500, 30));
panel.setMinimumSize (new Dimension(500, 30));
panel.setBackground(Color.gray);
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(inlabel);
panel.add(input);
panel1.setLayout(new BoxLayout(panel1, BoxLayout.X_AXIS));
panel1.add(compute);
panel1.add(clear);
add (Box.createRigidArea (new Dimension(0, 10)));
panel2.setLayout(new BoxLayout(panel2, BoxLayout.X_AXIS));
panel2.add(outlabel);
panel2.add(output);
setMaximumSize (new Dimension(600, 250));
setMinimumSize (new Dimension(600, 250));
setBackground(Color.white);
add (panel);
add (panel1);
add (panel2);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
String inputText = input.getText();//sets what is typed by the user
to a String object
String[] splitted = inputText.trim().split("\\p{javaSpaceChar}
{1,}");//makes a String array, and trims all the whitespaces from the user
input
int numberofWords = splitted.length;//it then sets splitted length
to an integer
String numow = Integer.toString(numberofWords);// finally it makes
the numberofwords int into a string
Arrays.sort(splitted);
if (event.getSource()==compute)//if the user presses the compute
button
{
output.setText (numow + " words; " );//the output is the string
of integers of how many words were typed
}
else//if the user presses another button
input.setText(" "); // clear text filed after copying
}
}
}
So based on the desired result...
I would recommend considering using a series of panels, dedicated to generating the layout requirements for each row, then wrapping those together into a single container.
For my money, GridBagLayout presents the most flexible option, while also presenting one of the more complicated at the same time.
This example focuses solely on the layout requirements, you'll have to figure out how to apply the functionality to it later.
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.HeadlessException;
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.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Test");
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() throws HeadlessException {
setBorder(new EmptyBorder(5, 5, 5, 5));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 2, 2, 2);
JPanel fieldPane = new JPanel(new GridBagLayout());
JTextField inputField = new JTextField("Computer Science 1");
fieldPane.add(new JLabel("Input Text:"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
fieldPane.add(inputField, gbc);
JPanel buttonPane = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 2, 2, 2);
buttonPane.add(new JButton("Computer Statistics"), gbc);
gbc.anchor = GridBagConstraints.LINE_START;
gbc.weightx = 1;
buttonPane.add(new JButton("Clear Text"), gbc);
JPanel resultsPane = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 2, 2, 2);
resultsPane.add(new JLabel("Text Statistics Result:"));
gbc.anchor = GridBagConstraints.LINE_START;
gbc.weightx = 1;
resultsPane.add(new JLabel("3 words"), gbc);
gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(fieldPane, gbc);
add(buttonPane, gbc);
add(resultsPane, gbc);
}
}
}
I strongly recommend having a look at Laying Out Components Within a Container for more details about how various layout managers work
You should use Layouts such as BorderLayout that might help you.
Change the JPanels by doing panel.add(new JButton("East"),BorderLayout.EAST);
etc.. I hope it helps. If you dont use layouts they will end up randomized.

How do I use GridBagConstraints setRows and setColumns?

How do I use setRows and setColumns to change the amount of rows and columns in my window?
Here's a copy of my code and where I tried to implement the set rows and columns:
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 java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.*;
#SuppressWarnings("unused")
public class GUI
{
public static void main(String[] args)
{
new GUI();
}
public GUI()
{
JFrame AG = new JFrame("Adventure Game");
AG.setExtendedState(JFrame.MAXIMIZED_BOTH);
AG.setResizable(true);
AG.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p=new JPanel();
p.setLayout (new GridBagLayout());
AG.add(p);
GridBagConstraints GBC = new GridBagConstraints();
GridLayout.setRows(100);//heres the set rows<<<<<<<<<<<<<<<<<<<
GridLayout.setColumns(100);//heres the set columns<<<<<<<<<<<<<<<<<<<
AG.getContentPane().add(p, BorderLayout.NORTH);
JButton saveButton =new JButton("Save");
JButton loadButton =new JButton("Load");
JButton optionsButton = new JButton("Options");
JLabel textBox= new JLabel("Story line will go here.");
JLabel label11 = new JLabel("Test 1");
GBC.gridx = 0;
GBC.gridy = 1;
p.add(label11,GBC);
JLabel label12 = new JLabel("Test 2");
GBC.gridx = 0;
GBC.gridy = 2;
p.add(label12,GBC);
JLabel label13 = new JLabel("Test 3");
GBC.gridx = 0;
GBC.gridy = 3;
p.add(label13,GBC);
JLabel label14 = new JLabel("Test 4");
GBC.gridx = 0;
GBC.gridy = 5;
p.add(label14,GBC);
AG.setVisible(true);
}
}
GridBagConstraints work with the GridBagLayout, not the GridLayout. Your call to GridLayout doesn't do anything.
To set the rows and columns with GridBagConstraints, you need to use GBC.gridx = ...; and GBC.gridy = ...;
If you are trying to place gaps between your buttons, empty GridBag cells are not the way to do it; use the insets of your GridBagConstraints for that.
To make a component in a GridBagLayout disappear without the other components shifting around, place the button in a JPanel with a CardLayout, and make sure you add that JPanel to your GridBagLayout instead of the button:
private JButton optionalButton;
private void buildWindow() {
// ...
optionalButton = new JButton("Optional Action");
JPanel optionalButtonPanel = new JPanel(new CardLayout());
optionalButtonPanel.add(optionalButton, "BUTTON");
optionalButtonPanel.add(new JLabel(), "BLANK");
// ...
}
private void setOptionalButtonVisible(boolean visible) {
Container optionalButtonPanel = optionalButton.getParent();
CardLayout layout = (CardLayout) optionalButtonPanel.getLayout();
layout.show(optionalButtonPanel, visible ? "BUTTON" : "BLANK");
}
CardLayout always displays one and only one of its components, but it sizes its associated container to fit all the components, including the invisible ones.

Categories