About the layout of a GUI - java

I'm in the middle of working on a program. It's GUI has two main parts, the left of the JFrame and the right of the JFrame. (Currently the right half is blank because I havn't started working on it yet).
The left part doesn't look good. All the buttons and textfields are stretched. I want them to have the height of standard buttons, similiar to the ones on this site. (You know, standard windows buttons).
How do I do that?
(I wouldn't want to simply pack() the whole thing, since the right half of the window is going to have a big square JPanel, and so pack()ing would mean that the window will still be square and the buttons on the left half would still be streched up and down).
Here's a picture:
And here's the code so far:
import javax.swing.*;
import java.awt.*;
import java.awt.Event.*;
public class GUI extends JFrame {
JButton rect,oval,tri,free,addPoint;
JLabel xLabel,yLabel;
JTextField xTextField,yTextField;
JPanel leftPanel,rightPanel,optionsPanel,pointsPanel;
public GUI(){
initUI();
}
private void initUI(){
setLayout(new GridLayout(1,2,5,5));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Graphics Generator");
setSize(500,500);
rect = new JButton("Rectangle");
oval = new JButton("Oval");
tri = new JButton("Triangle");
free = new JButton("Free Shape");
addPoint = new JButton("Add point");
xLabel = new JLabel("X: ");
yLabel = new JLabel("Y: ");
xTextField = new JTextField(2);
yTextField = new JTextField(2);
leftPanel = new JPanel();
rightPanel = new JPanel();
optionsPanel = new JPanel();
pointsPanel = new JPanel();
add(leftPanel);
add(rightPanel);
leftPanel.setLayout(new GridLayout(2,1,5,5));
leftPanel.add(optionsPanel);
optionsPanel.setLayout(new GridLayout(1,4,2,2));
optionsPanel.add(rect);
optionsPanel.add(oval);
optionsPanel.add(tri);
optionsPanel.add(free);
leftPanel.add(pointsPanel);
pointsPanel.setLayout(new GridLayout(1,5,2,2));
pointsPanel.add(xLabel);
pointsPanel.add(xTextField);
pointsPanel.add(yLabel);
pointsPanel.add(yTextField);
pointsPanel.add(addPoint);
setVisible(true);
}
public static void main(String[] args) {
GUI gui = new GUI();
}
}

Try this
import javax.swing.*;
import java.awt.*;
import java.awt.Event.*;
public class GUI extends JFrame {
JButton rect,oval,tri,free,addPoint;
JLabel xLabel,yLabel;
JTextField xTextField,yTextField;
JPanel leftPanel,rightPanel,optionsPanel,pointsPanel;
public GUI(){
initUI();
}
private void initUI(){
setLayout(new GridLayout(1,2,5,5));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Graphics Generator");
setSize(500,500);
rect = new JButton("Rectangle");
oval = new JButton("Oval");
tri = new JButton("Triangle");
free = new JButton("Free Shape");
addPoint = new JButton("Add point");
JPnel p=new JPanel();
p.add(rect);
p.add(oval);
p.add(tri);
p.add(free);
p.add(addPoint);
xLabel = new JLabel("X: ");
yLabel = new JLabel("Y: ");
xTextField = new JTextField(2);
yTextField = new JTextField(2);
leftPanel = new JPanel();
rightPanel = new JPanel();
optionsPanel = new JPanel();
pointsPanel = new JPanel();
add(leftPanel);
add(rightPanel);
leftPanel.setLayout(new GridLayout(2,1,5,5));
leftPanel.add(optionsPanel);
optionsPanel.setLayout(new GridLayout(1,4,2,2));
optionsPanel.add(p);
//optionsPanel.add(oval);
//optionsPanel.add(tri);
//optionsPanel.add(free);
leftPanel.add(pointsPanel);
pointsPanel.setLayout(new GridLayout(1,5,2,2));
pointsPanel.add(xLabel);
pointsPanel.add(xTextField);
pointsPanel.add(yLabel);
pointsPanel.add(yTextField);
pointsPanel.add(addPoint);
setVisible(true);
}
public static void main(String[] args) {
GUI gui = new GUI();
}
}
Like this for JLabels and JTextFields

Please go through following link for more information about Grid layout
How to Use GridLayout
Also try with different layouts in java swing
A Visual Guide to Layout Managers

Please try FlowLayout it is suitable for your requirement.
Just change setLayout(new FlowLayout());
Output :

You have that effect, because you use GridLayout, which resize component to whole cell(vertically/horizontally). You need to use another LayoutManager, or combinations of layouts.
For example I've changed your code with GridBagLayout:
private void initUI(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Graphics Generator");
setLayout(new GridBagLayout());
rect = new JButton("Rectangle");
oval = new JButton("Oval");
tri = new JButton("Triangle");
free = new JButton("Free Shape");
addPoint = new JButton("Add point");
xLabel = new JLabel("X: ");
yLabel = new JLabel("Y: ");
xTextField = new JTextField(2);
yTextField = new JTextField(2);
leftPanel = new JPanel();
leftPanel.setBorder(BorderFactory.createLineBorder(Color.RED));
rightPanel = new JPanel();
rightPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
optionsPanel = new JPanel(new GridBagLayout());
pointsPanel = new JPanel(new GridBagLayout());
GridBagConstraints cMain = new GridBagConstraints();
cMain.insets = new Insets(5, 5, 5, 5);
cMain.gridx = 0;
cMain.gridy = 0;
cMain.anchor = GridBagConstraints.NORTHWEST;
add(leftPanel,cMain);
cMain.fill = GridBagConstraints.BOTH;
cMain.gridx++;
cMain.weighty = 1;
cMain.weightx = 1;
add(rightPanel,cMain);
leftPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5, 5, 5, 5);
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
leftPanel.add(optionsPanel,c);
c.gridy++;
leftPanel.add(pointsPanel,c);
c.gridy = 0;
optionsPanel.add(rect,c);
c.gridx++;
optionsPanel.add(oval,c);
c.gridx++;
optionsPanel.add(tri,c);
c.gridx++;
optionsPanel.add(free,c);
c.gridx = 0;
c.gridy = 1;
pointsPanel.add(xLabel,c);
c.gridx++;
pointsPanel.add(xTextField,c);
c.gridx++;
pointsPanel.add(yLabel,c);
c.gridx++;
pointsPanel.add(yTextField,c);
c.gridx++;
pointsPanel.add(addPoint,c);
setSize(500,500);
setVisible(true);
}

Related

Anchor constraint in GridBagLayout not working

import java.awt.*;
import javax.swing.*;
public class GBLClumpingExample extends JFrame{
GBLClumpingExample(){
GridBagLayout g = new GridBagLayout();
GridBagConstraints gv = new GridBagConstraints();
GridBagLayout b = new GridBagLayout();
GridBagConstraints gc = new GridBagConstraints();
setVisible(true);
setSize(720,720);
setLayout(g);
JPanel p = new JPanel();
p.setLayout(b);
gv.fill = GridBagConstraints.BOTH;
add(p,gv);
Label l1 = new Label("Label 1");
Label l2 = new Label("Label 2");
Label l3 = new Label("Label 3");
Label l4 = new Label("Label 4");
Label l5 = new Label("Label 5");
gc.weightx =1.0;
gc.weighty = 1.0;
gc.gridx= 1;
gc.gridy= 1;
gc.anchor = GridBagConstraints.PAGE_START;
gc.gridx= -1;
gc.gridy= 0;
p.add(l1,gc);
gc.anchor = GridBagConstraints.SOUTH;
p.add(l2,gc);
gc.anchor = GridBagConstraints.EAST;
p.add(l3,gc);
gc.anchor = GridBagConstraints.WEST;
p.add(l4,gc);
gc.anchor = GridBagConstraints.CENTER;
p.add(l5,gc);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args){
GBLClumpingExample e = new GBLClumpingExample();
}
}
I was trying to use GridBagLayout but maybe it is not working correctly.
This is my code I don't know what is wrong but anchor constraints of GridBagConstraints are not working, they are all just clump together.
You are adding you components to a panel p which you are then adding to the frame (to its content pane) using add(p,gv);. The constraints in gv have been initialized with gv.fill = GridBagConstraints.BOTH;, but its weightx and weighty are left at their initial zero. As a result, this panel will stay at its preferred size and not receive additional space, so it has no additional space to distribute to its own content.
Since all labels have the same size, their anchors have no effect when there is no additional space.
When you change the line
gv.fill = GridBagConstraints.BOTH;
to
gv.fill = GridBagConstraints.BOTH;
gv.weightx = 1;
gv.weighty = 1;
you will see the effect of the anchors. Alternatively, you can get rid of the additional panel. There are other redundant operations too. You can simplify your code to:
import java.awt.*;
import javax.swing.*;
public class GBAnchorExample extends JFrame{
GBAnchorExample() {
Container c = super.getContentPane();
c.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.weightx = gc.weighty = 1.0;
JLabel l1 = new JLabel("Label 1");
JLabel l2 = new JLabel("Label 2");
JLabel l3 = new JLabel("Label 3");
JLabel l4 = new JLabel("Label 4");
JLabel l5 = new JLabel("Label 5");
gc.anchor = GridBagConstraints.PAGE_START;
c.add(l1,gc);
gc.anchor = GridBagConstraints.SOUTH;
c.add(l2,gc);
gc.anchor = GridBagConstraints.EAST;
c.add(l3,gc);
gc.anchor = GridBagConstraints.WEST;
c.add(l4,gc);
gc.anchor = GridBagConstraints.CENTER;
c.add(l5,gc);
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
GBAnchorExample e = new GBAnchorExample();
e.setSize(720,720);
e.setVisible(true);
}
}
To visualize the actual effect of the anchor you may change the main method to
public static void main(String[] args){
GBAnchorExample e = new GBAnchorExample();
Component grid = new JComponent() {
#Override
protected void paintComponent(Graphics g) {
g.setColor(Color.GREEN);
int w = getWidth(), h = getHeight();
for(int i = 1; i < 5; i++) {
int x = (int)(w/5.0*i);
g.drawLine(x, 0, x, h);
}
}
};
e.setGlassPane(grid);
grid.setVisible(true);
e.setSize(720,720);
e.setVisible(true);
}
This will paint a green grid to show the logical cells containing the labels, so it becomes apparent how the anchors affect the labels’ positions within their cells.
If I understand the intent of this layout correctly (I'm not sure I do) then this might be done using a BorderLayout.
Here it is with more width and height:
The titled borders are only there to provide a quick visual reference to the constraint used to place the component. The (spacer) is only added to the 3 labels in the center row to allow the full TitledBorder to appear!
Here is the code:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class BLNotClumpingExample {
private JComponent ui = null;
BLNotClumpingExample() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(10,10));
ui.setBorder(new EmptyBorder(4,4,4,4));
ui.add(getLabel("Label 1", "PAGE_START"), BorderLayout.PAGE_START);
ui.add(getLabel("Label 2", "PAGE_END"), BorderLayout.PAGE_END);
ui.add(getLabel("Label 3 (spacer)", "LINE_END"), BorderLayout.LINE_END);
ui.add(getLabel("Label 4 (spacer)", "LINE_START"), BorderLayout.LINE_START);
ui.add(getLabel("Label 5 (spacer)", "CENTER"), BorderLayout.CENTER);
}
private JLabel getLabel(String text, String constraint) {
JLabel l = new JLabel(text, SwingConstants.CENTER);
l.setBorder(new TitledBorder(constraint));
return l;
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
BLNotClumpingExample o = new BLNotClumpingExample();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}

GridBagLayout isn't formatting correctly

I'm trying to get the config panel to take up the top of the screen, and then have the input and output panels side-by-side. I'm also trying to get the text areas to be 70 characters wide each and 30 rows tall. However, right now, the config panel isn't showing up at all, and the text areas are only 35 characters wide and 2 rows tall. I've followed all the examples and tutorials I've found. What am I doing wrong?
public class BorderWrapper {
public static void main(String[] args) {
//Create frame
JFrame frame = new JFrame("Border Wrapper");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create main panel
MainPanel panel = new MainPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
//Display frame
Dimension minSize = new Dimension(650, 375);
frame.setPreferredSize(minSize);
frame.setMinimumSize(minSize);
frame.pack();
frame.setVisible(true);
}
}
public class MainPanel extends JPanel {
private static final Font INPUT_FONT = new Font("Monospaced", Font.PLAIN, 12);
private JTextArea inputArea, outputArea;
private JTextField titleField, topBorderField, sideBorderField;
public MainPanel() {
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//Set up config panel
JPanel configPanel = new JPanel();
configPanel.setLayout(new BoxLayout(configPanel, BoxLayout.X_AXIS));
configPanel.setMaximumSize(new Dimension(400, 200));
titleField = new JTextField(25);
titleField.setFont(INPUT_FONT);
topBorderField = new JTextField(1);
topBorderField.setFont(INPUT_FONT);
sideBorderField = new JTextField(4);
sideBorderField.setFont(INPUT_FONT);
configPanel.add(new JLabel("Title:"));
configPanel.add(titleField);
configPanel.add(new JLabel("Top border:"));
configPanel.add(topBorderField);
configPanel.add(new JLabel("Side border:"));
configPanel.add(sideBorderField);
c.gridwidth = 2;
c.gridx = 0;
c.gridy = 0;
add(configPanel, c);
//Set up Input panel
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.Y_AXIS));
inputArea = new JTextArea("Type or paste your stuff here . . .");
inputArea.setFont(INPUT_FONT);
inputArea.setLineWrap(true);
inputArea.setWrapStyleWord(true);
inputArea.setColumns(75);
JScrollPane inputPane = new JScrollPane(inputArea);
inputPane.setMinimumSize(new Dimension(250, 400));
JLabel inputLabel = new JLabel("Text Box");
inputLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
inputPanel.add(inputLabel);
inputPanel.add(inputPane);
inputPanel.setMinimumSize(new Dimension(250, 400));
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 1;
add(inputPanel, c);
//Set up Output panel
JPanel outputPanel = new JPanel();
outputPanel.setLayout(new BoxLayout(outputPanel, BoxLayout.Y_AXIS));
outputArea = new JTextArea();
outputArea.setFont(INPUT_FONT);
outputArea.setLineWrap(true);
outputArea.setWrapStyleWord(true);
outputArea.setColumns(75);
JScrollPane outputPane = new JScrollPane(outputArea);
outputPane.setMinimumSize(new Dimension(250, 400));
JLabel outputLabel = new JLabel("Wrapped Output");
outputLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
outputPanel.add(outputLabel);
outputPanel.add(outputPane);
outputPanel.setMinimumSize(new Dimension(250, 400));
c.gridwidth = 1;
c.gridx = 1;
c.gridy = 1;
add(outputPanel, c);
}
}
Originally, I was going to try to use a BorderLayout, since it seemed that made the most sense for the layout I was trying to make, but that did an even worse job when I set them to BorderLayout.WEST and BorderLayout.EAST.
Have modified your program to use BorderLayout in the MainPanel and few other minor changes to get the desired look and feel.Check if this helps.
public class BorderWrapper {
public static void main(String[] args) {
// Create frame
JFrame frame = new JFrame("Border Wrapper");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create main panel
MainPanel panel = new MainPanel();
frame.getContentPane().add(panel);
// Display frame
Dimension minSize = new Dimension(650, 375);
frame.setPreferredSize(minSize);
frame.setMinimumSize(minSize);
frame.pack();
frame.setVisible(true);
}
}
class MainPanel extends JPanel {
private static final Font INPUT_FONT = new Font("Monospaced", Font.PLAIN, 12);
private JTextArea inputArea, outputArea;
private JTextField titleField, topBorderField, sideBorderField;
public MainPanel() {
setLayout(new BorderLayout());
// Set up config panel
JPanel configPanel = new JPanel();
configPanel.setLayout(new BoxLayout(configPanel, BoxLayout.X_AXIS));
configPanel.setMaximumSize(new Dimension(400, 200));
titleField = new JTextField(25);
titleField.setFont(INPUT_FONT);
topBorderField = new JTextField(1);
topBorderField.setFont(INPUT_FONT);
sideBorderField = new JTextField(4);
sideBorderField.setFont(INPUT_FONT);
configPanel.add(new JLabel("Title:"));
configPanel.add(titleField);
configPanel.add(new JLabel("Top border:"));
configPanel.add(topBorderField);
configPanel.add(new JLabel("Side border:"));
configPanel.add(sideBorderField);
add(configPanel, BorderLayout.NORTH);
// Set up Input panel
JPanel lowerPanel = new JPanel(new GridLayout(1, 1));
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.Y_AXIS));
inputArea = new JTextArea("Type or paste your stuff here . . .");
inputArea.setFont(INPUT_FONT);
inputArea.setLineWrap(true);
inputArea.setWrapStyleWord(true);
inputArea.setColumns(75);
JScrollPane inputPane = new JScrollPane(inputArea);
JLabel inputLabel = new JLabel("Text Box");
inputLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
inputPanel.add(inputLabel);
inputPanel.add(inputPane);
lowerPanel.add(inputPanel);
// Set up Output panel
JPanel outputPanel = new JPanel();
outputPanel.setLayout(new BoxLayout(outputPanel, BoxLayout.Y_AXIS));
outputArea = new JTextArea();
outputArea.setFont(INPUT_FONT);
outputArea.setLineWrap(true);
outputArea.setWrapStyleWord(true);
outputArea.setColumns(75);
JScrollPane outputPane = new JScrollPane(outputArea);
JLabel outputLabel = new JLabel("Wrapped Output");
outputLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
outputPanel.add(outputLabel);
outputPanel.add(outputPane);
lowerPanel.add(outputPanel);
add(lowerPanel, BorderLayout.CENTER);
}
}
I felt it convenient to use BorderLayout for this format.Anyways, you can still make few changes to the code you posted using GridBagConstraints to get the desired look.Make the below changes one by one and you will observe the differences.
1.You were aligning the MainPanel to the NORTH by using BorderLayout.But in your case the entire set of components is placed in MainPanel,so better place it in center.So instead of NORTH use below :(after this change,you will see the complete input and output panels)
MainPanel panel = new MainPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
2.You have set the dimension of the Parent frame to Dimension(height=375)
minSize = new Dimension(650, 375);
You components(configPanel=200,outputPanel=400) combined height is more than 375.Increase the height of the Parent, to about 600.
3.Instead of BoxLayout try using GridLayout for configPanel.
configPanel.setLayout(new GridLayout(1,6,5,0));
Making the above 3 changes to your existing code will get the expected output.Hope this clarifies.

Unable to set the size of my buttons in GridLayout

I am trying to build a sample application using GridLayout in Java. But I am unable to re-size my buttons. Please help me in doing it.
There are four grid layouts in the code.
I have used the setSize(width, height) function and also the setPreferredSize function. But I am not able to set the size of the buttons.
Here is the code
import java.awt.*;
import javax.swing.*;
public class Details2 {
static JButton btn1,btn2;
public static void main(String[] a) {
JFrame myFrame = new JFrame("Medical History Form");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(700,700);
Container myPane = myFrame.getContentPane();
myPane.setLayout(new GridLayout(2,1));
myPane.add(getFieldPanel());
myPane.add(getButtonPanel());
myPane.setPreferredSize(new Dimension(100,100));
myFrame.setVisible(true);
}
private static JPanel getFieldPanel() {
JPanel p = new JPanel(new GridLayout(4,2));
p.setBorder(BorderFactory.createTitledBorder("Details"));
p.add(new JLabel("Please check in the here"));
p.add(new JCheckBox("Nothing till now",false));
p.add(getPanel());
return p;
}
private static JPanel getButtonPanel() {
GridLayout g =new GridLayout(1,2);
JPanel p = new JPanel(g);
btn1 = new JButton("Submit");
btn2 = new JButton("Reset");
p.add(btn1).setPreferredSize(new Dimension(100,100));
p.add(btn2).setPreferredSize(new Dimension(100,100));
p.setPreferredSize(new Dimension(100,100));
return p;
}
private static JPanel getPanel() {
JPanel p = new JPanel(new GridLayout(5,2));
p.add(new JCheckBox("A",false));
p.add(new JCheckBox("B",false));
p.add(new JCheckBox("C",false));
p.add(new JCheckBox("D",false));
p.add(new JCheckBox("E",false));
p.add(new JCheckBox("F",false));
p.add(new JCheckBox("G",false));
p.add(new JCheckBox("E",false));
p.add(new JCheckBox("H",false));
p.add(new JCheckBox("I",false));
return p;
}
}
I believe setting GridLayout(2,2) will override size changes made to the panels. To be more precise, use GridBagConStraints; you can refer following code to understand it.
private JTextField field1 = new JTextField();
private JButton addBtn = new JButton("Save: ");
public void addComponents(Container pane) {
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// Components
c.gridwidth = 1;
c.weightx = .01;
c.weighty = .2;
c.gridx = 0;
c.gridy = 1;
pane.add(field1, c);
c.gridwidth = 1;
c.weightx = .01;
c.weighty = .2;
c.gridx = 0;
c.gridy = 1;
pane.add(addBtn, c);
}
public MainView() {
//Create and set up the window.
JFrame frame = new JFrame("NAME");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponents(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
frame.setSize(400, 125);
frame.setLocation(400, 300);
}
if you want to control the size of your components then don't use a layout. do something like this:
private static JPanel getButtonPanel() {
JPanel p = new JPanel();
p.setLayout(null);
btn1 = new JButton("Submit");
btn2 = new JButton("Reset");
btn1.setBounds(x, y, width, height);
btn2.setBounds(x, y, width, height);
p.add(btn1);
p.add(btn2);
return p;

JScrollPane not properly stretching horizontal distance in GridBagLayout

I've seen other posts on this subject, but the solutions they found do not apply to me. I am setting a weighted value and using the c.fill = GridBagConstraints.BOTH constraints as well.
I'm including the whole GUI code I have, just in case my mistake is coming form something other than the GridBagLayout.
I want the scrollable text block on the right to expand the remaining space within the GUI and I have set all the variables that should be attributed to that and yet it still isn't working. What am I doing wrong?
My result:
import java.awt.*;
import javax.swing.*;
public class TestCode extends JFrame {
JTextArea textArea = new JTextArea ();
JComboBox <String> typeComboBox;
JTextField searchField;
JTextField fileField;
public TestCode(){
setTitle ("GUI Test");
setSize (600, 300);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setVisible (true);
JScrollPane scrollPane = new JScrollPane(textArea);
JButton readButton = new JButton("Read File");
JButton displayButton = new JButton("Display");
JButton searchButton = new JButton("Search");
searchField = new JTextField(10);
fileField = new JTextField(15);
typeComboBox = new JComboBox <String> ();
typeComboBox.addItem("Index");
typeComboBox.addItem("Type");
typeComboBox.addItem("Name");
JPanel container = new JPanel();
container.setLayout(new GridBagLayout());
container.setPreferredSize(new Dimension(250, 100));
JPanel filePanel = new JPanel();
filePanel.setLayout(new BoxLayout(filePanel, BoxLayout.Y_AXIS));
filePanel.add(new JLabel("Source file", SwingConstants.LEFT));
JPanel filePanelTop = new JPanel();
filePanelTop.setLayout(new FlowLayout(FlowLayout.LEFT));
filePanelTop.add(fileField);
JPanel filePanelBottom = new JPanel();
filePanelBottom.setLayout(new FlowLayout(FlowLayout.RIGHT));
filePanelBottom.add(readButton);
filePanelBottom.add(displayButton);
filePanel.add(filePanelTop);
filePanel.add(filePanelBottom);
filePanel.setMaximumSize(filePanel.getPreferredSize());
filePanel.setBorder(BorderFactory.createTitledBorder("Import File"));
JPanel searchPanel = new JPanel();
searchPanel.setLayout(new BoxLayout(searchPanel, BoxLayout.Y_AXIS));
searchPanel.add(new JLabel("Search target", SwingConstants.LEFT));
JPanel searchPanelTop = new JPanel();
searchPanelTop.setLayout(new FlowLayout(FlowLayout.LEFT));
searchPanelTop.add(searchField);
searchPanelTop.add(typeComboBox);
searchPanel.add(searchPanelTop);
searchPanel.add(searchButton);
searchPanel.setMaximumSize(searchPanel.getPreferredSize());
searchPanel.setBorder(BorderFactory.createTitledBorder("Search Objects"));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
container.add(filePanel, c);
c.gridx = 0;
c.gridy = 1;
container.add(searchPanel, c);
c.gridx = 1;
c.gridy = 0;
c.weightx = 1.0;
c.weighty = 1.0;
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridheight = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.NORTHWEST;
container.add(scrollPane, c);
add(container, BorderLayout.WEST);
validate();
} // end method toString
public static void main(String[] args){
TestCode run = new TestCode();
}
} // end class Treasure
//add(container, BorderLayout.WEST);
add(container);
The West contrains the components to their preferred width. The default is the CENTER which allows components to expand to fill the space available.
Also, the main structure of you code is wrong. You should be adding all the component to the frame first and then invoke:
frame.pack();
frame.setVisible(true);
Then there is no need for the validate().

Aligning panels with GridBagLayout

I'm not exactly new to java (I've been using it for a year now) but this is my first go at swing. I'm trying to make a very simple chat client to learn both socket and swing at once. My question is "What must I do to align my panels correctly?". I've tried a lot of things (Though I don't have it in my code). Usually I work something like this out on my own, but I'm to the point I need to ask for help. Do I need to change the wieghtx, weighty? What I want the client to look like is something like this.
This is what it currently looks like.
Here is my code.
package com.client.core;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Window extends JFrame{
private int screenWidth = 800;
private int screenHeight = 600;
public Window(){
//Initial Setup
super("NAMEHERE - Chat Client Alpha v0.0.1");
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(screenWidth,screenHeight);
GridBagConstraints c = new GridBagConstraints();
//Main Panel
JPanel window = new JPanel();
window.setLayout(new GridBagLayout());
window.setBackground(Color.black);
//Panels
JPanel display = new JPanel();
JPanel chat = new JPanel();
chat.setLayout(new GridBagLayout());
JPanel users = new JPanel();
display.setBackground(Color.blue);
c.gridx = 0;
c.gridy = 0;
c.insets= new Insets(5,5,5,5);
window.add(display, c);
chat.setBackground(Color.red);
c.gridx = 0;
c.gridy = 3;
c.gridheight = 2;
c.gridwidth = 1;
c.insets= new Insets(5,5,5,5);
window.add(chat, c);
users.setBackground(Color.green);
c.gridx = 2;
c.gridy = 0;
c.insets= new Insets(5,5,5,5);
window.add(users, c);
//Buttons
//Text fields
JTextArea text = new JTextArea("DEREADFADSFEWFASDFSADFASDF");
c.gridx = 0;
c.gridy = 0;
chat.add(text);
JTextField input = new JTextField("type here to chat", 50);
c.gridx = 0;
c.gridy = 1;
c.insets= new Insets(5,5,5,5);
chat.add(input);
add(window);
}
static class ActLis implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
}
If you wanted something like this as an output :
You can take help from this code example, though you can remove the last ButtonPanel if you don't need that :
package to.uk.gagandeepbali.swing.messenger.gui;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JTextField;
public class ChatPanel extends JPanel
{
private JButton backButton;
private JButton exitButton;
private JButton sendButton;
private JTextPane chatPane;
private JTextPane namePane;
private JTextField chatField;
private GridBagConstraints gbc;
private final int GAP = 10;
private final int SMALLGAP = 1;
public ChatPanel()
{
gbc = new GridBagConstraints();
}
protected void createGUI()
{
setOpaque(true);
setBackground(Color.WHITE);
setLayout(new BorderLayout(5, 5));
JPanel centerPanel = new JPanel();
centerPanel.setOpaque(true);
centerPanel.setBackground(Color.WHITE);
centerPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, 0, GAP));
centerPanel.setLayout(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 5;
gbc.weightx = 0.8;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
chatPane = new JTextPane();
JScrollPane scrollerChat = new JScrollPane();
scrollerChat.setBorder(BorderFactory.createTitledBorder("Chat"));
scrollerChat.setViewportView(chatPane);
centerPanel.add(scrollerChat, gbc);
gbc.gridx = 5;
gbc.gridwidth = 2;
gbc.weightx = 0.2;
namePane = new JTextPane();
JScrollPane scrollerName = new JScrollPane(namePane);
scrollerName.setBorder(BorderFactory.createTitledBorder("Names"));
centerPanel.add(scrollerName, gbc);
gbc.gridx = 0;
gbc.gridy = 5;
gbc.gridwidth = 5;
gbc.weightx = 0.8;
gbc.weighty = 0.1;
gbc.fill = GridBagConstraints.HORIZONTAL;
chatField = new JTextField();
chatField.setOpaque(true);
chatField.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("")
, BorderFactory.createEmptyBorder(SMALLGAP, SMALLGAP, SMALLGAP, SMALLGAP)));
centerPanel.add(chatField, gbc);
gbc.gridx = 5;
gbc.gridwidth = 2;
gbc.weightx = 0.2;
sendButton = new JButton("Send");
sendButton.setBorder(BorderFactory.createTitledBorder(""));
centerPanel.add(sendButton, gbc);
JPanel bottomPanel = new JPanel();
bottomPanel.setOpaque(true);
bottomPanel.setBackground(Color.WHITE);
bottomPanel.setBorder(
BorderFactory.createTitledBorder(""));
bottomPanel.setLayout(new BorderLayout());
JPanel buttonPanel = new JPanel();
buttonPanel.setOpaque(true);
buttonPanel.setBackground(Color.WHITE);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, 0, GAP));
backButton = new JButton("Back");
exitButton = new JButton("Exit");
buttonPanel.add(backButton);
buttonPanel.add(exitButton);
bottomPanel.add(buttonPanel, BorderLayout.CENTER);
add(centerPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
public JTextPane getChatPane()
{
return chatPane;
}
public JTextPane getNamePane()
{
return namePane;
}
public JTextField getChatField()
{
return chatField;
}
public JButton getExitButton()
{
return exitButton;
}
public JButton getBackButton()
{
return backButton;
}
public JButton getSendButton()
{
return sendButton;
}
}
What you could do, and probably gives the desired result
JPanel somethingHere = ...;
JPanel chat = ...;
JPanel userList = ...;
JPanel leftPanel = new JPanel( new BorderLayout() );
leftPanel.add( somethingHere, BorderLayout.CENTER );
leftPanel.add( chat, BorderLayout.SOUTH );
JPanel total = new JPanel( new BorderLayout() );
total.add( leftPanel, BorderLayout.CENTER );
total.add( userList, BorderLayout.EAST );
Way simpler then messing with GridBagLayout
Here is what I came out with thus far. The red box is where I plan to add a simple 2D avatar interface with LWJGL.
Here is the code for it
package com.client.core;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class Window extends JFrame{
private int screenWidth = 800;
private int screenHeight = 600;
public Window(){
//Initial Setup
super("NAMEHERE - Chat Client Alpha v0.0.1");
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(screenWidth,screenHeight);
//Main Panels
JPanel window = new JPanel(new BorderLayout());
JPanel center = new JPanel(new BorderLayout());
JPanel right = new JPanel(new BorderLayout());
//Panels
JPanel display = new JPanel( new BorderLayout());
display.setBackground(Color.red);
JPanel chat = new JPanel();
chat.setLayout(new BoxLayout(chat, BoxLayout.Y_AXIS));
chat.setBackground(Color.blue);
JPanel users = new JPanel(new BorderLayout());
users.setBackground(Color.green);
//TextFields
JTextArea chatBox = new JTextArea("Welcome to the chat!", 7,50);
chatBox.setEditable(false);
JTextField chatWrite = new JTextField();
JScrollPane userList = new JScrollPane();
JTextField userSearch = new JTextField(10);
userList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
users.add(userList);
users.add(userSearch, BorderLayout.NORTH);
chat.add(chatBox);
chat.add(chatWrite);
chat.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
//Menu bar
JMenuBar menu = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem exit = new JMenuItem("Exit");
JMenuItem ipconnect = new JMenuItem("Connect to IP");
file.add(ipconnect);
file.add(exit);
menu.add(file);
//Main window adding
right.add(users);
center.add(display, BorderLayout.CENTER);
center.add(chat, BorderLayout.SOUTH);
window.add(center, BorderLayout.CENTER);
window.add(right, BorderLayout.EAST);
window.add(menu, BorderLayout.NORTH);
add(window);
//Listeners
chatWrite.addKeyListener(new KeyLis());
ipconnect.addActionListener(new ActLis());
exit.addActionListener(new ActLis());
}
static class KeyLis implements KeyListener{
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
System.out.println("Message recieved.");
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
static class ActLis implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand() == "Exit"){
System.exit(0);
} else if(e.getActionCommand() == "Connect to IP"){
System.out.println("Connecting....");
JFrame frameip = new JFrame();
JPanel panelip = new JPanel();
JButton buttonip = new JButton("Hello");
frameip.add(panelip);
panelip.add(buttonip);
JDialog ippop = new JDialog(frameip, "Enter IP", false);
}
}
}
}
I had to build a similar layout using a GridBagLayout. The code below shows how I achieved it.
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GridBagLayoutTest {
public GridBagLayoutTest() {
JFrame jframe = new JFrame();
jframe.setLayout(new GridBagLayout());
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(800, 600);
jframe.setVisible(true);
// Left
JPanel leftPanel = new JPanel(new GridBagLayout());
leftPanel.setBackground(Color.YELLOW);
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.weightx = .7f;
gridBagConstraints.weighty = 1f;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
jframe.add(leftPanel, gridBagConstraints);
JPanel leftTopPanel = new JPanel(new FlowLayout());
leftTopPanel.setBackground(Color.RED);
GridBagConstraints gridBagConstraints0 = new GridBagConstraints();
gridBagConstraints0.fill = GridBagConstraints.BOTH;
gridBagConstraints0.weightx = 1f;
gridBagConstraints0.weighty = .7f;
gridBagConstraints0.gridx = 0;
gridBagConstraints0.gridy = 0;
leftPanel.add(leftTopPanel, gridBagConstraints0);
JPanel leftMiddlePanel = new JPanel(new FlowLayout());
leftMiddlePanel.setBackground(Color.BLACK);
gridBagConstraints0 = new GridBagConstraints();
gridBagConstraints0.fill = GridBagConstraints.BOTH;
gridBagConstraints0.weightx = 1f;
gridBagConstraints0.weighty = .2f;
gridBagConstraints0.gridx = 0;
gridBagConstraints0.gridy = 1;
leftPanel.add(leftMiddlePanel, gridBagConstraints0);
JPanel leftBottomBottomPanel = new JPanel(new FlowLayout());
leftBottomBottomPanel.setBackground(Color.PINK);
gridBagConstraints0 = new GridBagConstraints();
gridBagConstraints0.fill = GridBagConstraints.BOTH;
gridBagConstraints0.weightx = 1f;
gridBagConstraints0.weighty = .1f;
gridBagConstraints0.gridx = 0;
gridBagConstraints0.gridy = 2;
leftPanel.add(leftBottomBottomPanel, gridBagConstraints0);
// Right
JPanel rightPanel = new JPanel();
rightPanel.setBackground(Color.GREEN);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.weightx = .3f;
gridBagConstraints.weighty = 1f;
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
jframe.add(rightPanel, gridBagConstraints);
}
public static void main (String args[]) {
new GridBagLayoutTest();
}

Categories

Resources