Cannot add Listeners - java

I'm trying to put some Listeners in my code but I can't. For example I want to add a listener and when I write somenthing in the textfield area , then I choose the JRadioButton "From TextField" and after that I push the button "Do It" , I want to see the text that I wrote(in TextField) on JTextArea. How is that possible?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javafx.scene.Group;
public class Layout {
final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;
public static void addComponentsToPane(Container pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);}
JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
GridBagConstraints c1 = new GridBagConstraints();
if (shouldFill) {
c.fill = GridBagConstraints.HORIZONTAL;}
JTextField text = new JTextField( "Some Text");
if (shouldWeightX) {
c.weightx = 0.5;}
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.ipady = 50;
pane.add(text, c);
String names[] = { "Ferrari", "Koenigsegg", "Alfa Romeo" };
JComboBox cb = new JComboBox( names );
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
c.ipady = 50;
pane.add(cb, c);
Box box=Box.createVerticalBox();
JCheckBox checkbox = new JCheckBox("Water");
JCheckBox checkbox2 = new JCheckBox("Fire");
JCheckBox checkbox3 = new JCheckBox("Earth");
c1.fill = GridBagConstraints.HORIZONTAL;
c1.weightx = 0.5;
c1.ipady = 5;
box.add(checkbox);
box.add(checkbox2);
box.add(checkbox3);
pane.add(box,c1);
JPanel container = new JPanel();
container.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
container.setLayout(new GridLayout(2, 1));
JSlider slider = new JSlider(JSlider.HORIZONTAL,0,100,50);
slider.setPreferredSize(new Dimension(150,20));
slider.setMinorTickSpacing(1);
slider.setMajorTickSpacing(10);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40;
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
pane.add(slider, c);
JTextField text1 = new JTextField(" ");
c.ipady = 80;
c.weighty = 2.0;
c.anchor = GridBagConstraints.BASELINE;
c.gridx = 0;
c.gridwidth = 3;
c.gridy = 2;
pane.add(text1, c);
JRadioButton b1= new JRadioButton("From JTextField");
JRadioButton b2= new JRadioButton("From JComboBox");
JRadioButton b3= new JRadioButton("From JCheckboxes");
JRadioButton b4= new JRadioButton("J Slider");
b1.setForeground(Color.BLUE);
b2.setForeground(Color.RED);
b3.setBackground(Color.GREEN);
Box box1 = Box.createHorizontalBox();
box1.add(b1);
box1.add(b2);
box1.add(b3);
box1.add(b4);
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 10;
c.weighty = 1.0;
c.anchor = GridBagConstraints.BASELINE;
c.gridx = 0;
c.gridwidth = 3;
c.gridy =2;
pane.add(box1,c);
button = new JButton("Do it");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady =0;
c.weighty = 1.0;
c.anchor = GridBagConstraints.PAGE_END;
c.insets = new Insets(10,0,0,0);
c.gridx = 0;
c.gridwidth =3;
c.gridy = 2;
pane.add(button, c);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame(" ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
frame.setSize(600,400);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Read the section from the Swing tutorial on How to Use Text Areas. The first example shows how to append text from a JTextField to a JTextArea. This example uses an ActionListener for the text field.
then I choose the JRadioButton "From TextField" and after that I push the button "Do It" , I want to see the text that I wrote(in TextField) on JTextArea.
The concept will be similar except you add the ActionListener to you button. Then when it is invoked you check if the "From TextField" radio button is selected. If so, then you get the text from the text field and append it to the text area.

Related

How to center text in one grid of a button that span in two grids?

I am trying to recreate Mac Calculator GUI. I use Swing and GridBagLayout for this project.
I manage to put 0 in a button that span in 2 column grid but I want to center it in the first column grid instead of 2 column grid.
Basically I want to the button to look exactly like:
.
In the calculator, the first column grid (consists of button "AC", "1", "4", "7" and "0") has the texts center evenly.
Here I try to use setHorizontalAlignment(SwingConstants.LEFT) but the result is not what I want.
JButton bt
n_0 = new JButton("0");
btn_0.setHorizontalAlignment(SwingConstants.LEFT);
GridBagConstraints gbc_btn_0 = new GridBagConstraints();
gbc_btn_0.fill = GridBagConstraints.HORIZONTAL;
gbc_btn_0.gridwidth = 2;
gbc_btn_0.insets = new Insets(0, 0, 5, 5);
gbc_btn_0.gridx = 0;
gbc_btn_0.gridy = 5;
frame.getContentPane().add(btn_0, gbc_btn_0);
Is it possible to achieve or are there alternative way to do this?
Do you absolutely need buttons ? I'm not used to the Mac, but if those calculator keys don't require an actual "button" behaviour (3D effect, moving the text when pressed, etc), maybe a plain JPanel would do.
In that case, if your "0" key is a JPanel, applying a GridLayout(1,2) to it and putting a JLabel("0") in the first cell and nothing in the second one would probably achieve the result you want.
Now of course you'll need handle click and key events at the JPanel level (look for example at this answer for more) but I think it would be a "clean" (from a component hierarchy point of view) way of doing it.
Update: Here is what I mean (part between ### comments):
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Calculator {
public static final Color CALC_BACKGROUND = new Color(44, 45, 47);
public static final Color KEY_BG_LAST_OPERATION = new Color(255,159,12);
public static final Color KEY_BG_NUMBER = new Color(96,97,99);
public static final Color KEY_BG_SPECIAL = new Color(64,65,67);
public static final Font BUTTON_FONT = new Font("SansSerif", Font.PLAIN, 30);
private static JComponent make0Button(String text) {
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(CALC_BACKGROUND));
panel.setBackground(KEY_BG_NUMBER);
final JLabel label = new JLabel(text);
label.setFont(BUTTON_FONT);
label.setForeground(Color.WHITE);
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
//#######################################
// The "0" key is a panel with two cells
panel.setLayout(new GridLayout(1, 2));
// The "0" text on the left
panel.add(label);
// A blank (dummy) label on the right
panel.add(new JLabel(" "));
//#######################################
panel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(text);
}
});
return panel;
}
private static JComponent makeStdButton(String text, Color color) {
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(CALC_BACKGROUND));
panel.setBackground(color);
panel.setLayout(new GridLayout(1, 1));
JLabel label = new JLabel(text);
label.setFont(BUTTON_FONT);
label.setForeground(Color.WHITE);
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
panel.add(label);
panel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(text);
}
});
return panel;
}
public static void addComponentsToPane(Container container) {
container.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// Result (top)
c.anchor = GridBagConstraints.EAST;
c.fill = GridBagConstraints.BOTH;
c.gridwidth = 4;
c.gridx = 0; c.gridy = 0;
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBackground(CALC_BACKGROUND);
final JLabel resultLabel = new JLabel("0");
resultLabel.setFont(new Font("SansSerif", Font.PLAIN, 100));
resultLabel.setForeground(Color.WHITE);
panel.add(resultLabel, BorderLayout.EAST);
container.add(panel, c);
// Special "0" key
c = new GridBagConstraints();
c.anchor = GridBagConstraints.CENTER;
c.fill = GridBagConstraints.BOTH;
c.gridwidth = 2;
c.gridx = 0; c.gridy = 5;
container.add(make0Button("0"), c);
// All other keys
c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridwidth = 1;
c.weightx = 1;
c.weighty = 1;
c.gridx = 0; c.gridy = 1;
container.add(makeStdButton("AC", KEY_BG_SPECIAL), c);
c.gridx = 1; c.gridy = 1;
container.add(makeStdButton("+/-", KEY_BG_SPECIAL), c);
c.gridx = 2; c.gridy = 1;
container.add(makeStdButton("%", KEY_BG_SPECIAL), c);
c.gridx = 3; c.gridy = 1;
container.add(makeStdButton("/", KEY_BG_LAST_OPERATION), c);
c.gridx = 0; c.gridy = 2;
container.add(makeStdButton("7", KEY_BG_NUMBER), c);
c.gridx = 1; c.gridy = 2;
container.add(makeStdButton("8", KEY_BG_NUMBER), c);
c.gridx = 2; c.gridy = 2;
container.add(makeStdButton("9", KEY_BG_NUMBER), c);
c.gridx = 3; c.gridy = 2;
container.add(makeStdButton("x", KEY_BG_LAST_OPERATION), c);
c.gridx = 0; c.gridy = 3;
container.add(makeStdButton("4", KEY_BG_NUMBER), c);
c.gridx = 1; c.gridy = 3;
container.add(makeStdButton("5", KEY_BG_NUMBER), c);
c.gridx = 2; c.gridy = 3;
container.add(makeStdButton("6", KEY_BG_NUMBER), c);
c.gridx = 3; c.gridy = 3;
container.add(makeStdButton("-", KEY_BG_LAST_OPERATION), c);
c.gridx = 0; c.gridy = 4;
container.add(makeStdButton("1", KEY_BG_NUMBER), c);
c.gridx = 1; c.gridy = 4;
container.add(makeStdButton("2", KEY_BG_NUMBER), c);
c.gridx = 2; c.gridy = 4;
container.add(makeStdButton("3", KEY_BG_NUMBER), c);
c.gridx = 3; c.gridy = 4;
container.add(makeStdButton("+", KEY_BG_LAST_OPERATION), c);
c.gridx = 2; c.gridy = 5;
container.add(makeStdButton(".", KEY_BG_NUMBER), c);
c.gridx = 3; c.gridy = 5;
container.add(makeStdButton("=", KEY_BG_LAST_OPERATION), c);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.setSize(400,600);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGUI());
}
}
Looks to me it's quite close to the expected layout... (with clicks, see console)
I recommend you to use:
mig_layout library.
allows you to make easy/adaptable designs and you can solve your problem.

JFrame: How to add a button that adds a new text field to the frame?

I'm pretty new to Java and I thought I'd try to get my hands dirty and make a GUI but I can't seem to get it to work the way I want it to.
I wrote some code thinking that if I press the "Add" button on the GUI then a new JTextField will appear underneath where all the other textfields are but that doesn't happen. Only one new JTextField does appear but it appears next to my Add button instead of underneath all the other textfields I have and if I press it again, nothing happens. I tried playing around with other variables but it just doesn't seem to be working properly. I feel like something is wrong with my ActionListener but I don't know what.
public class TheGUI extends JFrame{
List<JTextField> listOfTextFields = new ArrayList<JTextField>();
private JTextField desc1;
private JTextField instruct;
private JTextField desc2;
private JButton submit;
private JButton addNew;
public TheGUI() { //My GUI with the default fields & buttons that should be on there.
super("Chili");
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
instruct = new JTextField("Choose your words");
instruct.setEditable(false);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 0;
add(instruct, c);
addNew = new JButton("Add");
c.weightx = 0.0;
c.gridx = 1;
c.gridy = 0;
add(addNew, c);
submit = new JButton("Submit!");
c.weightx = 0.5;
c.gridwidth = 2;
c.gridx = 0;
c.gridy = GridBagConstraints.PAGE_END;
add(submit, c);
desc1 = new JTextField(10);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridwidth = 2;
c.gridx = 0;
c.gridy = 1;
add(desc1, c);
desc2 = new JTextField(10);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridwidth = 2;
c.gridx = 0;
c.gridy = 2;
add(desc2, c);
addNew.addActionListener(new Adder());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setVisible(true);
}
private class Adder implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
int i = 0;
listOfTextFields.add(new JTextField());
GridBagConstraints textFieldConstraints = new GridBagConstraints();
//Give it a max of 9 text fields that can be created.
while(i < 10) {
textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
textFieldConstraints.weightx = 0.5;
textFieldConstraints.gridx = 0;
textFieldConstraints.gridwidth = 2;
textFieldConstraints.gridy = 3 + i;
i++;
}
add(listOfTextFields.get(i), textFieldConstraints);
revalidate();
repaint();
}
}
}
Your while loop is really strange.
Your ActionListener should look like:
private class Adder implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
if (listOfTextFields.size() == 9) {
// Give it a max of 9 text fields that can be created.
return;
}
JTextField textfield = new JTextField();
listOfTextFields.add(textfield);
GridBagConstraints textFieldConstraints = new GridBagConstraints();
textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
textFieldConstraints.weightx = 0.5;
textFieldConstraints.gridx = 0;
textFieldConstraints.gridwidth = 2;
textFieldConstraints.gridy = 3 + listOfTextFields.size();
add(textfield, textFieldConstraints);
revalidate();
repaint();
}
}

wrap JScrollPane to TextArea in Java (working with GridBagConstraints)

i new to java and swing (came from c#) and try to add scrollbar to my textarea with no success.
I tried all kinds of techniques , it is very difficult to me
please take a look on the following code, I would be very happy
package firmwareUpdate;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public class firmwareUpdate {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new firmwareUpdate().createUI();
}
};
EventQueue.invokeLater(r);
}
private void createUI() {
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
// row #1
JButton btnUpload = new JButton("Browse hex/bin file...");
c.weightx = 0.5;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
frame.getContentPane().add(btnUpload, c);
JLabel lblFileName = new JLabel("aaa");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 4;
frame.getContentPane().add(lblFileName, c);
// row #2
JButton btnConfig = new JButton("Config");
// c.fill = GridBagConstraints.HORIZONTAL;
// c.ipady = 40; //make this component tall
// c.weightx = 0.0;
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
frame.getContentPane().add(btnConfig, c);
JButton btnHex2Bin = new JButton("hex2bin");
// c.fill = GridBagConstraints.HORIZONTAL;
// c.ipady = 40; //make this component tall
// c.weightx = 0.0;
c.gridx = 1;
c.gridy = 2;
c.gridwidth = 1;
frame.getContentPane().add(btnHex2Bin, c);
JButton btnFirmwareUpdate = new JButton("Firmware Update");
// c.fill = GridBagConstraints.HORIZONTAL;
// c.ipady = 40; //make this component tall
// c.weightx = 0.0;
c.gridx = 2;
c.gridy = 2;
c.gridwidth = 1;
frame.getContentPane().add(btnFirmwareUpdate, c);
JButton btnFirmwareUpdateStop = new JButton("Firmware Update Stop");
//c.fill = GridBagConstraints.HORIZONTAL;
// c.ipady = 40; //make this component tall
//c.weightx = 0.0;
c.gridx = 3;
c.gridy = 2;
c.gridwidth = 1;
frame.getContentPane().add(btnFirmwareUpdateStop, c);
// row #3
JButton btnCheckSum = new JButton("Check Checksum");
c.fill = GridBagConstraints.HORIZONTAL;
// c.ipady = 40; //make this component tall
c.weightx = 0.0;
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 1;
frame.getContentPane().add(btnCheckSum, c);
JButton btnStartBootloader = new JButton("Start Bootloader");
c.fill = GridBagConstraints.HORIZONTAL;
// c.ipady = 40; //make this component tall
c.weightx = 0.0;
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 1;
frame.getContentPane().add(btnStartBootloader, c);
JButton btnStartApplication = new JButton("Start Application");
c.fill = GridBagConstraints.HORIZONTAL;
// c.ipady = 40; //make this component tall
c.weightx = 0.0;
c.gridx = 2;
c.gridy = 3;
c.gridwidth = 1;
frame.getContentPane().add(btnStartApplication, c);
JTextArea txtFileContent = new JTextArea(30,68);
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0; //reset to default
c.weighty = 1.0; //request any extra vertical space
c.anchor = GridBagConstraints.PAGE_START; //bottom of space
c.insets = new Insets(10,0,0,0); //top padding
c.gridx = 0; //aligned with button 2
c.gridy = 4; //third row
c.gridwidth = 4; //4 columns wide
frame.getContentPane().add(txtFileContent, c);
//txtFileContent.setVisible(false);
////////////// JScrollPane scrollPane = new JScrollPane(txtFileContent);
/////////////// scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
// middlePanel.add(scrollPane);
// scrollPane.setBounds(10,60,780,500);
//scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
////////////////// frame.getContentPane().add(scrollPane);
txtFileContent.setLineWrap(true);
txtFileContent.setWrapStyleWord(true);
JScrollPane scrolltxt = new JScrollPane();
scrolltxt.setViewportView(txtFileContent);
scrolltxt.setWheelScrollingEnabled(true);
frame.getContentPane().add(scrolltxt, c);
frame.setIconImage(new ImageIcon(getClass().getResource("/resources/fwup.png")).getImage());
frame.setTitle("Firmware Update");
//frame.setSize(600,800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Try This
JTextArea txtFileContent = new JTextArea(30,68);
JScrollPane scroll = new JScrollPane(txtFileContent);
frame.add(scroll);
I'm not too sure if this will solve your problem, but have you considered that not setting any column widths or heights in your layout may be your concern (line 30 of the code)? Allow me to give you an example:
GridBagLayout layout=new GridBagLayout();
GridBagConstraints gbc=new GridBagConstraints();
layout.columnWidths=new int[] {198, 198};
layout.rowHeights=new int[] {70};
panel.setLayout(layout);
Wherein, panel is a panel that is pushed onto the JFrame.
NB: I am personally against using the built-in content pane of a JFrame, because of its tendancies to default out on the user; however, for all intents and purposes, it shouldn't be a problem if done right.
I hope this helps, and best of luck!
When I tested your code, the scroll bar for the JTextArea shows up as expected when you exceed the row count of the initial JTextArea (The default value for the scrollbars' visibility are only to be shown when needed: JScrollPane API under verticalScrollBarPolicy and horizontalScrollBarPolicy). If you are asking to have it default as visible, then use either setVerticalScrollBarPolicy(...) or setHorizontalScrollBarPolicy(...) on your JScrollPane variable. There are several options available for ScrollPaneConstants

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);

Why is the middle column not showing up?

I am making a simple calculator GUI in Java to start to learn how to use Java. The following code is not working. Only the first column is appearing. Where is the second and third column going?
package Start;
import java.awt.*;
import javax.swing.*;
public class CalculatorGUI {
public static void addComponentsToPane(Container pane) {
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
JLabel label;
JButton button;
label = new JLabel("I'm a calculator");
c.gridwidth = GridBagConstraints.REMAINDER;
c.weightx = 0.0;
c.gridx = 0;
c.gridy = 0;
pane.add(label, c);
button = new JButton("1");
c.gridx = 0;
c.gridy = 1;
pane.add(button, c);
button = new JButton("2");
c.gridx = 1;
c.gridy = 1;
pane.add(button, c);
button = new JButton("3");
c.gridx = 2;
c.gridy = 1;
pane.add(button, c);
button = new JButton("4");
c.gridx = 0;
c.gridy = 2;
pane.add(button, c);
button = new JButton("5");
c.gridx = 1;
c.gridy = 2;
pane.add(button, c);
button = new JButton("6");
c.gridx = 2;
c.gridy = 2;
pane.add(button, c);
button = new JButton("7");
c.gridx = 0;
c.gridy = 3;
pane.add(button, c);
button = new JButton("8");
c.gridx = 1;
c.gridy = 3;
pane.add(button, c);
button = new JButton("9");
c.gridx = 2;
c.gridy = 3;
pane.add(button, c);
}
public static void createAndShowGUI() {
JFrame frame = new JFrame("CalculatorGUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
i tried making the label just say c.gridwidth = 3; but that does the same thing. When i make the width just equal 1 all the buttons appear, but the label is in only in one cell. How do i make the label span 3 columns? Without making the other buttons disappear.
How do i make the label span 3 columns without gridwidth?
c.gridwidth = 3;
You will then need to reset it to 1 before adding other components.
so that it is centered over the '2' button
You will also need to set the text alignment of the label:
label.setHorizontalAlignment(JLabel.CENTER);
You're using
c.gridwidth = GridBagConstraints.REMAINDER;
Which Specifies that the current component is the last component in its column or row.
So comment this line out, and it should work just fine.
Reaf more About GridBagLayout.

Categories