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.
Related
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);
}
}
Issues:
Need the scrollbar to increase to the panel height even when maximized.
When clicked on 1 or 2, need to change the selection color to some other color.
When clicked on 'x', the font should change.
Code:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.Color;
import javax.swing.border.CompoundBorder;
import java.awt.Dimension;
public class Sample1 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Sample1 frame = new Sample1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Sample1() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
final JPanel panel = new JPanel();
panel.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
contentPane.add(panel, BorderLayout.WEST);
Vector str = new Vector<>();
Vector v = new Vector();
v.add("1");
v.add("x");
Vector v1 = new Vector();
v1.add("2");
v1.add("x");
str.addElement(v);
str.addElement(v1);
DefaultTableModel mo = new DefaultTableModel(str,str);
final JTable list = new JTable(mo);
list.setBorder(new CompoundBorder());
list.setBackground(new Color(238, 232, 170));
list.setShowGrid(false);
// list.setListData(str);
list.getColumnModel().getColumn(1).setPreferredWidth(10);
JScrollPane scrollPane = new JScrollPane(list);
scrollPane.setPreferredSize(new Dimension(70, 300));
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
list.setTableHeader(null);
list.setFillsViewportHeight(true);
panel.add(scrollPane);
final JPanel panel_1 = new JPanel();
panel_1.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
contentPane.add(panel_1, BorderLayout.CENTER);
panel_1.setLayout(new CardLayout(0, 0));
JPanel panel_2 = new JPanel();
panel_1.add(panel_2, "1");
JLabel lblNewLabel = new JLabel("First");
panel_2.add(lblNewLabel);
JPanel panel_3 = new JPanel();
panel_1.add(panel_3, "2");
JLabel lblNewLabel_1 = new JLabel("Second");
panel_3.add(lblNewLabel_1);
list.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e){
int row = list.getSelectedRow();
int column = list.getSelectedColumn();
CardLayout cl = (CardLayout) panel_1.getLayout();
cl.show(panel_1,list.getValueAt(row, column).toString());
}
});
// list.add
}
}
Need the scrollbar to increase to the panel height even when maximized.
JPanel panel = new JPanel(new BorderLayout());
This will solve your first problem.
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.
I'm creating an about JFrame for my program. I have an icon which I used for the program and I have that show up as the first thing on the about JFrame, but I'm having issues trying to center the image. If I do some kind of centering it screws up the whole alignment of everything else.
I'm trying to have all the JLabels, other than the icon, to be left aligned. Then have the icon aligned to the center.
I had to remove some personal information, whatever I did remove I put them between "[]".
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class About extends JFrame {
public About() {
super("About [PROGRAM]");
setIconImage([PROGRAM].getInstance().setIcon());
JPanel main = new JPanel();
main.setLayout(new BoxLayout(main, BoxLayout.Y_AXIS));
main.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
JLabel icon = new JLabel("", new ImageIcon(getClass().getResource(Constants.ICON_FULL)), JLabel.CENTER);
JLabel name = new JLabel("[PROGRAM]");
JLabel expandedName = new JLabel("[PROGRAM DESCRIPTION]");
JLabel copyright = new JLabel("[COPYRIGHT JUNK]");
JLabel credits = new JLabel("[CREDITS]");
name.setFont(new Font(name.getFont().getFamily(), Font.BOLD, 18));
copyright.setBorder(BorderFactory.createEmptyBorder(0,0,10,0));
main.add(icon);
main.add(Box.createRigidArea(new Dimension(0, 10)));
main.add(name);
main.add(expandedName);
main.add(copyright);
main.add(credits);
add(main);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
}
Consider using some layouts to help you out. Ones that come to mind include BorderLayout with the icon in the BorderLayout.CENTER position. You can stack stuff on one side using a BoxLayout using JPanel that is added to the main BorderLayout-using JPanel.
e.g.,
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class About extends JDialog {
public static final String IMAGE_PATH = "http://upload.wikimedia.org/wikipedia/"
+ "commons/thumb/3/39/European_Common_Frog_Rana_temporaria.jpg/"
+ "800px-European_Common_Frog_Rana_temporaria.jpg";
public About(JFrame frame) {
super(frame, "About [PROGRAM]", true);
ImageIcon myIcon = null;
try {
URL imgUrl = new URL(IMAGE_PATH);
BufferedImage img = ImageIO.read(imgUrl);
myIcon = new ImageIcon(img);
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
JPanel main = new JPanel(new BorderLayout());
main.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JLabel centerLabel = new JLabel(myIcon);
JLabel name = new JLabel("[PROGRAM]");
JLabel expandedName = new JLabel("[PROGRAM DESCRIPTION]");
JLabel copyright = new JLabel("[COPYRIGHT JUNK]");
JLabel credits = new JLabel("[CREDITS]");
name.setFont(new Font(name.getFont().getFamily(), Font.BOLD, 18));
copyright.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
int eb = 20;
centerLabel.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS));
leftPanel.add(name);
leftPanel.add(Box.createVerticalGlue());
leftPanel.add(expandedName);
leftPanel.add(copyright);
leftPanel.add(credits);
leftPanel.add(Box.createVerticalGlue());
main.add(centerLabel, BorderLayout.CENTER);
main.add(leftPanel, BorderLayout.LINE_START);
add(main);
pack();
}
public static void main(String[] args) {
final JFrame frame = new JFrame("GUI");
JPanel panel = new JPanel();
panel.add(new JButton(new AbstractAction("About") {
#Override
public void actionPerformed(ActionEvent e) {
About about = new About(frame);
about.setLocationRelativeTo(frame);
about.setVisible(true);
}
}));
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
I searched a little bit and did not find a good answer to my problem.
I am working on a gui that has to be resizable. It contains a status JTextArea that is inside a JScrollPane. And this is my problem. As long as I don't manually resize my JFrame, the "initial" layout is kept and everything looks fine. As soon as I manually resize (if the JTextArea is already in scrolled mode), the layout gets messed up.
Here is a SSCCE (I got rid of most of the parts while keeping the structure of the code. I hope it's more readable that way):
import java.awt.Color;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import net.miginfocom.swing.MigLayout;
public class Tab extends JFrame {
private static final long serialVersionUID = 1L;
private JTextArea messageTextArea;
private JPanel optionPanel, messagePanel;
private JTabbedPane plotTabPane;
public static void main(String[] args) {
final Tab tab = new Tab();
tab.setSize(1000, 600);
tab.setVisible(true);
new Thread(new Runnable() {
#Override
public void run() {
int count = 0;
tab.printRawMessage("start");
while (true) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {}
tab.printRawMessage("\ntestMessage" + count++);
}
}
}).start();
}
public Tab() {
super();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
}
private void initComponents() {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new MigLayout("insets 0", "", ""));
mainPanel.add(getLeftTopPanel(), "shrinky, top, w 450!");
mainPanel.add(getRightPanel(), "spany 5, wrap, grow, pushx, wmin 400");
mainPanel.add(getMessagePanel(), "pushy, growy, w 450!");
JScrollPane contentScrollPane = new JScrollPane(mainPanel);
contentScrollPane.setBorder(BorderFactory.createEmptyBorder());
setContentPane(contentScrollPane);
}
protected JPanel getLeftTopPanel() {
if (optionPanel == null) {
optionPanel = new JPanel();
optionPanel.setBorder(BorderFactory.createTitledBorder(null, "Configuration", TitledBorder.LEFT, TitledBorder.TOP, new Font("null", Font.BOLD, 12), Color.BLUE));
optionPanel.setLayout(new MigLayout("insets 0", "", "top, align 50%"));
JLabel label = new JLabel("Choose");
label.setHorizontalAlignment(JLabel.RIGHT);
optionPanel.add(label, "w 65!");
optionPanel.add(new JSeparator(JSeparator.VERTICAL), "spany 5, growy, w 2!");
optionPanel.add(new JComboBox(new String[] {"option1", "option2", "option3"}), "span, growx, wrap");
optionPanel.add(new JLabel("Type"), "right");
optionPanel.add(new JTextField("3"), "w 65!, split 2");
optionPanel.add(new JLabel("Unit"), "wrap");
optionPanel.add(new JLabel("Slide"), "right");
optionPanel.add(new JSlider(0, 100), "span, growx, wrap");
}
return optionPanel;
}
protected JTabbedPane getRightPanel() {
if (plotTabPane == null) {
plotTabPane = new JTabbedPane();
plotTabPane.add("Tab1", new JPanel());
plotTabPane.add("Tab2", new JPanel());
}
return plotTabPane;
}
protected JPanel getMessagePanel() {
if (messagePanel == null) {
messagePanel = new JPanel();
messagePanel.setBorder(BorderFactory.createTitledBorder(null, "Status Console", TitledBorder.LEFT, TitledBorder.TOP, new Font("null", Font.BOLD, 12), Color.BLUE));
messagePanel.setLayout(new MigLayout("insets 0", "", "top, align 50%"));
messagePanel.add(new JScrollPane(getMessageTextArea()), "push, grow");
}
return messagePanel;
}
protected JTextArea getMessageTextArea() {
if (messageTextArea == null) {
messageTextArea = new JTextArea();
messageTextArea.setEditable(false);
messageTextArea.setFont(new Font(null, Font.PLAIN, 20));
messageTextArea.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
}
return messageTextArea;
}
public void printRawMessage(String rawMessage) {
getMessageTextArea().append(rawMessage);
getMessageTextArea().setCaretPosition(getMessageTextArea().getText().length());
}
}
The layout stuff basically happens in initComponents().
To see the problem:
Start the Application (I used miglayout-4.0-swing.jar).
Wait a bit (don't resize the window), until there are enough messages to create the scrollbar in the status text area.
Now this is what I want. The JTextArea goes all the way to the bottom of the JFrame and is scrolled if neccessary.
Now resize the window. As you can see, everything gets messed up. It will only be fine, if the window is maximized.
Here are two screenshots. The first one is how I want it to be:
The second one is after resizing:
My question: Can somebody tell me, how I keep the layout the way it is before resizing? I want to have the JTextArea go all the way down to the bottom of the window. And if neccessary, the scrollbar should appear. The only way, the status panel can go below the bottom of the window is, if the window is too small (because the configuration panel has a fixed height).
I hope I made myself clear. If not, please ask. ;)
EDIT: You can see the behaviour I want, if you remove the top JScrollPanel (the one that holds all the components). Just change
JScrollPane contentScrollPane = new JScrollPane(mainPanel);
contentScrollPane.setBorder(BorderFactory.createEmptyBorder());
setContentPane(contentScrollPane);
to
setContentPane(mainPanel);
to see what I mean. Unfortunately, this way I loose the scrollbars if the window is very small.
Focusing on your status area and using nested layouts produces the result shown below. Note in particular,
Use invokeLater() to construct the GUI on the EDT.
Use javax.swing.Timer to update the GUI on the EDT.
Use pack() to make the window fit the preferred size and layouts of its subcomponents.
Use the update policy of DefaultCaret to control scrolling.
Avoid needless lazy instantiation in public accessors.
Avoid setXxxSize(); override getXxxSize() judiciously.
Critically examine the decision to extend JFrame.
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.border.TitledBorder;
import javax.swing.text.DefaultCaret;
public class Tab extends JFrame {
private JTextArea messageTextArea;
private JPanel optionPanel, messagePanel;
private JTabbedPane plotTabPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
final Tab tab = new Tab();
tab.setVisible(true);
Timer t = new Timer(200, new ActionListener() {
int count = 0;
#Override
public void actionPerformed(ActionEvent e) {
tab.printRawMessage("testMessage" + count++);
}
});
t.start();
}
});
}
public Tab() {
initComponents();
}
private void initComponents() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel(new GridLayout(1, 0));
Box leftPanel = new Box(BoxLayout.Y_AXIS);
leftPanel.add(getLeftTopPanel());
leftPanel.add(getMessagePanel());
mainPanel.add(leftPanel);
mainPanel.add(getRightPanel());
this.add(mainPanel);
this.pack();
this.setLocationRelativeTo(null);
}
protected JPanel getLeftTopPanel() {
optionPanel = new JPanel();
optionPanel.setBorder(BorderFactory.createTitledBorder(null,
"Configuration", TitledBorder.LEFT, TitledBorder.TOP,
new Font("null", Font.BOLD, 12), Color.BLUE));
JLabel label = new JLabel("Choose");
label.setHorizontalAlignment(JLabel.RIGHT);
optionPanel.add(label);
optionPanel.add(new JSeparator(JSeparator.VERTICAL));
optionPanel.add(new JComboBox(
new String[]{"option1", "option2", "option3"}));
optionPanel.add(new JLabel("Type"));
optionPanel.add(new JTextField("3"));
return optionPanel;
}
protected JTabbedPane getRightPanel() {
plotTabPane = new JTabbedPane();
plotTabPane.add("Tab1", new JPanel());
plotTabPane.add("Tab2", new JPanel());
return plotTabPane;
}
protected JPanel getMessagePanel() {
messagePanel = new JPanel(new GridLayout());
messagePanel.setBorder(BorderFactory.createTitledBorder(null,
"Status Console", TitledBorder.LEFT, TitledBorder.TOP,
new Font("null", Font.BOLD, 12), Color.BLUE));
final JScrollPane sp = new JScrollPane(getMessageTextArea());
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
messagePanel.add(sp);
return messagePanel;
}
protected JTextArea getMessageTextArea() {
messageTextArea = new JTextArea("", 10, 19);
messageTextArea.setEditable(false);
messageTextArea.setFont(new Font(null, Font.PLAIN, 20));
messageTextArea.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
DefaultCaret caret = (DefaultCaret) messageTextArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
return messageTextArea;
}
public void printRawMessage(String rawMessage) {
messageTextArea.append(rawMessage + "\n");
}
}
Add size constraints to your mainPanel in the initComponents method. For instance :
mainPanel.setMinimumSize(new Dimension(400, 400));
mainPanel.setPreferredSize(new Dimension(400, 400));
mainPanel.setMaximumSize(new Dimension(400, 400));