I am relatively new to Java and I am making an app that helps me estimate construction costs. I built the backend for it, but the buttons and text fields were all in one row, making the app so wide it didn't fit in my screen. I am now trying to use a 3x6 grid bag layout to organize the components like this:
Title
question1 *answer*
question2 *answer*
question3 *answer*
question4 *answer*
--Calculate--
Estimate: $***
When I run the program, I am given an "illegal component position"
error (pasted at the bottom) and nothing pops up anymore since
I started adding in the grid constraints. The problem is not with the JButton or its action listener. Here is the code, sorry for
the lack of comments:
import java.util.*;
import packagepackage.HintTextFieldUI;
import java.awt.*;
import java.awt.event.*;
import java.security.PublicKey;
import javax.swing.*;
import javax.swing.text.JTextComponent;
public class CP_GUI extends JFrame {
public JLabel tLabel;
public JTextField linear;
public JLabel liLabel;
public JComboBox<String> sump;
public JLabel suLabel;
public JComboBox<String> elec;
public JLabel elLabel;
public JTextField prep;
public JLabel prLabel;
public JTextField estimate;
public JLabel esLabel;
public CP_GUI() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(200, 200, 100, 100));
GridBagConstraints c = new GridBagConstraints();
String title = "Drain Tile Calculator";
tLabel = new JLabel(title);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.ipady = 40;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 0;
panel.add(tLabel, c);
frame.setTitle(title);
liLabel = new JLabel("Basement Perimeter Length");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
panel.add(liLabel, c);
linear = new JTextField(10);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
panel.add(linear, c);
prLabel = new JLabel("Time needed to prepare site:");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 2;
c.gridy = 0;
panel.add(prLabel, c);
prep = new JTextField(10);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 2;
c.gridy = 2;
panel.add(prep, c);
suLabel = new JLabel("Using:");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 3;
c.gridy = 0;
panel.add(suLabel, c);
String[] sumpo = {"New sump pump","Existing sump pump"};
sump = new JComboBox<>(sumpo);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 3;
c.gridy = 2;
panel.add(sump, c);
elLabel = new JLabel("Location of electrical outlet:");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 4;
c.gridy = 0;
panel.add(elLabel, c);
String[] electo = {"There is no outlet within 6 feet of the sump pump","There is an outlet nearby, or I do not need a new pump"};
elec = new JComboBox<>(electo);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 4;
c.gridy = 2;
panel.add(elec, c);
estimate = new JTextField(10);
JButton calculate = new JButton("Calculate");
calculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event){
// TODO Auto-generated method stub
Integer linVar = Integer.parseInt(linear.getText());
linVar *= 13;
Object sumps = sump.getSelectedItem();
Integer sumpVar = 0;
if("New sump pump".equals(sumps)) {
sumpVar += 260;}
Object elecs = elec.getSelectedItem();
Integer elecsVar = 0;
if("There is no outlet within 6 feet of the sump pump".equals(elecs)) {
elecsVar += 280;}
Integer prepsVar = Integer.parseInt(prep.getText());
prepsVar += 30;
prepsVar *= 235;
prepsVar /= 100;
linVar += sumpVar += elecsVar += prepsVar;
/* overhead*/
linVar += 2428;
/* tax */
linVar *= 11;
linVar /= 10;
/* margin */
linVar *= 12;
linVar /= 10;
String toWords = String.valueOf(linVar);
estimate.setUI(new HintTextFieldUI(toWords, true));
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40;
c.weightx = 0.5;
c.gridwidth = 3;
c.gridx = 5;
c.gridy = 0;
panel.add(calculate, c);
esLabel = new JLabel("Estimated Cost:");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridwidth = 2;
c.gridx = 6;
c.gridy = 0;
panel.add(esLabel, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 6;
c.gridy = 2;
panel.add(estimate, c);
frame.add(panel, GridBagConstraints.CENTER);
frame.pack();
frame.setVisible(true);
linear.setUI(new HintTextFieldUI("Perimeter length", true));
prep.setUI(new HintTextFieldUI("Minutes of preptime", true));
}
public static void main(String[] args) {
new CP_GUI();
}
}
I suspect the issue might either have to with the fact that the size
of the grid itself (3x6) is never defined, or with the frame's layout
not being properly set to grid bags layout.
Error:
Exception in thread "main" java.lang.IllegalArgumentException: illegal component position
at java.desktop/java.awt.Container.addImpl(Container.java:1115)
at java.desktop/java.awt.Container.add(Container.java:1033)
at java.desktop/javax.swing.JFrame.addImpl(JFrame.java:554)
at java.desktop/java.awt.Container.add(Container.java:493)
at craftsmanPeak/packagepackage.CP_GUI.<init>(CP_GUI.java:163)
at craftsmanPeak/packagepackage.CP_GUI.main(CP_GUI.java:173)
Thanks so much in advance! I really appreciate it!
frame.add(panel, GridBagConstraints.CENTER); JFrame uses a BorderLayout by default, get rid of the GridBagConstraints.CENTER
I've also cleaned up you layout (trust me (said some stranger on the internet 🤣), it was a mess)
You're messing up your x and y positions
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public JLabel tLabel;
public JTextField linear;
public JLabel liLabel;
public JComboBox<String> sump;
public JLabel suLabel;
public JComboBox<String> elec;
public JLabel elLabel;
public JTextField prep;
public JLabel prLabel;
public JTextField estimate;
public JLabel esLabel;
public TestPane() {
setLayout(new GridBagLayout());
setBorder(BorderFactory.createEmptyBorder(16, 16, 16, 16));
GridBagConstraints c = new GridBagConstraints();
String title = "Drain Tile Calculator";
tLabel = new JLabel(title, JLabel.CENTER);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.ipady = 40;
c.gridwidth = GridBagConstraints.REMAINDER;
c.anchor = GridBagConstraints.CENTER;
c.gridx = 0;
c.gridy = 0;
add(tLabel, c);
c = new GridBagConstraints();
c.anchor = GridBagConstraints.LINE_END;
c.gridy = 1;
c.gridx = 0;
liLabel = new JLabel("Basement Perimeter Length:");
prLabel = new JLabel("Time needed to prepare site:");
suLabel = new JLabel("Using:");
elLabel = new JLabel("Location of electrical outlet:");
add(liLabel, c);
c.gridy++;
add(prLabel, c);
c.gridy++;
add(suLabel, c);
c.gridy++;
add(elLabel, c);
linear = new JTextField(10);
prep = new JTextField(10);
String[] sumpo = {"New sump pump", "Existing sump pump"};
sump = new JComboBox<>(sumpo);
String[] electo = {"There is no outlet within 6 feet of the sump pump", "There is an outlet nearby, or I do not need a new pump"};
elec = new JComboBox<>(electo);
c.anchor = GridBagConstraints.LINE_START;
c.gridx++;
c.gridy = 1;
add(linear, c);
c.gridy++;
add(prep, c);
c.gridy++;
add(sump, c);
c.gridy++;
add(elec, c);
JButton calculate = new JButton("Calculate");
//// calculate.addActionListener(new ActionListener() {
//// public void actionPerformed(ActionEvent event) {
//// // TODO Auto-generated method stub
//// Integer linVar = Integer.parseInt(linear.getText());
//// linVar *= 13;
////
//// Object sumps = sump.getSelectedItem();
//// Integer sumpVar = 0;
//// if ("New sump pump".equals(sumps)) {
//// sumpVar += 260;
//// }
////
//// Object elecs = elec.getSelectedItem();
//// Integer elecsVar = 0;
//// if ("There is no outlet within 6 feet of the sump pump".equals(elecs)) {
//// elecsVar += 280;
//// }
////
//// Integer prepsVar = Integer.parseInt(prep.getText());
//// prepsVar += 30;
//// prepsVar *= 235;
//// prepsVar /= 100;
////
//// linVar += sumpVar += elecsVar += prepsVar;
//// /* overhead*/
//// linVar += 2428;
//// /* tax */
//// linVar *= 11;
//// linVar /= 10;
//// /* margin */
//// linVar *= 12;
//// linVar /= 10;
//// String toWords = String.valueOf(linVar);
////
//// estimate.setUI(new HintTextFieldUI(toWords, true));
//// }
////
//// });
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10, 0, 10, 0);
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridx = 0;
c.gridy = 5;
add(calculate, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 6;
c.anchor = GridBagConstraints.LINE_END;
esLabel = new JLabel("Estimated Cost:");
estimate = new JTextField(10);
add(esLabel, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
add(estimate, c);
// linear.setUI(new HintTextFieldUI("Perimeter length", true));
// prep.setUI(new HintTextFieldUI("Minutes of preptime", true));
}
}
}
Related
I am using the gridbag layout to create my first application in Java. My code is completed and is located in another class. The problem I am having is being able to control buttons. I have the Jtextfield that outputs text on very first row to the bottom right. I want that Jtextfield to take 3 of the 4 spaces but its only taking the space in the end only. I want to be able to show entry spanning from from 3 of the cells in the top. I reserved one cell to reserve an image of the operator. Also, I set up some text constraints so that it doesn't resize the whole right hand size as output is being shown. But I wanted to keep the right hand side even. Can anyone tell me what I am doing wrong?
public class MyFrame extends JFrame{
static JLabel display;
static JLabel displayOperator;
public static String entry;
public static String repeatEntry;
public static String repeatEntry2;
public static String num1 = "";
public static String num2 = "";
public static String total = "";
public static String operator = "";
// public values for buttons
public JButton zero;
public JButton one;
public JButton two;
public JButton three;
public JButton four;
public JButton five;
public JButton six;
public JButton seven;
public JButton eight;
public JButton nine;
public JButton equal;
public JButton divide;
public JButton multiply;
public JButton minus;
public JButton plus;
public JButton clear;
public JButton negative;
public JButton decimal;
//attributes for bag layout
final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;
public MyFrame() {
super();
init();
//added strings to constructor frame
}
private void init() {
// creating a grid bag layout
/* FYI
* weight x and weight y refer to the space taking in the frame or space it takes
* grid x and y refers to location of button
* constraints sets limits to avoid things stretching out too much
*/
this.setLayout(new GridBagLayout());
this.setTitle("Calculator");
GridBagConstraints c = new GridBagConstraints();
if (shouldFill) {
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
}
//all output will shown in this JLabel
display = new JLabel("",SwingConstants.RIGHT); //aligns right
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 3;
c.weighty = 1;
c.gridx = 3;
c.gridy = 0;
this.add(display, c);
// this will display an indicator that show the operator currently in use
displayOperator = new JLabel("",SwingConstants.LEFT); //aligns LEFT
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0;
c.weighty = 0;
c.gridx = 0;
c.gridy = 0;
this.add(displayOperator, c);
display.setFont(new Font("Times Roman", Font.PLAIN, 20));
FontMetrics fm = display.getFontMetrics(display.getFont());
int w = fm.stringWidth("00000000"); //set display of numbers by these amount of digits to the text
int h = fm.getHeight();
Dimension size = new Dimension(w, h);
//locks perspective so that JBagged buttons are not autoresized
display.setMinimumSize(size);
display.setPreferredSize(size);
// all input buttons with Button Listeners assigned to them
JButton seven = new JButton("7");
this.add(seven);
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 4;
c.weightx = 1;
c.weighty = 1;
this.add(seven, c);
seven.addActionListener(new MyButtonListener(this));
JButton eight = new JButton("8");
this.add(eight);
c.fill = GridBagConstraints.BOTH;
c.gridx = 1;
c.gridy = 4;
c.weightx = 1;
c.weighty = 1;
this.add(eight, c);
eight.addActionListener(new MyButtonListener(this));
JButton nine = new JButton("9");
this.add(nine);
c.fill = GridBagConstraints.BOTH;
c.gridx = 2;
c.gridy = 4;
c.weightx = 1;
c.weighty = 1;
this.add(nine, c);
nine.addActionListener(new MyButtonListener(this));
JButton divide = new JButton("/");
this.add(divide);
c.fill = GridBagConstraints.BOTH;
c.gridx = 3;
c.gridy = 4;
c.weightx = .75;
c.weighty = .75;
this.add(divide, c);
divide.addActionListener(new MyButtonListener(this));
JButton four = new JButton("4");
this.add(four);
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 5;
c.weightx = 1;
c.weighty = 1;
this.add(four, c);
four.addActionListener(new MyButtonListener(this));
JButton five = new JButton("5");
this.add(five);
c.fill = GridBagConstraints.BOTH;
c.gridx = 1;
c.gridy = 5;
c.weightx = 1;
c.weighty = 1;
this.add(five, c);
five.addActionListener(new MyButtonListener(this));
JButton six = new JButton("6");
this.add(six);
c.fill = GridBagConstraints.BOTH;
c.gridx = 2;
c.gridy = 5;
c.weightx = 1;
c.weighty = 1;
this.add(six, c);
six.addActionListener(new MyButtonListener(this));
JButton multiply = new JButton("*");
this.add(multiply);
c.fill = GridBagConstraints.BOTH;
c.gridx = 3;
c.gridy = 5;
c.weightx = 1;
c.weighty = 1;
this.add(multiply, c);
multiply.addActionListener(new MyButtonListener(this));
JButton one = new JButton("1");
this.add(one);
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 6;
c.weightx = 1;
c.weighty = 1;
this.add(one, c);
one.addActionListener(new MyButtonListener(this));
JButton two = new JButton("2");
this.add(two);
c.fill = GridBagConstraints.BOTH;
c.gridx = 1;
c.gridy = 6;
c.weightx = 1;
c.weighty = 1;
this.add(two, c);
two.addActionListener(new MyButtonListener(this));
JButton three = new JButton("3");
this.add(three);
c.fill = GridBagConstraints.BOTH;
c.gridx = 2;
c.gridy = 6;
c.weightx = 1;
c.weighty = 1;
this.add(three, c);
three.addActionListener(new MyButtonListener(this));
JButton minus = new JButton("-");
this.add(minus);
c.fill = GridBagConstraints.BOTH;
c.gridx = 3;
c.gridy = 6;
c.weightx = 1;
c.weighty = 1;
this.add(minus, c);
minus.addActionListener(new MyButtonListener(this));
JButton zero = new JButton("0");
this.add(zero);
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 7;
c.weightx = 1;
c.weighty = 1;
this.add(zero, c);
zero.addActionListener(new MyButtonListener(this));
JButton decimal = new JButton(".");
this.add(decimal);
c.fill = GridBagConstraints.BOTH;
c.gridx = 1;
c.gridy = 7;
c.weightx = 1;
c.weighty = 1;
this.add(decimal, c);
decimal.addActionListener(new MyButtonListener(this));
JButton equal = new JButton("=");
this.add(equal);
c.fill = GridBagConstraints.BOTH;
c.gridx = 2;
c.gridy = 7;
c.weightx = 1;
c.weighty = 1;
this.add(equal, c);
equal.addActionListener(new MyButtonListener(this));
JButton plus = new JButton("+");
this.add(plus);
c.fill = GridBagConstraints.BOTH;
c.gridx = 3;
c.gridy = 7;
c.weightx = 1;
c.weighty = 1;
this.add(plus, c);
plus.addActionListener(new MyButtonListener(this));
JButton clear = new JButton("C");
this.add(clear);
c.fill = GridBagConstraints.BOTH;
c.gridx = 1;
c.gridy = 8;
c.weightx = 1;
c.weighty = 1;
this.add(clear, c);
clear.addActionListener(new MyButtonListener(this));
JButton negative = new JButton("+/-");
this.add(negative);
c.fill = GridBagConstraints.BOTH;
c.gridx = 2;
c.gridy = 8;
c.weightx = 1;
c.weighty = 1;
this.add(negative, c);
negative.addActionListener(new MyButtonListener(this));
JButton percentage = new JButton("%");
this.add(percentage);
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 8;
c.weightx = 1;
c.weighty = 1;
this.add(percentage, c);
percentage.addActionListener(new MyButtonListener(this));
// sets dimensions for window and locks resizing
this.setPreferredSize(new Dimension(400,500));
this.setMaximumSize(new Dimension(400,500));
this.setMinimumSize(new Dimension(400,500));
this.pack();
}
}
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.
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();
}
}
I have never used layouts before and from what I understand GridBagLayout is probably not the easiest layout to start on, however I am trying to use it anyway. I am trying to use the GridBagLayout for my JPanel so that when I re-size it the components grow. I only need it to keep the natural height of the components but I am trying to use GridBagConstraints.HORIZONTAL to make the width of a component re-size automatically. I have the code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.font.*;
import java.io.*;
public class NumberConverterDesignTest
{
JFrame numberConversionWindow = new JFrame("Number Conversion");
JPanel numberPanel = new JPanel();
////////COMPONENTS////////
JLabel lblTitle;
JLabel lblBase2;
JLabel lblBase8;
JLabel lblBase10;
JLabel lblBase16;
JTextField txtBase2;
JTextField txtBase8;
JTextField txtBase10;
JTextField txtBase16;
///////////Font///////////
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String []fontFamilies = ge.getAvailableFontFamilyNames();
Font FontT5 = new Font("SansSerif", Font.BOLD, 45);
public void numberConvertGUI()
{
numberConversionWindow.setBounds(10, 10, 420, 300);
numberConversionWindow.setMinimumSize(new Dimension(420, 300));
numberConversionWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
numberConversionWindow.setLayout(new GridLayout(1,1));
createNumberConversionPanel();
numberConversionWindow.getContentPane().add(numberPanel);
numberConversionWindow.setVisible(true);
}
public void createNumberConversionPanel()
{
numberPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
lblTitle = new JLabel();
c.weightx = 0.5;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
lblTitle.setText("Number Converter");
lblTitle.setHorizontalAlignment(JLabel.CENTER);
lblTitle.setFont(FontT5);
numberPanel.add(lblTitle, c);
lblBase2 = new JLabel();
c.weightx = 0.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
lblBase2.setText("Binary: ");
lblBase2.setHorizontalAlignment(JLabel.RIGHT);
numberPanel.add(lblBase2);
lblBase8 = new JLabel();
//c.weightx = 0.5;
c.weighty = 1.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 2;
lblBase8.setText("Octal: ");
lblBase8.setHorizontalAlignment(JLabel.RIGHT);
numberPanel.add(lblBase8);
lblBase10 = new JLabel();
c.weightx = 0.5;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 3;
lblBase10.setText("Decimal: ");
lblBase10.setHorizontalAlignment(JLabel.RIGHT);
numberPanel.add(lblBase10);
lblBase16 = new JLabel();
c.weightx = 0.5;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 4;
lblBase16.setText("Hexadecimal: ");
lblBase16.setHorizontalAlignment(JLabel.RIGHT);
numberPanel.add(lblBase16);
txtBase2 = new JTextField();
c.weightx = 0.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 1;
txtBase2.setText("");
numberPanel.add(txtBase2);
txtBase8 = new JTextField();
//c.weightx = 0.5;
c.weighty = 1.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 2;
txtBase8.setText("");
numberPanel.add(txtBase8);
txtBase10 = new JTextField();
c.weightx = 0.5;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 3;
txtBase10.setText("");
numberPanel.add(txtBase10);
txtBase16 = new JTextField();
c.weightx = 0.5;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 4;
txtBase16.setText("");
numberPanel.add(txtBase16);
}
public static void main(String[] args)
{
NumberConverterDesignTest nC = new NumberConverterDesignTest();
nC.numberConvertGUI();
}
}
and when this is compiled I get
My aim is to try and get
I believe the problem to be what I have set weightx to be, however I am not sure what to set it to, to get the result that I would like. Any help would be greatly appreciated
You need to pass the updated constraint each time you call the numberPanel.add method.
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