JTextArea height is only 1 line when using GridBayLayout - java

I am doing a program that finds words in a text file. I am using GridBagLayout for the position of the elements. When I run the program the text area shows with just one line. Even though it is set JTextArea results = new JTextArea(30, 30)
This is what it shows at the moment:
I am trying to do something like this:
Java code:
public class WordFinder extends JFrame {
private WordList words = new WordList();
private static final int WINDOW_WIDTH = 380;
private static final int WINDOW_HEIGHT = 380;
private static final int TEXT_WIDTH = 30;
private JLabel findLabel = new JLabel("Find:");
private JLabel wordsContaining = new JLabel("words containing");
private JTextField findWord = new JTextField(TEXT_WIDTH);
private JButton clear = new JButton("Clear");
private JTextArea results = new JTextArea(30, 30);
private JScrollPane scroll = new JScrollPane(results);
private JFileChooser chooseFile = new JFileChooser();
private JPanel pane = new JPanel(new GridBagLayout());
public WordFinder() {
super("Word Finder");
// Initialize the menu bar
//initMenu();
results.setEditable(false);
pane.setLayout(new GridBagLayout());
pane.setBorder(new EmptyBorder(15, 20, 0, 10));
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.PAGE_START;
results.setLineWrap(true);
results.setWrapStyleWord(true);
scroll.setViewportView(results);
// Add label "Find"
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
pane.add(findLabel, c);
// Add text field
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.gridx = 1;
c.gridy = 0;
pane.add(findWord, c);
// Add clear button
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = .1;
c.gridx = 2;
c.gridy = 0;
pane.add(clear, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 2;
c.insets = new Insets(5, 5, 0, 0);
pane.add(wordsContaining, c);
// Add text area
c.fill = GridBagConstraints.HORIZONTAL;
c.weighty = 1;
c.gridx = 1;
c.gridy = 3;
c.insets = new Insets(0, 3, 0, 5);
pane.add(scroll, c);
add(pane);
setVisible(true);
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run () {
new WordFinder().show();
}
});
}
}
Any ideas in what am I missing? or perhaps I am doing something wrong?

Change c.fill = GridBagConstraints.HORIZONTAL; to c.fill = GridBagConstraints.BOTH;
Use pack instead of setSize
For example
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class WordFinder extends JFrame {
private static final int WINDOW_WIDTH = 380;
private static final int WINDOW_HEIGHT = 380;
private static final int TEXT_WIDTH = 30;
private JLabel findLabel = new JLabel("Find:");
private JLabel wordsContaining = new JLabel("words containing");
private JTextField findWord = new JTextField(TEXT_WIDTH);
private JButton clear = new JButton("Clear");
private JTextArea results = new JTextArea(30, 30);
private JScrollPane scroll = new JScrollPane(results);
private JFileChooser chooseFile = new JFileChooser();
private JPanel pane = new JPanel(new GridBagLayout());
public WordFinder() {
super("Word Finder");
// Initialize the menu bar
//initMenu();
results.setEditable(false);
pane.setLayout(new GridBagLayout());
pane.setBorder(new EmptyBorder(15, 20, 0, 10));
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.PAGE_START;
results.setLineWrap(true);
results.setWrapStyleWord(true);
scroll.setViewportView(results);
// Add label "Find"
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
pane.add(findLabel, c);
// Add text field
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.gridx = 1;
c.gridy = 0;
pane.add(findWord, c);
// Add clear button
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = .1;
c.gridx = 2;
c.gridy = 0;
pane.add(clear, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 2;
c.insets = new Insets(5, 5, 0, 0);
pane.add(wordsContaining, c);
// Add text area
c.fill = GridBagConstraints.BOTH;
c.weighty = 1;
c.gridx = 1;
c.gridy = 3;
c.insets = new Insets(0, 3, 0, 5);
pane.add(scroll, c);
add(pane);
pack();
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new WordFinder().setVisible(true);
}
});
}
}
The problem you're having is caused by a combination of using the fill property GridBagConstraints.HORIZONTAL and setSize. When you use setSize, the size of the container is smaller then the JScrollPane's preferredSize and the layout manager is resorting to it's minimumSize instead.
By using GridBagConstraints.BOTH, you are allowing the layout manager to expand the component to fill the entire available space of the cell, regardless

Related

The component doesn't display correctly with GridBagLayout

I'm learning java swing and this is very confused to me. The quit button doesn't display. However, if I move the code part of textArea after the two parts of buttons, it will display correctly. So why?
package exercise1;
import javax.swing.*;
import java.awt.*;
public class ChatClient {
private JTextArea textArea;
private JTextField textField;
private JButton btnSend;
private JButton btnQuit;
private JFrame frame;
private JPanel panel;
private JScrollPane scrollPane;
private void launchFrame() {
panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
textArea = new JTextArea(10, 50);
scrollPane = new JScrollPane(textArea);
c.gridx = 0;
c.gridy = 0;
c.gridheight = 3;
panel.add(scrollPane, c);
btnSend = new JButton("Send");
c.gridx = 1;
c.gridy = 0;
c.anchor = GridBagConstraints.NORTH;
panel.add(btnSend, c);
btnQuit = new JButton("Quit");
c.gridx = 1;
c.gridy = 1;
c.anchor = GridBagConstraints.NORTH;
panel.add(btnQuit, c);
}
protected ChatClient() {
frame = new JFrame("Chat Room");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
launchFrame();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
ChatClient client = new ChatClient();
}
}
Simple: You forgot to reset c.gridheight = 1; after adding the JScrollPane. Without doing this, the send button will overlie the quit button.
private void launchFrame() {
panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL; // ** This is also worthwhile **
textArea = new JTextArea(10, 50);
scrollPane = new JScrollPane(textArea);
c.gridx = 0;
c.gridy = 0;
c.gridheight = 3;
panel.add(scrollPane, c);
btnSend = new JButton("Send");
c.gridx = 1;
c.gridy = 0;
c.gridheight = 1; // ********* ADD THIS *********
c.anchor = GridBagConstraints.NORTH;
panel.add(btnSend, c);
btnQuit = new JButton("Quit");
c.gridx = 1;
c.gridy = 1;
c.anchor = GridBagConstraints.NORTH;
panel.add(btnQuit, c);
}

Put space between label in GridLayout

package committeeGUI;
import static committeeGUI.CommitteeGUI.comList;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class StudentMemberFrame extends JFrame {
public StudentMemberFrame() {
super("Add Student");
setSize(450, 500);
setLocation(561, 150);
super.setResizable(false);
addStudentMember();
}
public void addStudentMember() {
CommitteeGUI.frame.setEnabled(false);
final JPanel showConsoleArea = new JPanel(new FlowLayout(FlowLayout.LEFT));
showConsoleArea.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//creating border and size of the border
showConsoleArea.setBorder(BorderFactory.createLineBorder(Color.black, 3));
add(showConsoleArea); //, BorderLayout.CENTER);
//setting a size to showConsoleArea.
showConsoleArea.setSize(500, 500);
final JLabel lblheading = new JLabel("STUDENT");
// showConsoleArea.add(lblheading,BorderLayout.CENTER);
/*
* creating components of company form
*/
final JLabel lblCommitteeName = new JLabel("Committee name");
final JTextField txtName = new JTextField(15);
final JLabel lblMemberName = new JLabel("Student name");
final JTextField txtMemberName = new JTextField(15);
final JLabel lblMemberNumber = new JLabel("Student number");
final JTextField txtMemberNumber = new JTextField(15);
final JLabel lblMemberCourse = new JLabel("Student course");
final JTextField txtMemberCourse = new JTextField(15);
final JButton buttAdd = new JButton("SAVE");
final JButton buttCancel = new JButton("CANCEL");
// adding components to the display area
c.gridx = 1;
c.gridy = 0;
showConsoleArea.add(lblheading, c);
c.gridx = 0;
c.gridy = 1;
showConsoleArea.add(lblCommitteeName, c);
c.gridx = 1;
c.gridy = 1;
showConsoleArea.add(txtName, c);
c.gridx = 0;
c.gridy = 2;
showConsoleArea.add(lblMemberName, c);
c.gridx = 1;
c.gridy = 2;
showConsoleArea.add(txtMemberName, c);
c.gridx = 0;
c.gridy = 3;
showConsoleArea.add(lblMemberNumber, c);
c.gridx = 1;
c.gridy = 3;
showConsoleArea.add(txtMemberNumber, c);
c.gridx = 0;
c.gridy = 4;
showConsoleArea.add(lblMemberCourse, c);
c.gridx = 1;
c.gridy = 4;
showConsoleArea.add(txtMemberCourse, c);
c.gridx = 0;
c.gridy = 5;
showConsoleArea.add(buttAdd, c);
c.gridx = 1;
c.gridy = 5;
showConsoleArea.add(buttCancel, c);
/*
* able to displaying the company frame
*/
this.show();
buttAdd.addActionListener((ActionEvent e) -> {
if (txtName.getText().equals("")
|| txtMemberName.getText().equals("")
|| txtMemberNumber.getText().equals("")
|| txtMemberCourse.getText().equals("")) //validating the data
{
CommitteeGUI.frame.setEnabled(false);
setEnabled(false);
messagebox("Enter a valid data", 0);
return;
}
if (!txtMemberNumber.getText().matches("\\d+")) {
CommitteeGUI.frame.setEnabled(false);
setEnabled(false);
messagebox("Member number must be a integer", 0);
return;
}
for (Committee com : comList) {
if (com.getName().equals(txtName.getText())) {
Student st = new Student();
st.setName(txtMemberName.getText());
st.setAcademicNo(Integer.parseInt(txtMemberNumber.getText()));
st.setCourse(txtMemberCourse.getText());
com.memberList.add(st);
messagebox("Member added successfully", 1);
setEnabled(false);
return;
}
}
messagebox("No Committee found with given name", 1);
});
//creating ActionListner to Cancel button
buttCancel.addActionListener((ActionEvent e) -> {
//frame is enabled for user.
CommitteeGUI.frame.setEnabled(true);
dispose(); //disposing the frame
} //pass the action to actionPerformed method and perform it.
);
}
#SuppressWarnings("deprecation")
public void messagebox(String label, final int conform) {
final JDialog infoBox = new JDialog();//message box
infoBox.setSize(400, 90);
infoBox.setAlwaysOnTop(true);
infoBox.setResizable(false);
infoBox.setLocation(675, 258);
JLabel space = new JLabel(" ");
JLabel label1 = new JLabel(label);
JButton buttOk = new JButton("Ok");
buttOk.addActionListener((ActionEvent e) -> {
if (conform == 1) {
// making frame operation enable.
CommitteeGUI.frame.setEnabled(true);
dispose();
}
setEnabled(true);
infoBox.hide();
});
JPanel holder = new JPanel(new FlowLayout());
holder.add(label1);
holder.add(buttOk);
infoBox.add(holder);
infoBox.show();
}
}
Above is my code. I want to put space between the heading (STUDENT) and the fields.
Attached is the snapshot of the frame:
I am not familiar with this layout. Help is much appreciated.
public void addStudentMember() {
final JPanel showConsoleArea = new JPanel(new FlowLayout(FlowLayout.LEFT));
showConsoleArea.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// Add below line of code change appropriate spacing
c.insets = new Insets(10, 10, 10, 10);

Getting rid of extra spaces between components when the JFrame is resized

I am using the GridBagLayout to arrange some components in a frame.
When the frame is first created, the components have a decent space in between them.
But as soon as I resize the frame there are alot of unwanted space between the components
I tried adjusting the weights and insets as suggested by some users, but it does not seem to fix the problem
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JTextArea;
public class Frame1 extends JFrame {
JLabel one = new JLabel("one");
JLabel two = new JLabel("two");
JLabel three = new JLabel("three");
JTextField oneF = new JTextField(20);
JTextField twoF = new JTextField(20);
JTextField threeF = new JTextField(20);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("menu");
GridBagConstraints c = new GridBagConstraints();
public Frame1() {
setTitle("GridBagLayout Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
menuBar.add(menu);
c.gridx = 0;
c.gridy = 0;
c.gridwidth = c.REMAINDER;
c.fill = c.HORIZONTAL;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(menuBar, c);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(one, c);
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(oneF, c);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(two, c);
c.gridx = 1;
c.gridy = 2;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(twoF, c);
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(three, c);
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(threeF, c);
//setResizable(false);
pack();
setVisible(true);
}
}
ps:- I am new to GUI programming, so please forgive me for any noob mistakes.
edit 1: This is the what I want to have after I am done. I know the currently it does not look anyway near what I have in mind... I am still working on it
Thanks
use an nested layout (combinations of a few LayoutManagers), your picture talks me about,
still you can use GridBagLayout for components placed into left side,
in my code (simplest idea as is possible) JComponents placed on left side can't be resizable because are restricted from LayoutManager`s defaults, more in Oracle tutorial
.
.
painted from SSCCE/MCVE
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyFrame {
private static final long serialVersionUID = 1L;
private JFrame myFrame = new JFrame("Whatever");
private JPanel parentPanel = new JPanel(new BorderLayout(10, 10)) {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 400);
}
#Override
public Color getBackground() {
return new Color(255, 000, 000);
}
};
private JPanel leftPanel = new JPanel(/*default is FlowLayout*/) {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 400);
}
#Override
public Color getBackground() {
return new Color(255, 255, 000);
}
};
private JPanel leftChildPanel = new JPanel() {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 400);
}
#Override
public Color getBackground() {
return new Color(255, 255, 225);
}
};
private JPanel rightPanel = new JPanel(new BorderLayout(10, 10)) {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 380);
}
#Override
public Color getBackground() {
return new Color(000, 255, 225);
}
};
public MyFrame() {
parentPanel.add(leftPanel, BorderLayout.WEST);
leftPanel.add(leftChildPanel);
parentPanel.add(rightPanel);
myFrame.add(parentPanel);
myFrame.setLocation(150, 150);
myFrame.pack();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new MyFrame();
});
}
}
The idea is to add empty row / columns that will grow to fill the available space:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JTextField;
public class Frame1 extends JFrame {
JLabel one = new JLabel("one");
JLabel two = new JLabel("two");
JLabel three = new JLabel("three");
JTextField oneF = new JTextField(20);
JTextField twoF = new JTextField(20);
JTextField threeF = new JTextField(20);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("menu");
public Frame1() {
setTitle("GridBagLayout Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0}; //this defines 4 rows
//make 2 last empty row grow
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 1.0,1.0};
//do the same for columns
gridBagLayout.columnWidths = new int[]{0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, 1.0,1.0};
getContentPane().setLayout(gridBagLayout);
menuBar.add(menu);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 5;
c.fill = c.HORIZONTAL;
c.anchor = c.NORTH;
c.insets = new Insets(5, 5, 5, 0);
getContentPane().add(menuBar, c);
//better have a new GridBagConstraints for each component added
GridBagConstraints c1 = new GridBagConstraints();
c1.gridx = 0;
c1.gridy = 1;
c1.gridwidth = 1;
c1.fill = c1.NONE;
c1.anchor = c1.NORTH;
c1.insets = new Insets(5, 5, 0, 5);
getContentPane().add(one, c1);
GridBagConstraints c2 = new GridBagConstraints();
c2.gridx = 1;
c2.gridy = 1;
c2.fill = c2.NONE;
c2.anchor = GridBagConstraints.NORTHWEST;
c2.insets = new Insets(5, 5, 0, 5);
getContentPane().add(oneF, c2);
pack();
setVisible(true);
}
public static void main(String[] args) {
new Frame1();
}
}
EDIT: in response to your edit: use the additional "growing" column for the "cover art"
The problem is your assignments of c.weightx and c.weighty. weightx and weighty determine how extra space is allocated to grid cells in a GridBagLayout when the container is made larger than necessary to accommodate the preferred sizes of the components.
The weightx and weighty should be zero for all cells except those cells which you want to grow larger when the window is made larger.
I have no real idea on how it is supposed to look like, but you could try to set for the labels c.anchor=GridBagConstraints.EAST and c.anchor=GridBagConstraints.WEST for the textfields.
Try also setting c.fill = GridBadConstraints.BOTH.

Want to resize components with the window?

I want to make my components on my JFrame resize with the resizing of the window.
How can this be done.
Currently when I make the JFrame smaller the components remain in the same place and then disappear as the frame gets smaller.
Ideally I would like to set a minimum JFrame size which would not allow the form to go any smaller but when I make it larger that components should move with the JFrame.
Add: What if I want to use an absolute layout manager. This is the layout manager that my boss prefers.
Code:
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import java.awt.Font;
public class TestFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JButton btnNewButton;
private JButton btnNewButton_1;
private JButton btnNewButton_2;
private JCheckBox chckbxNewCheckBox;
private JCheckBox chckbxNewCheckBox_1;
private JCheckBox chckbxNewCheckBox_2;
public static void main(String[] args) {
TestFrame frame = new TestFrame();
frame.setVisible(true);
}
public TestFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 629, 458);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(15, 15, 15, 15));
setContentPane(contentPane);
contentPane.setLayout(null);
btnNewButton = new JButton("Save");
btnNewButton.setFont(new Font("Sylfaen", Font.BOLD, 14));
btnNewButton.setBounds(514, 386, 89, 23);
contentPane.add(btnNewButton);
btnNewButton_1 = new JButton("Open");
btnNewButton_1.setBounds(514, 352, 89, 23);
contentPane.add(btnNewButton_1);
btnNewButton_2 = new JButton("Close");
btnNewButton_2.setBounds(514, 318, 89, 23);
contentPane.add(btnNewButton_2);
btnNewButton_2.setBackground(Color.YELLOW);
btnNewButton_2.setEnabled(false);
chckbxNewCheckBox = new JCheckBox("Employeed");
chckbxNewCheckBox.setBounds(506, 7, 97, 23);
contentPane.add(chckbxNewCheckBox);
chckbxNewCheckBox_1 = new JCheckBox("Not Employeed");
chckbxNewCheckBox_1.setBounds(506, 33, 97, 23);
contentPane.add(chckbxNewCheckBox_1);
chckbxNewCheckBox_2 = new JCheckBox("Self Employeed");
chckbxNewCheckBox_2.setBounds(506, 59, 97, 23);
contentPane.add(chckbxNewCheckBox_2);
}
}
An Example of GridBagLayout:
This is an an example of the GridBagLayout. The components resize correctly but I do not see a grow property. It must do that automatically.
import java.awt.*;
import javax.swing.JButton;
import javax.swing.JFrame;
public class GridBagLayoutDemo {
final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;
public static void addComponentsToPane(Container pane) {
JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
button = new JButton("Button 1");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
pane.add(button, c);
button = new JButton("Button 2");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
pane.add(button, c);
button = new JButton("Button 3");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 2;
c.gridy = 0;
pane.add(button, c);
button = new JButton("Long-Named Button 4");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40; //make this component tall
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
pane.add(button, c);
button = new JButton("5");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0; //reset to default
c.weighty = 1.0; //request any extra vertical space
c.anchor = GridBagConstraints.PAGE_END; //bottom of space
c.insets = new Insets(10,0,0,0); //top padding
c.gridx = 1; //aligned with button 2
c.gridwidth = 2; //2 columns wide
c.gridy = 2; //third row
pane.add(button, c);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("GridBagLayout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGUI();
}
}
Use a layout manager, like GridBagLayout, its have a property call "grow" for a column.

How to put a background image on GridBagLayout

I am trying to work with layout managers for the first time, and they are just kicking me in the teeth. I am trying to make a background image and then put buttons on top, using GridBagLayout, if there is a a better layoutmanager please do tell. As for trying to learn how to use layout managers, its very difficult and any learning references would also be much appreciated.
This is what it looks like currently,
I can get the frame to show the full image, but when i use gridlayout manager, it does that
public void addComponentsToPane(Container pane){
BackgroundImage image = new BackgroundImage();
JButton button1, button2, button3, button4, button5;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if(shouldFill){
c.fill = GridBagConstraints.NONE;
}
button1 = new JButton("Button 1");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 0;
button1.setOpaque(false);
pane.add(button1, c);
button2 = new JButton("Button 2");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 0;
button2.setOpaque(false);
pane.add(button2, c);
button3 = new JButton("Button 3");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 2;
c.gridy = 0;
button3.setOpaque(false);
pane.add(button3, c);
button4 = new JButton("Long-Named Button 4");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40; //make this component tall
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
pane.add(button4, c);
button5 = new JButton("button 1");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0; //reset to default
c.weighty = 1.0; //request any extra vertical space
c.anchor = GridBagConstraints.PAGE_END; //bottom of space
c.insets = new Insets(10,0,0,0); //top padding
c.gridx = 1; //aligned with button 2
c.gridwidth = 2; //2 columns wide
c.gridy = 2; //third row
pane.add(button5, c);
c.ipadx = 800;
c.ipady = 400;
pane.add(image, c);
}
This is what i'm trying to make it look like
Here is one way to do it: using a JLabel as a container with an image (it's a bit unusual but actually works pretty well):
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class TestBackgroundImage {
private static final String BACKHGROUND_IMAGE_URL = "http://www.okyn.org/wp-content/uploads/2013/04/League_of_Legends.jpeg";
protected void initUI() throws MalformedURLException {
JFrame frame = new JFrame(TestBackgroundImage.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final ImageIcon backgroundImage = new ImageIcon(new URL(BACKHGROUND_IMAGE_URL));
JLabel mainPanel = new JLabel(backgroundImage) {
#Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
Dimension lmPrefSize = getLayout().preferredLayoutSize(this);
size.width = Math.max(size.width, lmPrefSize.width);
size.height = Math.max(size.height, lmPrefSize.height);
return size;
}
};
mainPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
gbc.weightx = 1.0;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = GridBagConstraints.REMAINDER;
for (int i = 0; i < 5; i++) {
mainPanel.add(new JButton("Button " + (i + 1)), gbc);
}
// Let's put a filler bottom component that will push the rest to the top
gbc.weighty = 1.0;
mainPanel.add(Box.createGlue(), gbc);
frame.add(mainPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestBackgroundImage().initUI();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
And the result:
GridBagLayout is unable to handle layering of components (so if you have overlapping gridx/gridy pairs, it won't handle it as layering, I would think that the output is pretty much undetermined.
Try to avoid using gridx/gridy as it make a code hard to maintain. Playing with relative values on gridwidth/gridheight is much easier to maintain.
Check out the Background Panel for a couple of solutions depending on your requirement:
Use a JLabel for painting the image at its actual size.
Use the BackgroundPanel to allow for scaling of the background image.

Categories

Resources