How can I position my labels with this code? It seems that gridbaglayout is not working here, especially the gridbagconstraints. Even if I change the gridx and gridy values, the labels are not moving.
I need to make it in like 3 even columns, 1 column = 1 panel
package nest;
import javax.swing.*;
import java.awt.*;
public class nested extends JFrame{
public static void main(String[] args) {
JFrame f=new JFrame("Bio Data");
JPanel p1=new JPanel(new GridBagLayout());
JPanel p2=new JPanel(new GridBagLayout());
//JPanel p3=new JPanel(new GridBagLayout());
GridBagConstraints c1=new GridBagConstraints();
GridBagConstraints c2=new GridBagConstraints();
JLabel l1=new JLabel("aa");
JLabel l2=new JLabel("bb");
c1.gridx=1;
c1.gridy=1;
p1.add(l1, c1);
c2.gridx=4;
c2.gridy=4;
p2.add(l2, c2);
f.add(p1);
f.add(p2);
f.setVisible(true);
f.setSize(800,500);
f.setResizable(false);
f.setLayout(new FlowLayout());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Changing gridx and gridy does not change the actual position of the labels, but rather the order/format that the labels will be displayed in. If you have something in gridx 4 but nothing in gridx 1,2 or 3 then that object will be the first column.
Also, it woulld be very odd to put a new panel in each column since you can put things in different rows of the gridBagLayout. Here is a short example of a gridBagLayout inside a flowLayout with three different columns of labels:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.JLabel;
import java.awt.Insets;
public class nest extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
nest frame = new nest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public nest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(0, 1, 0, 0));
JPanel panel = new JPanel();
contentPane.add(panel);
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JPanel panel_1 = new JPanel();
panel.add(panel_1);
GridBagLayout gbl_panel_1 = new GridBagLayout();
gbl_panel_1.columnWidths = new int[]{0, 0, 27, 0};
gbl_panel_1.rowHeights = new int[]{0, 16, 0};
gbl_panel_1.columnWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panel_1.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
panel_1.setLayout(gbl_panel_1);
JLabel lblNewLabel_1 = new JLabel("New label");
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_1.gridx = 0;
gbc_lblNewLabel_1.gridy = 0;
panel_1.add(lblNewLabel_1, gbc_lblNewLabel_1);
JLabel lblNewLabel = new JLabel("New label");
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel.gridx = 1;
gbc_lblNewLabel.gridy = 0;
panel_1.add(lblNewLabel, gbc_lblNewLabel);
JLabel lblNewLabel_2 = new JLabel("New label");
GridBagConstraints gbc_lblNewLabel_2 = new GridBagConstraints();
gbc_lblNewLabel_2.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel_2.gridx = 2;
gbc_lblNewLabel_2.gridy = 0;
panel_1.add(lblNewLabel_2, gbc_lblNewLabel_2);
JLabel lblLabel = new JLabel("New label");
GridBagConstraints gbc_lblLabel = new GridBagConstraints();
gbc_lblLabel.gridx = 2;
gbc_lblLabel.gridy = 1;
panel_1.add(lblLabel, gbc_lblLabel);
}
}
I created this with the Google WindowBuilder. Note that you don't necessarily need to set the columnWidths, rowHeights, columnWeights, or rowWeights (and it is better not to sometimes when you have dynamic content). Hopefully this helps.
Related
I am trying to center components using a GridBagLayout in the same manner that a Box centers components when you use Box.createVerticalGlue(). I initially did use a vertical Box:
Box box = Box.createVerticalBox();
box.add(Box.createVerticalGlue());
box.add(add);
box.add(remove);
box.add(edit);
box.add(Box.createVerticalGlue());
JPanel internalPanel = new JPanel(new BorderLayout());
internalPanel.add(keywordsScrollPane, BorderLayout.CENTER);
internalPanel.add(box, BorderLayout.EAST);
But as you can see, it looks sloppy because my buttons are different sizes:
I decided to switch to GridBagLayout so I can utilize GridBagConstraints.fill. This approach fixes my button width issue, but I cannot figure out how to vertically center the buttons. I changed the grid size and placed the buttons in the middle three rows, but the buttons were still appearing at the top of the panel. I tried making use of GridBagConstraints.anchor and GridBagConstraints.weighty as well. The latter almost worked, but there are very large margins between the buttons:
I am looking for the buttons to be grouped together as they were in my Box approach. How can I achieve this with a GridBadLayout?
I am using a class I created called ConstraintsBuilder which works exactly as you would expect. It's for creating GridBagContraints with nice one-liners. Here is all the (relevant) code for your viewing pleasure:
public class KeywordsDialog extends JDialog implements ActionListener, ListSelectionListener {
private JList<String> keywords;
private JScrollPane keywordsScrollPane;
private JButton add;
private JButton remove;
private JButton edit;
private Set<String> keywordsList;
public KeywordsDialog(Window parent, Collection<String> keywordsList) {
super(parent);
this.keywordsList = keywordsList == null ? new HashSet<String>() : new HashSet<String>(keywordsList);
if (keywordsList != null && !keywordsList.isEmpty()) {
this.keywords = new JList<String>(toListModel(keywordsList));
} else {
this.keywords = new JList<String>(new DefaultListModel<String>());
}
this.keywordsScrollPane = new JScrollPane(keywords);
this.add = new JButton("Add");
this.remove = new JButton("Remove");
this.edit = new JButton("Edit");
this.edit.setEnabled(false);
this.add.setEnabled(false);
ConstraintsBuilder builder = LayoutUtils.gridBagConstraintsBuilder();
JPanel internalPanel = new JPanel(new GridBagLayout());
internalPanel.add(this.keywordsScrollPane, builder.gridX(0).gridY(0).gridHeight(3).margins(0, 0, 0, 5)
.fill(GridBagConstraints.BOTH).weightX(1D).weightY(1D).build());
internalPanel.add(this.add,
builder.reset().gridX(1).gridY(0).fill(GridBagConstraints.HORIZONTAL).weightX(1D).weightY(1D).build());
internalPanel.add(this.remove,
builder.reset().gridX(1).gridY(1).fill(GridBagConstraints.HORIZONTAL).weightX(1D).weightY(1D).build());
internalPanel.add(this.edit,
builder.reset().gridX(1).gridY(2).fill(GridBagConstraints.HORIZONTAL).weightX(1D).weightY(1D).build());
this.keywords.setBorder(BorderFactory.createTitledBorder("Keywords"));
internalPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
this.setLayout(new BorderLayout());
this.add(internalPanel, BorderLayout.CENTER);
Dimension screen = GuiHelper.getScreenSize(parent);
this.setSize((int) (screen.getWidth() / 4), (int) (screen.getHeight() / 3));
this.setLocationRelativeTo(parent);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
// ...
}
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the How to Use GridBagLayout section.
The easiest way to create this GUI is to treat the JTextArea separately from the JButton area.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class ExampleGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new ExampleGUI());
}
#Override
public void run() {
JFrame frame = new JFrame("Example GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTextArea(), BorderLayout.CENTER);
frame.add(createButtonPanel(), BorderLayout.EAST);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JScrollPane createTextArea() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JTextArea textArea = new JTextArea(10, 30);
textArea.setText("keyword");
panel.add(textArea, BorderLayout.CENTER);
return new JScrollPane(panel);
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(0, 5, 5, 5);
gbc.gridy = 0;
JButton button = new JButton("Add");
panel.add(button, gbc);
gbc.gridy++;
button = new JButton("Remove");
panel.add(button, gbc);
gbc.gridy++;
button = new JButton("Edit");
panel.add(button, gbc);
return panel;
}
}
I would make the GUI simpler. Put the three buttons into a JPanel that uses a GridLayout, one declared to use 1 column and variable number of rows, one with a desired spacing between buttons, here, 5 pixels: JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 5, 5)); and then put that JPanel into the center of a another JPanel, and GridBagLayout without constraints works well for this:
JPanel sidePanel = new JPanel(new GridBagLayout());
sidePanel.add(buttonPanel);
and put that JPanel into the right side of a border layout using JPanel. For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FooSwing01 extends JPanel {
public FooSwing01() {
JTextArea textArea = new JTextArea(20, 50);
JScrollPane scrollPane = new JScrollPane(textArea);
JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 5, 5));
int maxButtons = 3;
for (int i = 0; i < maxButtons; i++) {
buttonPanel.add(new JButton("Button " + (i + 1)));
}
JPanel sidePanel = new JPanel(new GridBagLayout());
sidePanel.add(buttonPanel);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout(5, 5));
add(scrollPane);
add(sidePanel, BorderLayout.LINE_END);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("GUI");
frame.add(new FooSwing01());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
I have one frame (600X500), A JPanel (50X100) and another JPanel (200X150) and
I am trying to get the following result:
My code is:
public class BtnsPanel extends JPanel{
public BtnsPanel()
{
setSize(50,100);
setBackground(Color.RED);
}
}
public class DialogPanel extends JPanel{
public DialogPanel() {
setSize(150,150);
setBackground(Color.BLUE);
}
}
public class MainFrame extends JFrame{
public MainFrame()
{
setSize(600,500);
setLayout(new BorderLayout());
add(new BtnsPanel(), BorderLayout.CENTER);
add(new DialogPanel(), BorderLayout.CENTER);
}
public static void main(String[] args){
new MainFrame().setVisible(true);
}
}
Code result:
And that is not the expected result.
Your picture is not to scale, but if you are not trying to reach the exact scale of the dimensions you have provided, I would suggest using GridBagLayout instead of BorderLayout:
public class MainFrame extends JFrame {
private JPanel btnsPanel;
private JPanel dialogPanel;
public MainFrame() {
getContentPane().setBackground(Color.BLUE);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setPreferredSize(new Dimension(600,500));
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0, 0, 0};
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.2, 0.1, 0.5, 0.2};
gridBagLayout.rowWeights = new double[]{0.3, 0.3, 0.15, 0.25};
getContentPane().setLayout(gridBagLayout);
btnsPanel = new JPanel();
btnsPanel.setBackground(Color.RED);
GridBagConstraints gbc_btnsPanel = new GridBagConstraints();
gbc_btnsPanel.insets = new Insets(0, 0, 5, 5);
gbc_btnsPanel.fill = GridBagConstraints.BOTH;
gbc_btnsPanel.gridx = 0;
gbc_btnsPanel.gridy = 0;
gbc_btnsPanel.gridheight = 2;
getContentPane().add(btnsPanel, gbc_btnsPanel);
dialogPanel = new JPanel();
dialogPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
dialogPanel.setBackground(Color.BLUE);
GridBagConstraints gbc_dialogPanel = new GridBagConstraints();
gbc_dialogPanel.insets = new Insets(0, 0, 0, 5);
gbc_dialogPanel.fill = GridBagConstraints.BOTH;
gbc_dialogPanel.gridx = 2;
gbc_dialogPanel.gridy = 1;
gbc_dialogPanel.gridheight = 2;
getContentPane().add(dialogPanel, gbc_dialogPanel);
pack();
}
}
Code Result:
Using GridbagLayout as proposed by EvT is a good and valid solution.
However, if you want to avoid the complexity of GridBagConstraints you can achieve similar results by wrapping btnsPanel and dialogPanel, each by a JPanel like so:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class MainFrame extends JFrame {
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cPane = getContentPane();
cPane.setBackground(Color.BLUE);
cPane.setLayout(new BorderLayout());
JPanel leftPane = new JPanel();
leftPane.setLayout(new BoxLayout(leftPane, BoxLayout.Y_AXIS));
leftPane.setOpaque(false);
JPanel btnsPanel = new JPanel();
btnsPanel.setBackground(Color.RED);
btnsPanel.setPreferredSize(new Dimension(50,100));
leftPane.add(btnsPanel);
leftPane.add(Box.createVerticalGlue());
cPane.add(leftPane, BorderLayout.LINE_START);
JPanel centerPane = new JPanel(new GridBagLayout());
centerPane.setPreferredSize(new Dimension(500,500));
centerPane.setOpaque(false);
JPanel dialogPanel = new JPanel();
dialogPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
dialogPanel.setBackground(Color.BLUE);
dialogPanel.setPreferredSize(new Dimension(200,150));
centerPane.add(dialogPanel);
cPane.add(centerPane, BorderLayout.CENTER);
pack();
}
public static void main(String[] args){
new MainFrame().setVisible(true);
}
}
I have a two jpanels: jpanel1 and jpanel2 which must have correct minimal size according to their content. jpanel0 is the container for these two panels, it must be on the left side of a frame. And here is jpanel3 that should take the rest of the available space on the right side.
How to set the size of a jpanel to all available space?
My desired output:
My current output:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class Panels {
public static void main(String[] args) {
JFrame myFrame = new JFrame();
myFrame.setLayout(new BorderLayout());
JTabbedPane jtp = new JTabbedPane();
JPanel jPaneTab1 = new JPanel();
jPaneTab1.setLayout(new FlowLayout(FlowLayout.LEFT));
JPanel jpanel0 = new JPanel();
jpanel0.setLayout(new BoxLayout(jpanel0, BoxLayout.Y_AXIS));
jpanel0.setBorder(BorderFactory.createTitledBorder("jpanel0"));
jpanel0.setBackground(Color.RED);
JPanel jpanel1 = new JPanel();
jpanel1.setLayout(new GridBagLayout());
jpanel1.setBorder(BorderFactory.createTitledBorder("jpanel1"));
GridBagConstraints gc = new GridBagConstraints();
jpanel1.setBackground(Color.BLUE);
JLabel jlabel1 = new JLabel("jlabel1");
gc.gridx = 0;
gc.gridy = 0;
gc.anchor = GridBagConstraints.NORTHWEST;
gc.insets = new Insets(0, 0, 0, 2);
jpanel1.add(jlabel1, gc);
JLabel jlabel2 = new JLabel("jlabel2");
gc.gridx = 0;
gc.gridy = 1;
gc.anchor = GridBagConstraints.NORTHWEST;
gc.insets = new Insets(0, 0, 0, 2);
jpanel1.add(jlabel2, gc);
JPanel jpanel2 = new JPanel();
jpanel2.setLayout(new GridBagLayout());
jpanel2.setBorder(BorderFactory.createTitledBorder("jpanel2"));
GridBagConstraints gc2 = new GridBagConstraints();
jpanel1.setBackground(Color.BLUE);
JLabel jlabel3 = new JLabel("jlabel3");
gc2.gridx = 0;
gc2.gridy = 0;
gc2.anchor = GridBagConstraints.NORTHWEST;
gc2.insets = new Insets(0, 0, 0, 2);
jpanel2.add(jlabel3, gc2);
JLabel jlabel4 = new JLabel("jlabel4");
gc2.gridx = 0;
gc2.gridy = 1;
gc2.anchor = GridBagConstraints.NORTHWEST;
gc2.insets = new Insets(0, 0, 0, 2);
jpanel2.add(jlabel4, gc2);
JPanel jpanel3 = new JPanel();
jpanel3.setBackground(Color.YELLOW);
JLabel jlabel5 = new JLabel("jpanel3");
jpanel3.add(jlabel5);
jpanel0.add(jpanel1);
jpanel0.add(jpanel2);
jPaneTab1.add(jpanel0, BorderLayout.WEST);
jPaneTab1.add(jpanel3, BorderLayout.CENTER);
JPanel jPaneTab2 = new JPanel();
jtp.addTab("tab1", jPaneTab1);
jtp.addTab("tab2", jPaneTab2);
myFrame.add(jtp);
myFrame.setSize(800, 600);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
}
Addition:
When I use BorderLayout for main(tab panel) I'm getting another problem:
Layouts work easier when you break down the layout into logical panels and then nest panels with different layout managers.
For example, use a panel with a BorderLayout as the content for the tabbed pane.
Then you create a "ride side panel" and add it to this panel and a "center panel"
JPanel main = new JPanel( new BorderLayout() );
JPanel rightSide = new JPanel( ... );
JPanel center = new JPanel(...);
main.add(rightSide, BorderLayout.LINE_START);
main.add(center, BorderLayout.CENTER);
Then you set the layouts for the "rightSide" and "center" panels and add components to each of those panels.
You should not be using GridBagLayout, BorderLayout, or BoxLayout managers. These are outdated managers from the 90s.
For instance, when you do this:
gc.insets = new Insets(0, 0, 0, 2);
you are hardcoding pixel-width spaces between components, which
will not work across the wide variety of today's screens.
Insted, one should choose either GroupLayout or MigLayout.
Here is a working example with the MigLayout manager. Notice how easy
is to create the layout with this manager. (Four lines of code.) Also, we use logical pixels (lp) instead of physical pixels.
package com.zetcode;
import java.awt.EventQueue;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import net.miginfocom.swing.MigLayout;
public class PanelsEx extends JFrame {
public PanelsEx() {
initUI();
}
private void initUI() {
JTabbedPane tabpane = new JTabbedPane();
JPanel mainPanel = new JPanel();
JPanel pnl1 = createPanel("Panel 1");
JPanel pnl2 = createPanel("Panel 2");
JPanel pnl3 = createPanel("Panel 3");
mainPanel.setLayout(new MigLayout("ins 10lp"));
mainPanel.add(pnl1, "w 150lp, h 100lp, split 2, flowy, ay top");
mainPanel.add(pnl2, "w 150lp, h 100lp");
mainPanel.add(pnl3, "push, grow");
tabpane.add("First", mainPanel);
add(tabpane);
pack();
setTitle("Panels");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private JPanel createPanel(String text) {
JLabel lbl = new JLabel(text);
JPanel pnl = new JPanel();
pnl.add(lbl);
pnl.setBorder(BorderFactory.createEtchedBorder());
return pnl;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
PanelsEx ex = new PanelsEx();
ex.setVisible(true);
});
}
}
And here is a screenshot:
I am new to java swing, recently I try to create a swing app to format text.
When I click the maximum button, the text panel's length does not resize, and the middle panel takes large space.
And seems setResizable(false) does not work
Code
public class MainFrame extends JFrame {
private static final long serialVersionUID = 7553142908344084288L;
private JTextArea fromTextArea;
private JTextArea toTextArea;
public MainFrame() {
super("jFormatter");
Panel mainPanel = new Panel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
setContentPane(mainPanel);
fromTextArea = createTextArea();
lines.setBorder(BorderFactory.createMatteBorder(0, 1, 0, 1, Color.LIGHT_GRAY));
lines.setEditable(false);
Font f = new Font(Font.SANS_SERIF, Font.PLAIN, 16);
lines.setFont(f);
JScrollPane fromTextAreaScrollPanel = new JScrollPane(fromTextArea);
fromTextAreaScrollPanel.setBorder(BorderFactory.createEmptyBorder(15, 5, 15, 5));
fromTextAreaScrollPanel.getViewport().add(fromTextArea);
fromTextAreaScrollPanel.setRowHeaderView(lines);
mainPanel.add(fromTextAreaScrollPanel);
// control panel
mainPanel.add(createCtrlPanel());
toTextArea = createTextArea();
mainPanel.add(createTextAreaPanel(toTextArea));
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setResizable(false);
setVisible(true);
setLocationRelativeTo(null);
}
private JPanel createCtrlPanel() {
final JComboBox jComboBox = new JComboBox(formatters.keySet().toArray());
jComboBox.setBorder(BorderFactory.createTitledBorder("Text Format"));
JButton fmtButton = new JButton("Format >>");
JPanel ctrPanel = new JPanel(new GridBagLayout());
ctrPanel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
ctrPanel.add(jComboBox, gbc);
ctrPanel.add(Box.createRigidArea(new Dimension(50, 15)), gbc);
//gbc.fill = GridBagConstraints.NONE;
ctrPanel.add(fmtButton, gbc);
return ctrPanel;
}
private JScrollPane createTextAreaPanel(JTextArea textArea) {
JScrollPane fromTextAreaScrollPanel = new JScrollPane(textArea);
//fromTextAreaScrollPanel.setPreferredSize(new Dimension(300, 300));
fromTextAreaScrollPanel.setBorder(BorderFactory.createEmptyBorder(15, 5, 15, 5));
return fromTextAreaScrollPanel;
}
private JTextArea createTextArea() {
JTextArea textArea = new JTextArea(20, 40);
Font f = new Font(Font.SANS_SERIF, Font.PLAIN, 16);
textArea.setFont(f);
//fromTextArea.setLineWrap(true);
//textArea.setBackground(Color.LIGHT_GRAY);
textArea.setMargin(new Insets(0, 10, 0, 10));
return textArea;
}
public static void main(String[] args) {
new MainFrame();
}
}
result:
You should probably use BorderLayout or GridBagLayout for this. BoxLayout just lays out components one after the other at their preferred size. It doesn't make any attempt to resize the components or make them fill their parent.
Try to make a layout like this:
Code:
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
public class Test extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{0, 0, 0, 0};
gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_contentPane.columnWeights = new double[]{0.0, 0.0, 1.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{1.0, 0.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JScrollPane scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.gridheight = 2;
gbc_scrollPane.insets = new Insets(0, 0, 0, 5);
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 0;
gbc_scrollPane.weightx=1;
contentPane.add(scrollPane, gbc_scrollPane);
JTextArea textArea = new JTextArea();
scrollPane.setViewportView(textArea);
JPanel panel = new JPanel();
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.gridheight = 2;
gbc_panel.insets = new Insets(0, 0, 5, 5);
//gbc_panel.fill = GridBagConstraints.BOTH;
gbc_panel.gridx = 1;
gbc_panel.gridy = 0;
contentPane.add(panel, gbc_panel);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0, 0, 0};
gbl_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 0.0, 1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JComboBox comboBox = new JComboBox();
GridBagConstraints gbc_comboBox = new GridBagConstraints();
gbc_comboBox.insets = new Insets(0, 0, 5, 0);
gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox.gridx = 2;
gbc_comboBox.gridy = 0;
gbc_comboBox.weightx=0.0;
panel.add(comboBox, gbc_comboBox);
JButton btnNewButton = new JButton(">>");
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.insets = new Insets(0, 0, 5, 0);
gbc_btnNewButton.gridx = 2;
gbc_btnNewButton.gridy = 1;
panel.add(btnNewButton, gbc_btnNewButton);
JScrollPane scrollPane_1 = new JScrollPane();
GridBagConstraints gbc_scrollPane_1 = new GridBagConstraints();
gbc_scrollPane_1.gridheight = 2;
gbc_scrollPane_1.fill = GridBagConstraints.BOTH;
gbc_scrollPane_1.gridx = 2;
gbc_scrollPane_1.gridy = 0;
gbc_scrollPane_1.weightx=1;
contentPane.add(scrollPane_1, gbc_scrollPane_1);
JTextArea textArea_1 = new JTextArea();
scrollPane_1.setViewportView(textArea_1);
pack();
}
}
I need to add JLabel object to specific component of my panel. I use setLabelFor method but this one adds label nex to component. How to change it to set label on top of component?
TextField sampleField = new TextField();
JLabel sampleLabel = new JLabel("sample text");
panel.add(sampleField);
sampleLabel.setLabelFor(sampleField);
panel.add(sampleLabel);
^ this one puts sampleLabel next to sampleField. How to put sampleLabel on top of sampleField?
Thanks from advance.
#Edit:
I use something like this:
public TabBody()
{
setLayout(new BorderLayout());
nameField = new TextField();
//nameField.setSize(new Dimension(200, 200));
//revalidate();
nameLabel = new JLabel("name test");
amountLabel = new JLabel("amount test");
amountField = new TextField();
unitsBox = new JComboBox(units);
unitsBox.setSelectedIndex(3);
nameLabel.setLabelFor(nameField);
amountLabel.setLabelFor(amountField);
add(nameLabel, BorderLayout.NORTH);
add(amountLabel, BorderLayout.NORTH);
add(nameField);
add(amountField);
add(unitsBox);
}
and outcome is:
And I need something like this:
Your JPanel use FlowLayout by default, that place component one by one in a row. Because of you have that effect.
You need to use a proper LayoutManager for example use BorderLayout :
import java.awt.BorderLayout;
import java.awt.TextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Example {
public static void main(String[] args){
JFrame frame = new JFrame();
JPanel panel = new JPanel(new BorderLayout());
TextField sampleField = new TextField();
JLabel sampleLabel = new JLabel("sample text");
panel.add(sampleField);
sampleLabel.setLabelFor(sampleField);
panel.add(sampleLabel,BorderLayout.NORTH);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
If you need to place components in grid, one by one for example try to use GridBagLayout
JPanel panel = new JPanel(new GridBagLayout());
JTextField sampleField = new JTextField(5);
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(5, 5, 5, 5);
JLabel sampleLabel = new JLabel("sample text");
panel.add(sampleLabel,c);
c.gridy++;
panel.add(sampleField,c);
c.gridy++;
panel.add(new JLabel("sample text 2"),c);
c.gridy++;
panel.add(new JTextField(5),c);
c.gridy++;
panel.add(new JTextField(5),c);
manage positions with gridx and gridy properties of GridBagConstraints
.
You must use Layout for arranging your components. For JPanel by deafult it is FlowLayout which arranges your component next to one-another. You can use GridLayout or GridBagLayout
Here is the sample code:
TextField sampleField = new TextField();
JLabel sampleLabel = new JLabel("sample text");
panel.setLayout(new GridBagLayout());
sampleLabel.setLabelFor(sampleField);
GridBagConstraints = new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0);
panel.add(sampleLabel, gbc);
gbc.gridY=1;
panel.add(sampleField, gbc);