Java Swing Alignment problem with BoxLayout - java

I have three components inside a top to down boxLayout (JLabel, JTextField, JButton). The problem is that when i set the X alignment for the label it looks as if i would've changed the X alignment of the button and vice versa, only when both have the same alignment it works fine.
When the screen gets wider both components take a weird alignment.
when both components have the same alignment everything works fine.
here is my code:
public void create(){
JPanel panel = new JPanel();
BoxLayout boxLayout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.setLayout(boxLayout);
panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
JLabel etiqueta = new JLabel("Numero de consultorio: ");
etiqueta.setBackground(Color.BLUE);
etiqueta.setOpaque(true);
etiqueta.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.add(etiqueta);
JTextField consultorio = new JTextField();
panel.add(consultorio);
JButton registrar = new JButton("Registrar");
registrar.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.add(registrar);
this.getContentPane().add(panel, BorderLayout.CENTER);
}

Here is the proposed by Andrew Thompson solution:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
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.WindowConstants;
public class TestFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new TestFrame()::create);
}
private void create() {
JPanel panel = new JPanel();
BoxLayout boxLayout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.setLayout(boxLayout);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JLabel etiqueta = new JLabel("Numero de consultorio: ");
etiqueta.setBackground(Color.BLUE);
etiqueta.setOpaque(true);
JPanel layout = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0));
layout.add(etiqueta);
panel.add(layout);
JTextField consultorio = new JTextField();
panel.add(consultorio);
JButton registrar = new JButton("Registrar");
layout = new JPanel(new FlowLayout(FlowLayout.TRAILING, 0, 0));
layout.add(registrar);
panel.add(layout);
JFrame frm = new JFrame("Test");
frm.getContentPane().add(panel, BorderLayout.CENTER);
frm.pack();
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
}

Related

Java.Swing BorderLayout issue

So I'm trying to get the button on the bottom right and the text field taking up the bottom left but it keeps switching around for some reason. I think its borderLayout being stupid. I'm a noob at Java btw. Here's my code:
package textchat;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
public class window extends JFrame{
public static void main(String[] args)
{
new window();
}
public window()
{
//Window Config
//JFrame frame = new JFrame();
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension dm = tk.getScreenSize();
this.setSize(400,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("CALI V1");
this.setExtendedState(this.getExtendedState() | JFrame.MAXIMIZED_BOTH);
//this.setLayout(null);
int Width = this.getWidth();
//Panel(s)
JPanel Panel = new JPanel();
Panel.setLayout(new BorderLayout());
JPanel PanelSouth = new JPanel();
JPanel PanelEast = new JPanel();
JPanel PanelWest = new JPanel();
//button
JButton btn = new JButton("SEND");
//Text Area
JTextArea txt = new JTextArea(100 , 100);
txt.setText("TEXT IS HERE");
//Text Field
JTextField fld = new JTextField("Type Here",15);
//Adding to the panel
Panel.add(txt);
PanelSouth.add(PanelEast, BorderLayout.EAST);
PanelSouth.add(PanelWest, BorderLayout.WEST);
PanelEast.add(btn);
PanelWest.add(fld);
//adding to frame
this.add(Panel);
this.add(PanelSouth , BorderLayout.SOUTH);
this.setVisible(true);
}
}
While using BorderLayout in such a way kind of works, you should
not use it in such a way. Besides, your example has several issues.
For instance, you did not start the application on the EDT (Event Dispatch Tread).
Here is a working example that creates your inteded layout. It uses the powerful GroupLayout manager.
package com.zetcode;
import java.awt.Container;
import java.awt.EventQueue;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class TextChatEx extends JFrame {
public TextChatEx() {
initUI();
}
private void initUI() {
JTextArea area = new JTextArea(15, 15);
JTextField field = new JTextField(15);
JButton sendButton = new JButton("Send");
createLayout(area, field, sendButton);
setTitle("Text chat");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void createLayout(JComponent... arg) {
Container pane = getContentPane();
GroupLayout gl = new GroupLayout(pane);
pane.setLayout(gl);
gl.setAutoCreateContainerGaps(true);
gl.setAutoCreateGaps(true);
gl.setHorizontalGroup(gl.createParallelGroup()
.addComponent(arg[0])
.addGroup(gl.createSequentialGroup()
.addComponent(arg[1])
.addComponent(arg[2]))
);
gl.setVerticalGroup(gl.createSequentialGroup()
.addComponent(arg[0])
.addGroup(gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(arg[1])
.addComponent(arg[2]))
);
pack();
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
TextChatEx ex = new TextChatEx();
ex.setVisible(true);
});
}
}
GroupLayout is a powerful layout manager; with this manager, you don't have to create a bunch of panels to create some basic layout.
public TextChatEx() {
initUI();
}
The GUI creation is delegated to the initUI() method. Rather than placing all the code into the constructor, we use a specialized method.
EventQueue.invokeLater(() -> {
TextChatEx ex = new TextChatEx();
ex.setVisible(true);
});
Each Swing application should be placed on the EDT. Failing to do this can lead to hard to find bugs in the future.

Can't add JPanel to BorderLayout.CENTER

I am just Starting out with JAVA.
I have say a JPanel x, a JPanel y and a BorderLayout JPanel z.
When I try to change the contents of the center of z from default x t y, it works but it doesn't go back to x. I AM calling revalidate() after each. Help please.
The class below is where the problem is.
Main Class Below
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.LayoutManager;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
#SuppressWarnings({ "serial", "unused" })
public class Manager extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Manager frame = new Manager();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Manager() {
setTitle("Popper");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
height = height/5.1;
setSize((int)width, (int)height);
setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(0,0,0,0));
setContentPane(contentPane);
contentPane.setBackground(new Color(14,99,165));
contentPane.setLayout(new BorderLayout(0, 0));
ImageIcon image = new ImageIcon("D:/popper26.png");
setIconImage(image.getImage());
JPanel pane = new JPanel();
calcu cal = new calcu();
curr nup = new curr();
stopc newst = new stopc();
pane.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel mainpanel = new JPanel();
BorderLayout x =new BorderLayout(0,0);
mainpanel.setLayout(x);
mainpanel.setBackground(Color.WHITE);
JLabel madeby = new JLabel("Project By Anant Bhasin");
madeby.setHorizontalAlignment(SwingConstants.RIGHT);
mainpanel.add(madeby, BorderLayout.SOUTH);
JPanel logo = new JPanel();
logo.setLayout(new FlowLayout(FlowLayout.CENTER));
JLabel jk = new JLabel(new ImageIcon("D:/popper2.png"));
logo.add(jk, BorderLayout.NORTH);
logo.setBackground(Color.decode("#1abc9c"));
mainpanel.add(logo, BorderLayout.NORTH);
mainpanel.add(cal, BorderLayout.CENTER);
contentPane.add(mainpanel, BorderLayout.CENTER);
JPanel newj = new JPanel();
BoxLayout bxl = new BoxLayout(newj, BoxLayout.PAGE_AXIS);
newj.setLayout(bxl);
newj.setBackground(new Color(58,115,144));
contentPane.add(newj, BorderLayout.WEST);
Border emptyBorder = BorderFactory.createEmptyBorder();
JButton calc = new JButton(new ImageIcon("D:/calc.png"));
newj.add(calc);
calc.setBorder(emptyBorder);
calc.setFocusPainted(false);
calc.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
mainpanel.add(BorderLayout.CENTER, cal);
mainpanel.revalidate();
}
});
JButton currb = new JButton(new ImageIcon("D:/curr.png"));
currb.setBorder(emptyBorder);
newj.add(currb);
currb.setFocusPainted(false);
currb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
mainpanel.add(BorderLayout.CENTER, nup);
mainpanel.revalidate();
}
});
JButton stop = new JButton(new ImageIcon("D:/stop.png"));
stop.setBorder(emptyBorder);
newj.add(stop);
stop.setFocusPainted(false);
stop.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
mainpanel.add(BorderLayout.CENTER, newst);
mainpanel.revalidate();
}
});
JButton timer = new JButton(new ImageIcon("D:/timer.png"));
timer.setBorder(emptyBorder);
newj.add(timer);
timer.setFocusPainted(false);
JButton memo = new JButton(new ImageIcon("D:/memo.png"));
memo.setBorder(emptyBorder);
newj.add(memo);
memo.setFocusPainted(false);
}
}
A BorderLayout is not designed to display multiple components with the same constraint because of the way ZOrder painting works in Swing.
If you need the ability to swap panels, then you should be using a CardLayout.
A CardLayout lets you specify the name of the panel that you want to display. Read the section from the Swing tutorial on How to Use CardLayout for more information and working examples.
You set up the layout with code like:
JPanel main = new JPanel( new CardLayout() );
main.add(panelx, "X");
main.add(panely, "Y");
Then to swap a panel you use code like:
CardLayout cl = (CardLayout)(main.getLayout());
cl.show(main, "X");

JPanels appear to go off the frame?

I am working on an assignment "of sorts" not a school assignment. Having said that, any ideas would be great.
I am using WindowBuilder in Eclipse and have created a basic form. I have used nested JPanel components on a border layout to create it. For some reason, the panels appear as though they are spilling over the edges of the JFrame. I have the frame dimensions set to (500, 400) and the panels are various sizes, but none greater than 400 wide.
Code:
package SwingAssignment;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import java.awt.GridBagLayout;
import javax.swing.BoxLayout;
import net.miginfocom.swing.MigLayout;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import com.jgoodies.forms.factories.FormFactory;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.border.BevelBorder;
import javax.swing.SwingConstants;
public class Swing_Assignemnt {
private JFrame frmWindowBuilderAssignment;
private JPanel Center_Panel;
private JTextArea textArea;
private JPanel panel_1;
private JPanel panel;
private JTextField textField;
private JPanel panel_2;
private JTextArea txtrTextarea_0;
private JTextArea txtrTextarea_1;
private JPanel panel_3;
private JTextArea txtrTextareasouth;
private JLabel lblNewLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Swing_Assignemnt window = new Swing_Assignemnt();
window.frmWindowBuilderAssignment.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Swing_Assignemnt() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmWindowBuilderAssignment = new JFrame();
frmWindowBuilderAssignment.setTitle("Window Builder Assignment");
//frmWindowBuilderAssignment.setBounds(500, 500, 650, 600);
frmWindowBuilderAssignment.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmWindowBuilderAssignment.getContentPane().setLayout(new BorderLayout(0, 0));
frmWindowBuilderAssignment.setVisible(true);
frmWindowBuilderAssignment.setSize(394, 500);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
//frmWindowBuilderAssignment.pack();
//frmWindowBuilderAssignment.pack();
frmWindowBuilderAssignment.setVisible( true );
panel = new JPanel();
panel.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
frmWindowBuilderAssignment.getContentPane().add(panel, BorderLayout.NORTH);
panel.setPreferredSize(new Dimension(200, 40));
panel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
//panel.setBounds(20, 10, 200, 400);
panel.setVisible(true);
JComboBox comboBox = new JComboBox();
panel.add(comboBox);
comboBox.setPreferredSize(new Dimension(125, 20));
comboBox.setVisible(true);
textField = new JTextField();
panel.add(textField);
textField.setColumns(10);
textField.setVisible(true);
panel_2 = new JPanel();
panel_2.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
frmWindowBuilderAssignment.getContentPane().add(panel_2, BorderLayout.CENTER);
panel_2.setLayout(new GridLayout(1, 2, 2, 2));
panel_2.setPreferredSize(new Dimension(200, 400));
panel_2.setVisible(true);
txtrTextarea_0 = new JTextArea();
txtrTextarea_0.setText("textArea_0");
panel_2.add(txtrTextarea_0);
txtrTextarea_0.setPreferredSize(new Dimension(50, 30));
txtrTextarea_0.setVisible(true);
txtrTextarea_1 = new JTextArea();
txtrTextarea_1.setText("textArea_1");
panel_2.add(txtrTextarea_1);
txtrTextarea_1.setVisible(true);
txtrTextarea_1.setPreferredSize(new Dimension(50, 30));
panel_3 = new JPanel();
panel_3.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
frmWindowBuilderAssignment.getContentPane().add(panel_3, BorderLayout.SOUTH);
panel_3.setLayout(new GridLayout(2, 1, 2, 2));
panel_3.setVisible(true);
txtrTextareasouth = new JTextArea();
txtrTextareasouth.setText("textArea_South");
panel_3.add(txtrTextareasouth);
txtrTextareasouth.setVisible(true);
txtrTextareasouth.setPreferredSize(new Dimension(200, 150));
lblNewLabel = new JLabel("Status Label");
panel_3.add(lblNewLabel);
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setPreferredSize(new Dimension(200, 20));
}
}
What it looks like:
After some code changes, this is what I now have, I am not sure how to resize the label at the bottom. It only needs to be about 15 tall.
Don't use setBounds() or setPreferredSize(). Each Swing component should determine its own preferred size and the layout manager will then position the components based on the rules of the layout manager.
Don't use setVisible(true) on all your Swing components (except for the JFrame). By default Swing components are visible.
You should add all the components to the frame before using:
frame.pack()
frame.setVisible( true );
try using
frmWindowBuilderAssignment.pack();
at the End of your initialising Method.
This set all of your Components to their preferred Sizes and adjust the Frame.

How do I left and right align components in Swing?

I have what appears to be a simple issue. I have some labels that I'd like to align to the left but when I resize, they start to drift towards the middle. This is going to throw off the alignment of other components I plan on adding. What do I do to keep them to the left?
It's short, easy code, not sure what my problem is here:
package com.protocase.notes.views;
import com.protocase.notes.model.Note;
import com.protocase.notes.model.User;
import java.awt.Component;
import java.util.Date;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.BevelBorder;
/**
* #author dah01
*/
public class NotesPanel extends JPanel{
public NotesPanel(Note note){
this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
JLabel creatorLabel = new JLabel("Note by "+note.getCreator()+ " # "+note.getDateCreated());
creatorLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
creatorLabel.setHorizontalAlignment(JLabel.LEFT);
JTextArea notesContentsArea = new JTextArea(note.getContents());
notesContentsArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(notesContentsArea);
JLabel editorLabel = new JLabel(" -- Last edited by "+note.getLastEdited() +" at "+note.getDateModified());
editorLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
editorLabel.setHorizontalAlignment(JLabel.LEFT);
this.add(creatorLabel);
this.add(scrollPane);
this.add(editorLabel);
this.setBorder(new BevelBorder(BevelBorder.RAISED));
}
public static void main(String[] args) {
JFrame frame = new JFrame("Notes Panel");
Note note = new Note();
User user = new User();
user.setFirstName("d");
user.setLastName("h");
user.setUserID("dah01");
note.setCreator(user);
note.setLastEdited(user);
note.setDateCreated(new Date());
note.setDateModified(new Date());
note.setContents("A TEST CONTENTS");
NotesPanel np = new NotesPanel(note);
JScrollPane scroll = new JScrollPane(np);
frame.setContentPane(scroll);
np.setVisible(true);
frame.setVisible(true);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
If you want to align things in your panel, you have to align everything. You forgot to align your JScrollPane. If you add this line to your code, the alignment should be fixed for you:
scrollPane.setAlignmentX(JScrollPane.LEFT_ALIGNMENT);
And what your new constructor would look like:
public NotesPanel(Note note){
this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
JLabel creatorLabel = new JLabel("Note by "+note.getCreator()+ " # "+note.getDateCreated());
creatorLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
creatorLabel.setHorizontalAlignment(JLabel.LEFT);
JTextArea notesContentsArea = new JTextArea(note.getContents());
notesContentsArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(notesContentsArea);
scrollPane.setAlignmentX(JScrollPane.LEFT_ALIGNMENT);
JLabel editorLabel = new JLabel(" -- Last edited by "+note.getLastEdited() +" at "+note.getDateModified());
editorLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
editorLabel.setHorizontalAlignment(JLabel.LEFT);
this.add(creatorLabel);
this.add(scrollPane);
this.add(editorLabel);
this.setBorder(new BevelBorder(BevelBorder.RAISED));
}
As per your comments, I would recommend you to go with some other layout, I would recommend MigLayout
Here you go with MigLayout:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.miginfocom.swing.MigLayout;
import javax.swing.JLabel;
import javax.swing.JTextArea;
public class MigLayoutDemo {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new MigLayoutDemo();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MigLayoutDemo() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.setContentPane(contentPane);
contentPane.setLayout(new MigLayout("", "[grow]", "[][grow][]"));
JLabel lblLabel = new JLabel("Label 1");
lblLabel.setBorder(BorderFactory.createLineBorder(Color.red));
contentPane.add(lblLabel, "cell 0 0,alignx left");
JTextArea textArea = new JTextArea();
contentPane.add(textArea, "cell 0 1,grow");
JLabel lblLabel_1 = new JLabel("Label 2");
lblLabel_1.setBorder(BorderFactory.createLineBorder(Color.red));
contentPane.add(lblLabel_1, "cell 0 2,alignx left");
frame.setVisible(true);
}
}
OUTPUT :
As you can see labels marked with red border are not stretched to the middle, they are left aligned .
Using a BorderLayout definitely fixes your issue.
this.setLayout(new BorderLayout());
this.add(creatorLabel, BorderLayout.NORTH);
this.add(scrollPane);
this.add(editorLabel, BorderLayout.SOUTH);
Alternatively, if you have more components to display in the UI than what you show in the sample code, you can still use a GridBagLayout. I know that not many people like to use this one because it's quite verbose but in my opinion, it's the most powerful layout manager of swing.

How to make JTextArea Stick to the window

Hello I would like to make this TextArea stick to the windows size whene I resize it by mouse, the same way as lower buttons does. This is the code it is perfectly working no bugs, please have a glance at it.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Rozklady extends JFrame {
public Rozklady() {
super();
}
public void createGUI(){
setPreferredSize(new Dimension(400,150));
JPanel jp = new JPanel();
// jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS));
jp.setLayout(new GridLayout(0,1));
JPanel gora = new JPanel();
JPanel dol = new JPanel();
pack();
JTextArea jt1 = new JTextArea("JF1");
gora.add(jt1);
jt1.setPreferredSize(new Dimension(getWidth(),getHeight()/2));
dol.setLayout(new BorderLayout());
JPanel lewo = new JPanel();
JPanel prawo = new JPanel();
JPanel srodek = new JPanel();
dol.add(lewo, BorderLayout.EAST);
dol.add(prawo,BorderLayout.WEST);
dol.add(srodek, BorderLayout.CENTER);
lewo.setLayout(new GridLayout(2,2));
prawo.setLayout(new GridLayout(2,2));
srodek.setLayout(new GridLayout(0,1));
for(int i = 0; i < 4; i++){
lewo.add(new JButton(i+""));
prawo.add(new JButton(i+""));
if(i < 3){
srodek.add(new JTextField("JF"+i));
}
}
jp.add(gora);
jp.add(dol);
add(jp);
setVisible(true);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new Rozklady().createGUI();
}
});
}
}
Use BorderLayout for you gora panel. Put text area to the center:
gora.setLayout(new BorderLayout());
gora.add(jt1, BorderLayout.CENTER);
// declare a GridLayout in constructor, one component will 'fill the container'
JPanel gora = new JPanel(new GridLayout());
JPanel dol = new JPanel();
// this should be called after all components are added! BNI
pack();
JTextArea jt1 = new JTextArea("JF1");
// be sure to use a scroll pane for multi-line text components
gora.add(new JScrollPane(jt1));
// ..
Stretching a single component to fill the available space can be achieved various was. Two common ways are using either BorderLayout as mentioned by AlexR or GridLayout. See this answer for sample code. I prefer GridLayout because it is shorter (less typing). ;)

Categories