How do I set the size of a JButton? - java

The button takes up the whole screen, and I try using setSize() but that doesn't appear to be doing anything. Here's my code so far:
JButton start = new JButton("PLAY");
start.setSize(new Dimension(100, 100));
myFrame.add(start);

By default, JFrame has BorderLayout with CENTER alignment. Thats why single component will takes full screen. So add a suitable Layout Manager to JFrame.
For details, go through, How to Use Various Layout Managers.

you can try using GridBagLayout to set it's size within a Container.
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class test extends JPanel{
private static final long serialVersionUID = 1L;
JButton b1, b2, b3, b4, b5;
GridBagConstraints g = new GridBagConstraints();
public test() {
setLayout(new GridBagLayout());
g.insets = new Insets(1, 1, 1, 1);
b1 = new JButton("Button 1");
g.gridx = 0;
g.gridy = 6;
g.gridwidth = 2;
g.gridheight = 1;
g.fill = GridBagConstraints.HORIZONTAL;
g.fill = GridBagConstraints.VERTICAL;
add(b1, g);
b2 = new JButton("Button 2");
g.gridx = 0;
g.gridy = 0;
g.gridwidth = 3;
g.gridheight = 1;
g.fill = GridBagConstraints.HORIZONTAL;
g.fill = GridBagConstraints.VERTICAL;
add(b2, g);
b3 = new JButton("Button 3");
g.gridx = 2;
g.gridy = 2;
g.gridwidth = 1;
g.gridheight = 1;
g.fill = GridBagConstraints.HORIZONTAL;
g.fill = GridBagConstraints.VERTICAL;
add(b3, g);
b4 = new JButton("Button 4");
g.gridx = 6;
g.gridy = 0;
g.gridheight = 3;
g.gridwidth = 1;
g.fill = GridBagConstraints.HORIZONTAL;
g.fill = GridBagConstraints.VERTICAL;
add(b4, g);
b5 = new JButton("Button 5");
g.gridx = 1;
g.gridy = 3;
g.gridheight = 1;
g.gridwidth = 2;
g.fill = GridBagConstraints.HORIZONTAL;
g.fill = GridBagConstraints.VERTICAL;
add(b5, g);
}
public static void main(String[] args) {
test t = new test();
JFrame frame = new JFrame("test");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.add(t);
}
}

Related

LayoutManager for different sized components without coding absolute positions

I'm trying to create some UI but no idea how to use LayoutManger for it.
Like showing in the image Purple color component have fixed width and height but stick to the corners. 8 and 4 have fixed with and variable height, 2 and 6 have fixed height and variable width. the middle component (9) need variable width and height.
These 8 component work like a border and middle one is need to resize according to parent component size. I could do this coding absolute positions using null layout. but I have suggested to not to use null layout.
How could I do this with a Layout manager witch layout I can use for this? Do I need to use more layouts than one?
UPDATE
i have tried something with GridBagLayout as Andrew's suggestion but I still need a little help to understand how it works. Here is my code
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GridLayoutTest {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel jPanel1 = new JPanel();
jPanel1.setLayout(new GridBagLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button;
GridBagConstraints c = new GridBagConstraints();
button = new JButton("1");
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.gridx = 0;
c.gridy = 0;
jPanel1.add(button, c);
button = new JButton("2");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1.0;
c.gridx = 1;
c.gridy = 0;
jPanel1.add(button, c);
button = new JButton("3");
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.FIRST_LINE_END;
c.gridx = 2;
c.gridy = 0;
jPanel1.add(button, c);
button = new JButton("4");
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.LINE_START;
c.weighty = 1.0;
c.gridx = 0;
c.gridy = 1;
jPanel1.add(button, c);
//Panel
JPanel panel = new JPanel();
panel.setBackground(Color.green.darker());
c.fill = GridBagConstraints.BOTH;
c.weightx = 0.0;
//c.weightx = 1.0;
c.gridx = 1;
c.gridy = 1;
jPanel1.add(panel, c);
button = new JButton("5");
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.LINE_END;
c.weighty = 1.0;
c.gridx = 2;
c.gridy = 1;
jPanel1.add(button, c);
button = new JButton("6");
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.LAST_LINE_START;
c.gridx = 0;
c.gridy = 2;
jPanel1.add(button, c);
button = new JButton("7");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1.0;
c.gridx = 1;
c.gridy = 2;
jPanel1.add(button, c);
button = new JButton("8");
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.LAST_LINE_END;
c.gridx = 2;
c.gridy = 2;
jPanel1.add(button, c);
frame.add(jPanel1);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
I created the following GUI.
I set all six of the GridBagConstraints (anchor, fill, gridx, gridy, weightx, weighty) for each element of the grid. That way, I could more easily keep track of what the values were for each element.
Here's the complete runnable code I used. In other words a minimal, reproducible example.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GridBagLayoutGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new GridBagLayoutGUI());
}
#Override
public void run() {
JFrame frame = new JFrame("GridBagLayout GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setPreferredSize(new Dimension(300, 300));
JButton button;
GridBagConstraints c = new GridBagConstraints();
button = new JButton("1");
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.weightx = 0.0d;
c.weighty = 0.0d;
c.gridx = 0;
c.gridy = 0;
panel.add(button, c);
button = new JButton("2");
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
c.weightx = 1.0d;
c.weighty = 0.0d;
c.gridx = 1;
c.gridy = 0;
panel.add(button, c);
button = new JButton("3");
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.FIRST_LINE_END;
c.weightx = 0.0d;
c.weighty = 0.0d;
c.gridx = 2;
c.gridy = 0;
panel.add(button, c);
button = new JButton("4");
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.LINE_START;
c.weightx = 0.0d;
c.weighty = 1.0d;
c.gridx = 0;
c.gridy = 1;
panel.add(button, c);
// Panel
JPanel innerPanel = new JPanel();
innerPanel.setBackground(Color.green.darker());
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.CENTER;
c.weightx = 1.0d;
c.weighty = 1.0d;
c.gridx = 1;
c.gridy = 1;
panel.add(innerPanel, c);
button = new JButton("5");
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.LINE_END;
c.weightx = 0.0d;
c.weighty = 1.0d;
c.gridx = 2;
c.gridy = 1;
panel.add(button, c);
button = new JButton("6");
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LAST_LINE_START;
c.weightx = 0.0d;
c.weighty = 0.0d;
c.gridx = 0;
c.gridy = 2;
panel.add(button, c);
button = new JButton("7");
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
c.weightx = 1.0d;
c.weighty = 0.0d;
c.gridx = 1;
c.gridy = 2;
panel.add(button, c);
button = new JButton("8");
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LAST_LINE_END;
c.weightx = 0.0d;
c.weighty = 0.0d;
c.gridx = 2;
c.gridy = 2;
panel.add(button, c);
return panel;
}
}
Another option would be JGoodies FormLayout. I have been using this in combination with JFormDesigner for all my layouting needs since basically forever. It covers 95% percent of my use cases. The remaining 5% is BorderLayout and absolute positioning (null layout).
A common strategy to solve complex computing tasks, is to break them into small, well defined manageable tasks. Divide and conquer.
This also applies to gui: you can break the design into small, easy to layout containers.
In this case the needed layout can be achieved by using BoxLayout and BorderLayout:
import java.awt.*;
import javax.swing.Box.Filler;
import javax.swing.*;
public class FramedContent extends JPanel{
private static final int FRAME_WIDTH = 35, CONTENT_SIZE = 300, BORDER_SIZE = 1;
private static final Color CORNER_COLOR = Color.MAGENTA, RULLER_COLOR = Color.BLUE,
CONTENT_COLOR = Color.GREEN, BORDER_COLOR = Color.WHITE;
FramedContent(){
setLayout(new BorderLayout());
add(header(), BorderLayout.NORTH);
add(center(), BorderLayout.CENTER);
add(header(), BorderLayout.SOUTH);
}
private JPanel header(){
JPanel hExpandPane = new JPanel();
hExpandPane.setLayout(new BoxLayout(hExpandPane, BoxLayout.X_AXIS));
hExpandPane.add(corner());
hExpandPane.add(hRuller());
hExpandPane.add(corner());
return hExpandPane;
}
private JComponent corner(){
Dimension d = new Dimension(FRAME_WIDTH, FRAME_WIDTH);
Filler filler = new Filler(d, d, d);
filler.setBackground(CORNER_COLOR);
filler.setBorder(BorderFactory.createLineBorder(BORDER_COLOR, BORDER_SIZE));
filler.setOpaque(true);
return filler;
}
private JComponent hRuller(){
Dimension d = new Dimension(0,FRAME_WIDTH);
Filler filler = new Filler(d, d, new Dimension(Short.MAX_VALUE, FRAME_WIDTH));
filler.setBackground(RULLER_COLOR);;
filler.setOpaque(true);
return filler;
}
private JPanel center(){
JPanel vExpandPane = new JPanel();
vExpandPane.setLayout(new BorderLayout());
vExpandPane.add(vRuller(), BorderLayout.WEST);
vExpandPane.add(content(), BorderLayout.CENTER);
vExpandPane.add(vRuller(), BorderLayout.EAST);
return vExpandPane;
}
private JComponent vRuller(){
Dimension d = new Dimension(FRAME_WIDTH, 0);
Filler filler = new Filler(d, d, new Dimension(FRAME_WIDTH, Short.MAX_VALUE));
filler.setBackground(RULLER_COLOR);
filler.setOpaque(true);
return filler;
}
private JPanel content(){
JPanel content = new JPanel(new GridBagLayout());// GridBagLayout used just to center the content
content.setBackground(CONTENT_COLOR);
content.add(new JLabel("Your Content Goes Here"));
content.setPreferredSize(new Dimension(CONTENT_SIZE,CONTENT_SIZE));
return content;
}
public static void createWindow() {
JFrame frame = new JFrame("Framed content");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(new FramedContent());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createWindow();
}
}

Does GridBagLayout affect JLabel images?

Currently trying to add a header image to my JFrame based GUI, I've developed the layout of the project and everything looks good, but every time I run the project the image does not load (no error messages).
My code (partial):
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
public class DeltaFlightFrame extends JFrame implements ActionListener, ChangeListener{
//<SNIPPED CODE FOR EASE OF VIEWING>
//Labels for inputs
//<SNIPPED CODE FOR EASE OF VIEWING>
private JLabel deltaLogo;
//icon
private Icon logo;
//<SNIPPED CODE FOR EASE OF VIEWING>
DeltaFlightFrame() {
GridBagConstraints layoutConst = null;
//<SNIPPED CODE FOR EASE OF VIEWING>
setTitle("Delta Flight Price Estimator");
//<SNIPPED CODE FOR EASE OF VIEWING>
//initialize delta logo
logo = new ImageIcon("../img/logo.png");
deltaLogo = new JLabel(logo);
System.out.println("Height" + logo.getIconHeight());
System.out.println("Width" + logo.getIconWidth());
//<SNIPPED CODE FOR EASE OF VIEWING>
// Create frame and add components using GridBagLayout
setLayout(new GridBagLayout());
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
//layoutConst.anchor = GridBagConstraints.LINE_START;
layoutConst.gridx = 0;
layoutConst.gridy = 0;
//layoutConst.gridwidth = 4;
add(deltaLogo, layoutConst);
//<SNIPPED CODE FOR EASE OF VIEWING>
}
//TODO: this
public void stateChanged(ChangeEvent event) {
}
//TODO, also: this
public void actionPerformed(ActionEvent event) {
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception ignored){}
DeltaFlightFrame myFrame = new DeltaFlightFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setVisible(true);
}
}
My full code (I didn't want to put it all, it's a disgusting mess and I'm a first year student so this isn't... nice... hahaha):
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
public class DeltaFlightFrame extends JFrame implements ActionListener, ChangeListener{
//Text Fields
private JTextField desCityField; // Holds destination city abbreviation,
private JTextField depCityField; // Holds departure city abbreviation.
private JTextField finalOutputField; //Shows final price
//Drop Down
//=====TODO
//Labels for inputs
private JLabel desCityLabel;
private JLabel depCityLabel;
private JLabel tripTypeLabel;
private JLabel seatTypeLabel;
private JLabel adultTravelerCountLabel;
private JLabel childTravelerCountLabel;
private JLabel finalOutput; //final price
private JLabel flightTitle;
private JLabel passengerTitle;
private JLabel deltaLogo;
//icon
private Icon logo;
//dropdown
String[] seatClassChoices = { "Basic Economy", "Business+ Comfort", "First Class" };
private JComboBox seatClassDrop;
//JSpinners
private JSpinner adultTravelerCount;
private JSpinner childTravelerCount;
//radio button
private JRadioButton oneWay;
private JRadioButton roundTrip;
//Buttons
private JButton calculateButton;
/* Constructor creates GUI components and adds GUI components
using a GridBagLayout. */
DeltaFlightFrame() {
GridBagConstraints layoutConst = null;
SpinnerNumberModel spinnerModelAdult = null;
SpinnerNumberModel spinnerModelChild = null;
String desInit = "ATL";
String depInit = "JFK";
double priceInit = 150.00;
int passCountMin = 0;
int passCountMax = 9;
int passAdultInit = 1;
int passChildInit = 0;
//Set Frame Title
setTitle("Delta Flight Price Estimator");
//create labels
depCityLabel = new JLabel("Departure City: ");
desCityLabel = new JLabel("Destination City: ");
tripTypeLabel = new JLabel("Trip Type: ");
seatTypeLabel = new JLabel("Seat Class: ");
adultTravelerCountLabel = new JLabel("Travelling Adults: ");
childTravelerCountLabel = new JLabel("Travelling Children: ");
finalOutput = new JLabel("Price: ");
flightTitle = new JLabel("Flight Information");
flightTitle.setFont(new Font("Sans-Serif", Font.BOLD, 20));
passengerTitle = new JLabel("Passenger Information");
passengerTitle.setFont(new Font("Sans-Serif", Font.BOLD, 20));
//create dropdown
seatClassDrop = new JComboBox<String>(seatClassChoices);
//create spinners
spinnerModelAdult = new SpinnerNumberModel(passAdultInit, passCountMin, passCountMax, 1);
adultTravelerCount = new JSpinner(spinnerModelAdult);
spinnerModelChild = new SpinnerNumberModel(passChildInit, passCountMin, passCountMax, 1);
childTravelerCount = new JSpinner(spinnerModelChild);
//initialize delta logo
logo = new ImageIcon("../img/logo.png");
deltaLogo = new JLabel(logo);
System.out.println("Height" + logo.getIconHeight());
System.out.println("Width" + logo.getIconWidth());
//initialize text fields
desCityField = new JTextField("JFK");
desCityField.setEditable(true);
desCityField.setDocument(new LengthRestrictedDocument(3));
desCityField.setColumns(3);
depCityField = new JTextField("ATL");
depCityField.setEditable(true);
depCityField.setDocument(new LengthRestrictedDocument(3));
depCityField.setColumns(3);
//radio button
oneWay = new JRadioButton("One Way");
roundTrip = new JRadioButton("Round Trip");
//button
calculateButton = new JButton("Calculate");
calculateButton.addActionListener(this);
ButtonGroup tripType = new ButtonGroup();
tripType.add(oneWay);
tripType.add(roundTrip);
// Create frame and add components using GridBagLayout
setLayout(new GridBagLayout());
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
//layoutConst.anchor = GridBagConstraints.LINE_START;
layoutConst.gridx = 0;
layoutConst.gridy = 0;
//layoutConst.gridwidth = 4;
add(deltaLogo, layoutConst);
setLayout(new GridBagLayout());
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
layoutConst.anchor = GridBagConstraints.LINE_START;
layoutConst.gridx = 0;
layoutConst.gridy = 1;
layoutConst.gridwidth = 4;
add(flightTitle, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
layoutConst.anchor = GridBagConstraints.LINE_START;
layoutConst.gridx = 0;
layoutConst.gridy = 2;
layoutConst.gridwidth = 1;
add(desCityLabel, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
layoutConst.anchor = GridBagConstraints.LINE_START;
layoutConst.gridx = 2;
layoutConst.gridy = 2;
layoutConst.gridwidth = 1;
add(depCityLabel, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 10);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 1;
layoutConst.gridy = 2;
layoutConst.gridwidth = 1;
add(desCityField, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 10);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 3;
layoutConst.gridy = 2;
layoutConst.gridwidth = 1;
add(depCityField, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 0;
layoutConst.gridy = 4;
layoutConst.gridwidth = 1;
add(roundTrip, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 10);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 2;
layoutConst.gridy = 4;
layoutConst.gridwidth = 2;
add(seatClassDrop, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 0;
layoutConst.gridy = 5;
layoutConst.gridwidth = 1;
add(oneWay, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(50, 10, 1, 1);
layoutConst.anchor = GridBagConstraints.LINE_START;
layoutConst.gridx = 0;
layoutConst.gridy = 6;
layoutConst.gridwidth = 4;
add(passengerTitle, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 10, 1);
layoutConst.fill = GridBagConstraints.LINE_START;
layoutConst.gridx = 0;
layoutConst.gridy = 7;
layoutConst.gridwidth = 1;
add(adultTravelerCountLabel, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 10, 10);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 1;
layoutConst.gridy = 7;
layoutConst.gridwidth = 1;
add(adultTravelerCount, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 10, 10);
layoutConst.fill = GridBagConstraints.LINE_START;
layoutConst.gridx = 2;
layoutConst.gridy = 7;
layoutConst.gridwidth = 1;
add(childTravelerCountLabel, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 10, 10);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 3;
layoutConst.gridy = 7;
layoutConst.gridwidth = 1;
add(childTravelerCount, layoutConst);
}
//TODO: this
public void stateChanged(ChangeEvent event) {
}
//TODO, also: this
public void actionPerformed(ActionEvent event) {
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception ignored){}
DeltaFlightFrame myFrame = new DeltaFlightFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setVisible(true);
}
}
I did do some messing around, here:
logo = new ImageIcon("../img/logo.png");
deltaLogo = new JLabel(logo);
System.out.println("Height: " + logo.getIconHeight());
System.out.println("Width: " + logo.getIconWidth());
And the output of that was:
Height: -1
Width: -1
Which I do find odd, if that's a starting point.
SO, my question is: Does my setup with GridBagLayout affect the display of the of the JLabel image?
Using the website provided by #camickr, I was able to successfully render the image using their "createImageIcon" method.

Componenets alignment in GridBagLayout

I am using GridBagLayout to align components. Actually, i have two buttons which i want to align like this:
Desired layout:
But the following code results in the following layout:
Resulted layout:
My code:
iconAdd = new ImageIcon(getClass().getResource("../images/add.png"));
add = new JButton(iconAdd);
add.setPreferredSize(new Dimension(130, 100));
add.setBorder(new LineBorder(Color.decode("#9b9999"), 1, true));
add.setCursor(Cursor.getPredefinedCursor(12));
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5, 5, 5, 5);
pane.add(add, gbc);
iconSearch = new
ImageIcon(getClass().getResource("../images/search.png"));
search = new JButton(iconSearch);
search.setCursor(Cursor.getPredefinedCursor(12));
search.setPreferredSize(new Dimension(130, 100));
search.setBorder(new LineBorder(Color.decode("#9b9999"), 1, true));
gbc.gridx++;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5, 5, 5, 5);
pane.add(search, gbc);
Any help would be highly appreciated.
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class GridBagLayoutDemo extends JFrame{
GridBagLayoutDemo(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWeights = new double[]{1.0, 1.0, 1.0};
gridBagLayout.columnWidths = new int[]{0,0,300};
getContentPane().setLayout(gridBagLayout);
JButton button1 = new JButton("Long Button");
GridBagConstraints c1 = new GridBagConstraints();
c1.fill = GridBagConstraints.HORIZONTAL;
c1.weightx = 0.0;
c1.gridwidth = 3;
c1.gridx = 0;
c1.gridy = 0;
getContentPane().add(button1, c1);
JButton button2 = new JButton("Button 2");
GridBagConstraints c2 = new GridBagConstraints();
c2.weightx = 0.5;
c2.gridx = 0;
c2.gridy = 1;
getContentPane().add(button2, c2);
JButton button3 = new JButton("Button 3");
GridBagConstraints c3 = new GridBagConstraints();
c3.weightx = 0.5;
c3.gridx = 1;
c3.gridy = 1;
getContentPane().add(button3, c3);
pack();
setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new GridBagLayoutDemo();
}
});
}
}
gbc.weightx = 1;
You are telling the layout to give extra space to each component. So essentially each component becomes half the size of the frame.
You really only want that constraint set for the second button, so it takes up all the remaining space.
Read the section from the Swing tutorial on How to Use GridBagLayout which explains how the weightx/y constraints should be used.
Also, an easier solution would be do just use a FlowLayout. Create a panel with a FlowLayout. Add the buttons to the panel. Then add the panel to the BorderLayout.PAGE_START of the frame.

JScrollPane not showing on JTable

I am trying to get a JScrollPane to appear on my JTable. I passed the table to the scrollpane when i created an instance of the component. But to no avail it has yet to show on my table.
table = new JTable();
scrollPane = new JScrollPane(table);
table.setPreferredSize(new Dimension(200,100));
I dont know how i can fix this issue, i cant seem to find an issue that would cause it to fail. Here is the rest of the GUI code. It is very long. Adding the jtable to a jpanel starts at line 152.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javasql;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GraphicsConfiguration;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.event.ActionEvent;
import javax.swing.table.DefaultTableModel;
/**
*
* #author KJ4CC
*/
public class UserInterface implements ActionListener {
DefaultTableModel dtm = new DefaultTableModel(0, 0);
public UserInterface() {
startGui();
}
JFrame frame = new JFrame();
Javasql sql = new Javasql();
JPanel buttom = new JPanel(new GridBagLayout());
JPanel commandPane = new JPanel(new GridBagLayout());
JPanel top = new JPanel(new GridBagLayout());
JPanel buttons = new JPanel(new GridBagLayout());
JPanel label = new JPanel(new GridBagLayout());
JButton connect = new JButton("Connect To Database");
JButton clr = new JButton("Clear Command");
JButton exeSql = new JButton("Execute SQL Command");
JButton clrRes = new JButton("Clear Result Window");
JLabel infoLabel = new JLabel("Enter Database Information ");
JLabel driverLabel = new JLabel("JDBC Driver: ");
JLabel dbLabel = new JLabel("Database URL: ");
JLabel userLabel = new JLabel("Username: ");
JLabel passLabel = new JLabel("Password: ");
JLabel sqlLabel = new JLabel("Enter SQL Command: ");
JLabel connectionLabel = new JLabel("No Connection Now ");
JLabel exeLabel = new JLabel("SQL Execution Result: ");
//creating an instance of the new table
public JTable table;
public JScrollPane scrollPane;
JComboBox driverSelect = new JComboBox();
JComboBox url = new JComboBox();
JTextField username = new JTextField();
JTextField pass = new JTextField();
JTextArea command = new JTextArea(1, 1);
public void startGui() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagConstraints c = new GridBagConstraints();
System.out.println("sdf");
c.insets = new Insets(0, 0, 0, 10);
c.fill = 0;
c.weightx = 1;
//adding all of the compoenets to their panel and then to the frame.
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
top.add(infoLabel, c);
c.gridx = 0;
c.gridy = 1;
top.add(driverLabel, c);
c.gridx = 1;
c.gridy = 1;
c.ipadx = 150;
c.fill = GridBagConstraints.HORIZONTAL;
top.add(driverSelect, c);
c.gridx = 0;
c.gridy = 2;
c.fill = 0;
top.add(dbLabel, c);
c.gridx = 1;
c.gridy = 2;
c.fill = GridBagConstraints.HORIZONTAL;
top.add(url, c);
c.gridx = 0;
c.gridy = 3;
c.fill = 0;
c.fill = 0;
top.add(userLabel, c);
c.gridx = 1;
c.gridy = 3;
c.fill = GridBagConstraints.HORIZONTAL;
top.add(username, c);
c.gridx = 0;
c.gridy = 4;
c.fill = 0;
c.fill = 0;
top.add(passLabel, c);
c.gridx = 1;
c.gridy = 4;
c.fill = GridBagConstraints.HORIZONTAL;
top.add(pass, c);
//add the driver and url to the comboboxes
c.gridx = 2;
c.gridy = 0;
commandPane.add(sqlLabel, c);
c.gridx = 2;
c.gridy = 1;
c.ipadx = 150;
c.ipady = 75; //sql text area for command
c.fill = GridBagConstraints.FIRST_LINE_END;
c.fill = GridBagConstraints.HORIZONTAL;
commandPane.add(command, c);
c.insets = new Insets(0, 0, 0, 20);
c.ipadx = 9;
c.ipady = 1;
c.gridx = 0;
c.gridy = 0;
//buttons
label.add(connectionLabel, c);
c.gridx = 1;
c.gridy = 0;
//c.insets = new Insets(0, 0, 0, 50);
buttons.add(connect, c);
connect.addActionListener(this);
c.gridx = 2;
buttons.add(clr, c);
clr.addActionListener(this);
c.gridx = 3;
buttons.add(exeSql, c);
exeSql.addActionListener(this);
//adding the label and buttons above and below the tabel.
c.gridx = 0;
c.gridy = 1;
buttom.add(exeLabel, c);
c.gridx = 0;
c.gridy = 2;
//-----------------------------------------------------------------Table here
table = new JTable();
scrollPane = new JScrollPane(table);
table.setPreferredSize(new Dimension(200, 100));
c.fill = GridBagConstraints.HORIZONTAL;
buttom.add(table, c);
buttom.add(scrollPane);
c.gridx = 0;
c.gridy = 3;
buttom.add(clrRes, c);
c.weightx = 2;
c.weighty = 2;
c.gridx = 0;
c.gridy = 0;
frame.setLayout(new GridLayout(3, 2));
frame.add(top);
c.gridx = 2;
c.gridy = 1;
frame.add(commandPane);
frame.add(label);
frame.add(buttons);
frame.add(buttom, BorderLayout.SOUTH);
//adding the content panel to the jframe.
frame.pack();
frame.setSize(1000, 550);
frame.setVisible(true);
//adding items to both of the combo boxes.
driverSelect.addItem("com.mysql.jdbc.Driver");
url.addItem("jdbc:mysql://localhost:3306/project3");
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == connect) {
sql.connect(this);
} else if (e.getSource() == clr) {
command.setText("");
} else if (e.getSource() == exeSql) {
sql.exeCommand(this);
}
}
}
You can not add the table twice :
table = new JTable();
scrollPane = new JScrollPane(table); //here
table.setPreferredSize(new Dimension(200, 100));
c.fill = GridBagConstraints.HORIZONTAL;
buttom.add(table, c); //here
buttom.add(scrollPane);
If you add it to the scrollPane, just add the scrollpane. A Component can't have two parents.
I did not check your complete code but try
buttom.add(scrollPane,c);
instead of this
buttom.add(table, c); //here
buttom.add(scrollPane);
scrollPane = new JScrollPane(table);
table.setPreferredSize(new Dimension(200, 100));
c.fill = GridBagConstraints.HORIZONTAL;
buttom.add(table, c);
buttom.add(scrollPane);
here you add the table twice, directly in the first line and (implicitly) along with the ScrollPane at the last line.
In Swing this is not possible. Therefore the JTable is removed from the Scrollpane at the first line, when you add it directly to the bottom panel, and in turn at the last line an empty scrollpane is added, removing the JTable added earlier.
just remove the first line.

GridBagLayout JLabels & JTextAreas organization within JPanel

I'm trying to make 4 columns within a panel.
JLabel(Title)
JLabel JLabel
JLabel JTextArea JLabel JTextArea
...
...
...
JButton
Its pretty much a panel where you enter data. The labels will be something like "speed" then you type in a number in the text area next to it. I'm having a problem with the gridbaglayout though. The title is pretty big so it looks something like this. Using GridBagLayout , The title is at (1,0) but seeing as its so big, when I put the JLabel1 (0,1) and JLabel2 (2,0), they are way too spaced out since the title seems to have taken a pretty big chunk.
JLabel(Title..............)
JLabel1 JLabel2
...
...
...
JButton
I want it to be more like
JLabel(Title..........................................)
JLabel JLabel
JLabel JTextArea JLabel JTextArea
...
...
...
JButton
The code if you'd like to run it:
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Example {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
new Example();
}
});
}
JFrame go = new JFrame("Example");
JPanel panel = new JPanel();
JButton Button = new JButton("Button");
GridBagLayout Grid = new GridBagLayout();
JLabel Title = new JLabel("LARGEE TITLEE");
JLabel Label1 = new JLabel("Label 1");
JLabel Label2 = new JLabel("Label 2");
public Example() {
panel.setLayout(Grid);
GridBagConstraints c = new GridBagConstraints();
Title.setFont(new Font("Serif", Font.BOLD, 60));
c.insets = new Insets(10,10,10,10);
c.gridy = 0; c.gridx = 1;
panel.add(Title, c);
c.gridy = 1; c.gridx = 0;
panel.add(Label1 , c);
c.gridx = 2;
panel.add(Label2, c);
c.gridy = 2; c.gridx = 1;
panel.add(Button, c);
go.add(panel);
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(750, 750);
go.setVisible(true);
}
}
Divide the screen into parts and specify the width of every component (gridwidth), as well as the gridx and gridy, so that they will be placed accordingly.
The output of the sample I wrote looks like this:
Code:
public class Example extends JPanel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Example();
}
});
}
JFrame go = new JFrame("Example");
JPanel panel = new JPanel();
GridBagLayout Grid = new GridBagLayout();
JLabel Title = new JLabel("LARGE TITLE", SwingConstants.CENTER);
JLabel Label1 = new JLabel("Label 1", SwingConstants.CENTER);
JLabel Label2 = new JLabel("Label 2", SwingConstants.CENTER);
JLabel anotherLabel1 = new JLabel("Another Label 1", SwingConstants.CENTER);
JLabel anotherLabel2 = new JLabel("Another Label 2", SwingConstants.CENTER);
JTextArea textArea1 = new JTextArea("TextArea 1");
JTextArea textArea2 = new JTextArea("TextArea 2");
public Example() {
panel.setLayout(Grid);
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
Title.setFont(new Font("Serif", Font.BOLD, 60));
JButton button;
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40; //increase height of the title
c.weightx = 0.5;
c.gridwidth = 4;
c.gridx = 0;
c.gridy = 0;
panel.add(Title, c);
c.ipady = 0;
c.gridwidth = 2;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 1;
panel.add(Label1, c);
c.weightx = 0.5;
c.gridwidth = 2;
c.gridx = 2;
c.gridy = 1;
panel.add(Label2, c);
c.ipady = 0;
c.gridwidth = 1;
c.weightx = 0.25;
c.gridx = 0;
c.gridy = 2;
panel.add(anotherLabel1, c);
c.weightx = 0.25;
c.gridx = 1;
c.gridy = 2;
panel.add(textArea1, c);
c.weightx = 0.25;
c.gridx = 2;
c.gridy = 2;
panel.add(anotherLabel2, c);
c.weightx = 0.25;
c.gridx = 3;
c.gridy = 2;
panel.add(textArea2, c);
button = new JButton("JButton");
c.ipady = 0;
c.weighty = 1.0;
c.insets = new Insets(10, 0, 0, 0);
c.gridx = 1;
c.gridwidth = 2;
c.gridy = 3;
panel.add(button, c);
go.add(panel);
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.pack();
go.setSize(750, 300);
go.setVisible(true);
}
}
Related Documentation:
How to Use GridBagLayout
If I get it right, what you need is to set the title label full width, try this:
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 4; //where 4 is the numbers of columns
c.gridx=0; // set position at (0,0) because now is full width
panel.add(title, c);

Categories