Cannot Complete Class Body - java

I have counted the curly braces and cannot figure out why the class body is incomplete.
Everytime I try to fix the class it messes the whole class up.
The problem is the very last class in the code. The very last curly brace is the one giving me trouble with the class. I'm using Eclipse to write this in.
Here is the code for the whole program:
import java.awt.BorderLayout;
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.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Stocks {
public static void main(String [] args) {
JFrame frame = new JFrame ("Java Stocks");
frame.setSize(700,700);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel (new GridBagLayout());
frame.add(panel);
frame.getContentPane().add(panel, BorderLayout.WEST);
GridBagConstraints c = new GridBagConstraints ();
JButton button1 = new JButton("Profile");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(40, 40, 40, 40);
panel.add(button1, c);
button1.addActionListener(new Action());
}
static class Action implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame2 = new JFrame("Your Stocks");
frame2.setVisible(true);
frame2.setSize(600,600);
JLabel label = new JLabel("Your Personal Stocks");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label);
}
public static void main(String [] args) {
GridBagConstraints c = new GridBagConstraints ();
JButton button2 = new JButton("Market");
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(40, 40, 40, 40);
button2.addActionListener(new Action());
}
static class Action2 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame2 = new JFrame("Your Stocks");
frame2.setVisible(true);
frame2.setSize(600,600);
JLabel label = new JLabel("Your Personal Stocks");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label);
}
public static void main(String [] args) {
GridBagConstraints c = new GridBagConstraints ();
JButton button3 = new JButton("Users");
c.gridx = 0;
c.gridy = 2;
c.insets = new Insets(40, 40, 40, 40);
button3.addActionListener(new Action());
}
static class Action3 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame2 = new JFrame("Your Stocks");
frame2.setVisible(true);
frame2.setSize(600,600);
JLabel label = new JLabel("Your Personal Stocks");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label);
}
public static void main(String [] args) {
GridBagConstraints c = new GridBagConstraints ();
JButton button4 = new JButton("Notes");
c.gridx = 0;
c.gridy = 3;
c.insets = new Insets(40, 40, 40, 40);
button4.addActionListener(new Action());
}
static class Action4 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame2 = new JFrame("Your Stocks");
frame2.setVisible(true);
frame2.setSize(600,600);
JLabel label = new JLabel("Your Personal Stocks");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label);
}
public static void main(String [] args) {
GridBagConstraints c = new GridBagConstraints ();
JButton button5 = new JButton("Information");
c.gridx = 0;
c.gridy = 4;
c.insets = new Insets(40, 40, 40, 40);
button5.addActionListener(new Action());
}
static class Action5 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame2 = new JFrame("Your Stocks");
frame2.setVisible(true);
frame2.setSize(600,600);
JLabel label = new JLabel("Your Personal Stocks");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label);
}

Due to confusing indentation, it is not obvious that you are nesting your nested classes inside each other. Action5 is nested in Action4, which is nested in Action3, which is nested in Action2, which is nested in Action, which is nested in Stocks.
Either place 5 braces at the very end of the file, to close all your classes, or even better, nest them all directly in Stocks, not within each other.

Try to use crlt+shift + f to format your code

When you clean this up, your code should look like something like this:
import java.awt.BorderLayout;
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.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
class Action implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame2 = new JFrame("Your Stocks");
frame2.setVisible(true);
frame2.setSize(600,600);
JLabel label = new JLabel("Your Personal Stocks");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label);
}
}
public class Stocks {
public static void main(String [] args) {
JFrame frame = new JFrame ("Java Stocks");
frame.setSize(700,700);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel (new GridBagLayout());
frame.add(panel);
frame.getContentPane().add(panel, BorderLayout.WEST);
GridBagConstraints c = new GridBagConstraints ();
JButton button1 = new JButton("Profile");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(40, 40, 40, 40);
panel.add(button1, c);
button1.addActionListener(new Action());
}
}
My advice #1: first learn to code with keyboard, not mouse.
My advice #2: if you aren't sure what static modifier is for and what are the implications, don't use it.

Related

My content pane show only white even if it has components on it

I'm doing this as a challenge for myself. My problem is that when I click on the button, the content pane appears plain even if the JPanel has components in it.
I've tried adding the components on the frame but I get an error: >Cannot read field "parent" because "comp" is null.
I've tried other layout on JFrame and JPanel and still it didn't show.
Here's the full code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
public class test implements ActionListener{
public static void main(String [] args) {
new test();
}
static JPanel mainPanel, cubePanel;
static JFrame frame;
static Container container = new Container();
static JLabel calculatorFor;
static JButton sphereButton, rightCylinderButton, rightConeButton, rectangularPrismButton, triangularPrismButton,
cubeButton, squarePyramidButton, rectangularPyramidButton, ellipsoidButton, tetrahedronButton ,backToPreviousFrameButton;
static Font font = new Font(null, Font.PLAIN, 30);
static JLabel enterValueForEdge;
static JTextField edgeTextField;
static JTextArea surfaceAreaTextArea, surfaceAreaFormulaTextArea, surfaceAreaSolutionTextArea;
static JButton calculateButton;
static double edge;
static DecimalFormat surfaceAreaDecimal;
public test(){
frame = new JFrame("Calculating for Surface Area");
calculatorFor = new JLabel("Calculator for the Surface Area of:");
calculatorFor.setSize(600, 40);
calculatorFor.setLocation(100, 50);
calculatorFor.setFont(font);
calculatorFor.setFocusable(false);
sphereButton = new JButton("Sphere ");
sphereButton.setSize(400, 40);
sphereButton.setLocation(100, 100);
sphereButton.setFont(font);
sphereButton.addActionListener(this);
sphereButton.setFocusable(false);
rightCylinderButton = new JButton("Right Cylinder");
rightCylinderButton.setSize(400, 40);
rightCylinderButton.setLocation(100, 150);
rightCylinderButton.setFont(font);
rightCylinderButton.addActionListener(this);
rightCylinderButton.setFocusable(false);
rightConeButton = new JButton("Right Cone");
rightConeButton.setSize(400, 40);
rightConeButton.setLocation(100, 200);
rightConeButton.setFont(font);
rightConeButton.addActionListener(this);
rightConeButton.setFocusable(false);
rectangularPrismButton = new JButton("Rectangular Prism");
rectangularPrismButton.setSize(400, 40);
rectangularPrismButton.setLocation(100, 250);
rectangularPrismButton.setFont(font);
rectangularPrismButton.addActionListener(this);
rectangularPrismButton.setFocusable(false);
triangularPrismButton = new JButton("Triangular Prism");
triangularPrismButton.setSize(400, 40);
triangularPrismButton.setLocation(100, 300);
triangularPrismButton.setFont(font);
triangularPrismButton.addActionListener(this);
triangularPrismButton.setFocusable(false);
cubeButton = new JButton("Cube");
cubeButton.setSize(400, 40);
cubeButton.setLocation(100, 350);
cubeButton.setFont(font);
cubeButton.addActionListener(this);
cubeButton.setFocusable(false);
squarePyramidButton = new JButton("Square Pyramid");
squarePyramidButton.setSize(400, 40);
squarePyramidButton.setLocation(100, 400);
squarePyramidButton.setFont(font);
squarePyramidButton.addActionListener(this);
squarePyramidButton.setFocusable(false);
rectangularPyramidButton = new JButton("Rectangular Pyramid");
rectangularPyramidButton.setSize(400, 40);
rectangularPyramidButton.setLocation(100, 450);
rectangularPyramidButton.setFont(font);
rectangularPyramidButton.addActionListener(this);
rectangularPyramidButton.setFocusable(false);
ellipsoidButton = new JButton("Ellipsoid");
ellipsoidButton.setSize(400, 40);
ellipsoidButton.setLocation(100, 500);
ellipsoidButton.setFont(font);
ellipsoidButton.addActionListener(this);
ellipsoidButton.setFocusable(false);
tetrahedronButton = new JButton("Tetrahedron");
tetrahedronButton.setSize(400, 40);
tetrahedronButton.setLocation(100, 550);
tetrahedronButton.setFont(font);
tetrahedronButton.addActionListener(this);
tetrahedronButton.setFocusable(false);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
mainPanel = new JPanel();
mainPanel.setBounds(0, 0, 1080, 720);
mainPanel.setLayout(null);
mainPanel.setBackground(Color.decode("#FAF7FC"));
mainPanel.add(calculatorFor);
mainPanel.add(sphereButton);
mainPanel.add(rightCylinderButton);
mainPanel.add(rightConeButton);
mainPanel.add(rectangularPrismButton);
mainPanel.add(triangularPrismButton);
mainPanel.add(cubeButton);
mainPanel.add(squarePyramidButton);
mainPanel.add(rectangularPyramidButton);
mainPanel.add(ellipsoidButton);
mainPanel.add(tetrahedronButton);
mainPanel.add(backToPreviousFrameButton);
frame.getContentPane().add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.decode("#FAF7FC"));
frame.setLayout(new BorderLayout());
frame.setSize(1080,720);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public void cubePanel(){
enterValueForEdge = new JLabel("Enter Edge:");
enterValueForEdge.setSize(200, 40);
enterValueForEdge.setLocation(100, 50);
enterValueForEdge.setFont(font);
enterValueForEdge.setFocusable(false);
edgeTextField = new JTextField();
edgeTextField.setSize(400, 40);
edgeTextField.setLocation(300, 50);
edgeTextField.setFont(font);
calculateButton = new JButton("Calculate");
calculateButton.setSize(200, 40);
calculateButton.setLocation(100, 100);
calculateButton.setFont(font);
calculateButton.addActionListener(this);
calculateButton.setFocusable(false);
surfaceAreaFormulaTextArea = new JTextArea("SA = 6a²");
surfaceAreaFormulaTextArea.setSize(400, 40);
surfaceAreaFormulaTextArea.setLocation(100, 150);
surfaceAreaFormulaTextArea.setFont(font);
surfaceAreaFormulaTextArea.setEditable(false);
surfaceAreaTextArea = new JTextArea("SA: ");
surfaceAreaTextArea.setSize(500, 40);
surfaceAreaTextArea.setLocation(100, 200);
surfaceAreaTextArea.setFont(font);
surfaceAreaTextArea.setEditable(false);
surfaceAreaSolutionTextArea = new JTextArea();
surfaceAreaSolutionTextArea.setSize(900, 80);
surfaceAreaSolutionTextArea.setLocation(100, 250);
surfaceAreaSolutionTextArea.setFont(font);
surfaceAreaSolutionTextArea.setEditable(false);
surfaceAreaSolutionTextArea.setLineWrap(true);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
cubePanel = new JPanel();
cubePanel.setBounds(0, 0, 1080, 720);
cubePanel.setLayout(null);
cubePanel.setBackground(Color.decode("#FAF7FC"));
container = new Container();
cubePanel.add(enterValueForEdge);
cubePanel.add(edgeTextField);
cubePanel.add(calculateButton);
cubePanel.add(surfaceAreaFormulaTextArea);
cubePanel.add(surfaceAreaTextArea);
cubePanel.add(surfaceAreaSolutionTextArea);
cubePanel.add(backToPreviousFrameButton);
container.add(cubePanel);
container.setLayout(null);
container.setBackground(Color.decode("#FAF7FH"));
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == sphereButton){
new sphereFrame();
frame.dispose();
}
if(e.getSource() == rightCylinderButton){
new rightCylinderFrame();
frame.dispose();
}
if(e.getSource() == rightConeButton){
new rightConeFrame();
frame.dispose();
}
if(e.getSource() == rectangularPrismButton){
new rectangularPrismFrame();
frame.dispose();
}
if(e.getSource() == triangularPrismButton){
new triangularPrismFrame();
frame.dispose();
}
if(e.getSource() == cubeButton){
frame.getContentPane().removeAll();
frame.add(cubePanel);
frame.repaint();
frame.revalidate();
System.out.println("Remove");
frame.getContentPane().add(container);
}
}
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the Laying Out Components Within a Container section.
Here's the GUI I created.
Press the "Cube" button to bring up the page for the cube calculation.
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
The JFrame has a default BorderLayout and holds the main JPanel. The main JPanel uses a CardLayout to display the various calculation JPanels. Using a CardLayout is much easier than managing multiple JFrames and provides a nicer user experience.
I used Swing layout managers to position the Swing components on the various JPanels.
The start JPanel consists of two subordinate JPanels. The title JPanel uses a FlowLayout to display the title. The button JPanel uses a GridLayout to display the various calculation JButtons. You can create complex JPanels by nesting multiple simple JPanels.
The cube calculation JPanel was the only one you had in your code, so it was the only one I created. I made it a method, but you can create a separate class for each of the calculations. The cube calculation JPanel uses a GridBagLayout to create a form-like JPanel. I used lambda expressions to create the ActionListener for each of the JButtons, since they were so simple.
I made the start JPanel button ActionListener a separate class just to get the code away from the for loop that creates the JButtons.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class CardLayoutGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new CardLayoutGUI());
}
private CardLayout cardLayout;
private JTextField edgeTextField, surfaceAreaSolutionTextField;
private JPanel mainPanel;
#Override
public void run() {
JFrame frame = new JFrame("Calculating for Surface Area");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.mainPanel = createMainPanel();
frame.add(mainPanel, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
cardLayout = new CardLayout();
JPanel panel = new JPanel(cardLayout);
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
panel.add(createStartPanel(), "Start");
panel.add(createCubeCalculationPanel(), "Cube");
return panel;
}
private JPanel createStartPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
panel.add(createTitlePanel(), BorderLayout.NORTH);
panel.add(createButtonPanel(), BorderLayout.CENTER);
return panel;
}
private JPanel createTitlePanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font font = new Font(Font.DIALOG, Font.PLAIN, 36);
JLabel label = new JLabel("Calculator for the Surface Area of:");
label.setFont(font);
panel.add(label);
return panel;
}
private JPanel createButtonPanel() {
String[] text = { "Sphere", "Right Cylinder", "Right Cone",
"Rectangular Prism", "Triangular Prism", "Cube",
"Square Pyramid", "Rectangular Pyramid", "Ellipsoid",
"Tetrahedron" };
JPanel panel = new JPanel(new GridLayout(0, 3, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font font = new Font(null, Font.PLAIN, 24);
ButtonListener listener = new ButtonListener();
for (String s : text) {
JButton button = new JButton(s);
button.addActionListener(listener);
button.setFont(font);
panel.add(button);
}
return panel;
}
private JPanel createCubeCalculationPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font titleFont = new Font(null, Font.PLAIN, 32);
Font font = new Font(null, Font.PLAIN, 16);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(0, 5, 5, 5);
gbc.weighty = 1.0;
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy = 0;
JLabel label = new JLabel("SA = 6a²");
label.setFont(titleFont);
panel.add(label, gbc);
gbc.gridwidth = 1;
gbc.gridy++;
label = new JLabel("Edge:");
label.setFont(font);
panel.add(label, gbc);
gbc.gridx++;
edgeTextField = new JTextField(10);
edgeTextField.setFont(font);
panel.add(edgeTextField, gbc);
gbc.gridx = 0;
gbc.gridy++;
label = new JLabel("SA:");
label.setFont(font);
panel.add(label, gbc);
gbc.gridx++;
surfaceAreaSolutionTextField = new JTextField(10);
surfaceAreaSolutionTextField.setFont(font);
surfaceAreaSolutionTextField.setEditable(false);
panel.add(surfaceAreaSolutionTextField, gbc);
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy++;
JButton calculateButton = new JButton("Calculate");
calculateButton.addActionListener(event -> {
double edge = Double.valueOf(edgeTextField.getText());
double sa = 6.0 * edge * edge;
surfaceAreaSolutionTextField.setText(Double.toString(sa));
});
calculateButton.setFont(font);
panel.add(calculateButton, gbc);
gbc.gridy++;
JButton backButton = new JButton("Back");
backButton.addActionListener(event -> {
cardLayout.show(mainPanel, "Start");
});
backButton.setFont(font);
panel.add(backButton, gbc);
return panel;
}
public class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
JButton button = (JButton) event.getSource();
String text = button.getText();
cardLayout.show(mainPanel, text);
}
}
}
Try this :
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
public class Test2 implements ActionListener {
public static void main(String[] args) {
new Test2();
}
static JPanel mainPanel, cubePanel;
static JFrame frame;
static Container container = new Container();
static JLabel calculatorFor;
static JButton sphereButton, rightCylinderButton, rightConeButton, rectangularPrismButton, triangularPrismButton,
cubeButton, squarePyramidButton, rectangularPyramidButton, ellipsoidButton, tetrahedronButton, backToPreviousFrameButton;
static Font font = new Font(null, Font.PLAIN, 30);
static JLabel enterValueForEdge;
static JTextField edgeTextField;
static JTextArea surfaceAreaTextArea, surfaceAreaFormulaTextArea, surfaceAreaSolutionTextArea;
static JButton calculateButton;
static double edge;
static DecimalFormat surfaceAreaDecimal;
public Test2() {
frame = new JFrame("Calculating for Surface Area");
calculatorFor = new JLabel("Calculator for the Surface Area of:");
calculatorFor.setSize(600, 40);
calculatorFor.setLocation(100, 50);
calculatorFor.setFont(font);
calculatorFor.setFocusable(false);
sphereButton = new JButton("Sphere ");
sphereButton.setSize(400, 40);
sphereButton.setLocation(100, 100);
sphereButton.setFont(font);
sphereButton.addActionListener(this);
sphereButton.setFocusable(false);
rightCylinderButton = new JButton("Right Cylinder");
rightCylinderButton.setSize(400, 40);
rightCylinderButton.setLocation(100, 150);
rightCylinderButton.setFont(font);
rightCylinderButton.addActionListener(this);
rightCylinderButton.setFocusable(false);
rightConeButton = new JButton("Right Cone");
rightConeButton.setSize(400, 40);
rightConeButton.setLocation(100, 200);
rightConeButton.setFont(font);
rightConeButton.addActionListener(this);
rightConeButton.setFocusable(false);
rectangularPrismButton = new JButton("Rectangular Prism");
rectangularPrismButton.setSize(400, 40);
rectangularPrismButton.setLocation(100, 250);
rectangularPrismButton.setFont(font);
rectangularPrismButton.addActionListener(this);
rectangularPrismButton.setFocusable(false);
triangularPrismButton = new JButton("Triangular Prism");
triangularPrismButton.setSize(400, 40);
triangularPrismButton.setLocation(100, 300);
triangularPrismButton.setFont(font);
triangularPrismButton.addActionListener(this);
triangularPrismButton.setFocusable(false);
cubeButton = new JButton("Cube");
cubeButton.setSize(400, 40);
cubeButton.setLocation(100, 350);
cubeButton.setFont(font);
cubeButton.addActionListener(this);
cubeButton.setFocusable(false);
squarePyramidButton = new JButton("Square Pyramid");
squarePyramidButton.setSize(400, 40);
squarePyramidButton.setLocation(100, 400);
squarePyramidButton.setFont(font);
squarePyramidButton.addActionListener(this);
squarePyramidButton.setFocusable(false);
rectangularPyramidButton = new JButton("Rectangular Pyramid");
rectangularPyramidButton.setSize(400, 40);
rectangularPyramidButton.setLocation(100, 450);
rectangularPyramidButton.setFont(font);
rectangularPyramidButton.addActionListener(this);
rectangularPyramidButton.setFocusable(false);
ellipsoidButton = new JButton("Ellipsoid");
ellipsoidButton.setSize(400, 40);
ellipsoidButton.setLocation(100, 500);
ellipsoidButton.setFont(font);
ellipsoidButton.addActionListener(this);
ellipsoidButton.setFocusable(false);
tetrahedronButton = new JButton("Tetrahedron");
tetrahedronButton.setSize(400, 40);
tetrahedronButton.setLocation(100, 550);
tetrahedronButton.setFont(font);
tetrahedronButton.addActionListener(this);
tetrahedronButton.setFocusable(false);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
mainPanel = new JPanel();
mainPanel.setBounds(0, 0, 1080, 720);
mainPanel.setLayout(null);
mainPanel.setBackground(Color.decode("#FAF7FC"));
mainPanel.add(calculatorFor);
mainPanel.add(sphereButton);
mainPanel.add(rightCylinderButton);
mainPanel.add(rightConeButton);
mainPanel.add(rectangularPrismButton);
mainPanel.add(triangularPrismButton);
mainPanel.add(cubeButton);
mainPanel.add(squarePyramidButton);
mainPanel.add(rectangularPyramidButton);
mainPanel.add(ellipsoidButton);
mainPanel.add(tetrahedronButton);
mainPanel.add(backToPreviousFrameButton);
frame.getContentPane().add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.decode("#FAF7FC"));
frame.setLayout(new BorderLayout());
frame.setSize(1080, 720);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public Container cubePanel() {
enterValueForEdge = new JLabel("Enter Edge:");
enterValueForEdge.setSize(200, 40);
enterValueForEdge.setLocation(100, 50);
enterValueForEdge.setFont(font);
enterValueForEdge.setFocusable(false);
edgeTextField = new JTextField();
edgeTextField.setSize(400, 40);
edgeTextField.setLocation(300, 50);
edgeTextField.setFont(font);
calculateButton = new JButton("Calculate");
calculateButton.setSize(200, 40);
calculateButton.setLocation(100, 100);
calculateButton.setFont(font);
calculateButton.addActionListener(this);
calculateButton.setFocusable(false);
surfaceAreaFormulaTextArea = new JTextArea("SA = 6a²");
surfaceAreaFormulaTextArea.setSize(400, 40);
surfaceAreaFormulaTextArea.setLocation(100, 150);
surfaceAreaFormulaTextArea.setFont(font);
surfaceAreaFormulaTextArea.setEditable(false);
surfaceAreaTextArea = new JTextArea("SA: ");
surfaceAreaTextArea.setSize(500, 40);
surfaceAreaTextArea.setLocation(100, 200);
surfaceAreaTextArea.setFont(font);
surfaceAreaTextArea.setEditable(false);
surfaceAreaSolutionTextArea = new JTextArea();
surfaceAreaSolutionTextArea.setSize(900, 80);
surfaceAreaSolutionTextArea.setLocation(100, 250);
surfaceAreaSolutionTextArea.setFont(font);
surfaceAreaSolutionTextArea.setEditable(false);
surfaceAreaSolutionTextArea.setLineWrap(true);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
cubePanel = new JPanel();
cubePanel.setBounds(0, 0, 1080, 720);
cubePanel.setLayout(null);
cubePanel.setBackground(Color.decode("#FAF7FC"));
container = new Container();
cubePanel.add(enterValueForEdge);
cubePanel.add(edgeTextField);
cubePanel.add(calculateButton);
cubePanel.add(surfaceAreaFormulaTextArea);
cubePanel.add(surfaceAreaTextArea);
cubePanel.add(surfaceAreaSolutionTextArea);
cubePanel.add(backToPreviousFrameButton);
container.add(cubePanel);
container.setLayout(null);
container.setBackground(Color.getColor("#FAF7FH"));
return container;
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == sphereButton) {
new sphereFrame();
frame.dispose();
}
if (e.getSource() == rightCylinderButton) {
new rightCylinderFrame();
frame.dispose();
}
if (e.getSource() == rightConeButton) {
new rightConeFrame();
frame.dispose();
}
if (e.getSource() == rectangularPrismButton) {
new rectangularPrismFrame();
frame.dispose();
}
if (e.getSource() == triangularPrismButton) {
//new triangularPrismFrame();
frame.dispose();
}
if (e.getSource() == cubeButton) {
frame.getContentPane().removeAll();
frame.add(cubePanel());
frame.repaint();
frame.revalidate();
System.out.println("Remove");
frame.getContentPane().add(container);
}
}
}

Why can't I add buttons to my GridLayout JPanel?

I am trying to add 24 JButtons to the GridLayout of my JPanel buttonPanel, but when I run it, I see that no buttons are added. (At least, they are not visible!). I tried giving the buttonPanel a background color, and it
was visible.
Does anyone know what I'm doing wrong?
This is my code (there is an other class):
package com.Egg;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class NormalCalc implements ActionListener {
static JPanel normalCalcPanel = new JPanel();
JPanel buttonPanel = new JPanel(new GridLayout(6,4,10,10));
Font font = new Font("Monospaced Bold", Font.BOLD, 18);
JButton powB = new JButton("^");
JButton sqrtB = new JButton("sqrt(");
JButton hOpenB = new JButton("(");
JButton hCloseB = new JButton(")");
JButton delB = new JButton("DEL");
JButton acB = new JButton("AC");
JButton mulB = new JButton("*");
JButton divB = new JButton("/");
JButton addB = new JButton("+");
JButton minB = new JButton("-");
JButton decB = new JButton(".");
JButton equB = new JButton("=");
JButton negB = new JButton("(-)");
JButton[] numberButtons = new JButton[10];
JButton[] functionButtons = new JButton[13];
public NormalCalc() {
functionButtons[0] = powB;
functionButtons[1] = delB;
functionButtons[2] = acB;
functionButtons[3] = sqrtB;
functionButtons[4] = mulB;
functionButtons[5] = divB;
functionButtons[6] = hOpenB;
functionButtons[7] = addB;
functionButtons[8] = minB;
functionButtons[9] = hCloseB;
functionButtons[10] = decB;
functionButtons[11] = negB;
functionButtons[12] = equB;
for (int i=0; i<10; i++) {
numberButtons[i] = new JButton(String.valueOf(i));
numberButtons[i].setFocusable(false);
numberButtons[i].setFont(font);
numberButtons[i].addActionListener(this);
}
for (int i=0; i <13; i++) {
functionButtons[i].setFocusable(false);
functionButtons[i].setFont(font);
functionButtons[i].addActionListener(this);
}
normalCalcPanel.setBounds(0, 0, 500, 700);
buttonPanel.setBounds(50, 200, 400, 400);
// Adding the buttons;
buttonPanel.add(functionButtons[0]);
buttonPanel.add(numberButtons[7]);
buttonPanel.add(numberButtons[8]);
buttonPanel.add(numberButtons[9]);
buttonPanel.add(functionButtons[1]);
buttonPanel.add(functionButtons[2]);
buttonPanel.add(functionButtons[3]);
buttonPanel.add(numberButtons[4]);
buttonPanel.add(numberButtons[5]);
buttonPanel.add(numberButtons[6]);
buttonPanel.add(functionButtons[4]);
buttonPanel.add(functionButtons[5]);
buttonPanel.add(functionButtons[6]);
buttonPanel.add(numberButtons[1]);
buttonPanel.add(numberButtons[2]);
buttonPanel.add(numberButtons[3]);
buttonPanel.add(functionButtons[7]);
buttonPanel.add(functionButtons[8]);
buttonPanel.add(functionButtons[9]);
buttonPanel.add(numberButtons[0]);
buttonPanel.add(functionButtons[10]);
buttonPanel.add(functionButtons[11]);
buttonPanel.add(functionButtons[12]);
buttonPanel.repaint();
normalCalcPanel.add(buttonPanel);
normalCalcPanel.add(MainMath.exitButton);
MainMath.frame.add(normalCalcPanel);
MainMath.frame.repaint();
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
Other (main) class:
package com.Egg;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class MainMath implements ActionListener {
static JFrame frame = new JFrame("Math Tools");
static JButton exitButton = new JButton("Exit");
JPanel mainPanel = new JPanel();
JLabel mainLabel = new JLabel("Select your tool.", SwingConstants.CENTER);
JButton nB = new JButton("Normal Calc.");
JButton tB = new JButton("Right Triangle Calc.");
JButton eB = new JButton("Equations Calc.");
public MainMath() {
frame.setBounds(300, 300, 500, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setResizable(false);
mainPanel.setLayout(null);
mainPanel.setBounds(0, 0, 500, 700);
mainLabel.setBounds(100, 25, 300, 50);
mainLabel.setFont(new Font("Monospaced Bold", Font.BOLD, 18));
nB.setBounds(100, 100, 300, 40);
tB.setBounds(100, 150, 300, 40);
eB.setBounds(100, 200, 300, 40);
nB.setFocusable(false);
tB.setFocusable(false);
eB.setFocusable(false);
nB.addActionListener(this);
tB.addActionListener(this);
eB.addActionListener(this);
mainPanel.add(mainLabel);
mainPanel.add(nB);
mainPanel.add(tB);
mainPanel.add(eB);
frame.add(mainPanel);
frame.setVisible(true);
exitButton.setBounds(16, 10, 80, 35);
exitButton.setFocusable(false);
exitButton.addActionListener(this);
}
public static void main(String[] args) {
new MainMath();
System.out.println("");
}
public void setMainScreen() {
frame.remove(exitButton);
frame.remove(NormalCalc.normalCalcPanel);
frame.add(mainPanel);
frame.repaint();
}
public static JFrame getFrame() {
return frame;
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == exitButton)
setMainScreen();
if (e.getSource() == nB) {
frame.remove(mainPanel);
new NormalCalc();
}
if (e.getSource() == tB)
new TriangleCalc();
if (e.getSource() == eB)
new EquationCalc();
}
}
I see multiple issues in your code:
Your arrangement of your buttons is weird looking at first glance.
normalCalcPanel is static, why? It should never be
setBounds(...) when using layout managers, those statements are ignored, so no need for them
repaint() unless you've added / removed any element AFTER you've displayed your GUI, these calls are unnecessary, and should come with revalidate() as well.
MainMath.exitButton another static component, STOP
MainMath.frame.add(normalCalcPanel) implies that your JFrame called frame is static as well, which again, shouldn't be
And (I'm gonna guess here) more than probably you're creating a second instance inside MainMath, but because we don't have the code from that class we don't know what's going on
I ran your code and it looks ok, so that's why I believe your MainMath is creating another instance of JFrame
Here's an example of a calculator arrangement, that should help you to structure your code similarly, not the GUI but the components and classes
Edit
Okay, I understand now that I should not use static things, but how can I add a panel to a frame which I created in another class? I used 'static', because it seemed to work
Let's make an analogy for this case, imagine that your JFrame is a book, and that your JPanels are the sheets of that book, when you write on those sheets, you don't add / paste the book to the sheets, you add the sheets to the book.
So, in this case it's the same, your main class should create the JPanels and add those to your JFrame, your JPanel classes shouldn't have knowledge of your JFrame
In the case of the book, your sheets don't need to know to which book the belong, you know that and the book knows which sheets belong to it, not viceversa.
I made an example to show you what I mean by this, I didn't recreate your GUI but made it as simple as I could for you to get the idea:
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class AnotherCalculator {
private JFrame frame;
private CalculatorPanel calculatorPanel;
public static void main(String[] args) {
SwingUtilities.invokeLater(new AnotherCalculator()::createAndShowGUI);
}
private void createAndShowGUI() {
frame = new JFrame(getClass().getSimpleName());
calculatorPanel = new CalculatorPanel();
frame.add(calculatorPanel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class CalculatorPanel extends JPanel {
private String[] operations = {"+", "-", "*", "/", "DEL", "AC", "(", ")", "-", "^", "SQRT", ".", "+/-", "="};
private static final int NUMBER_OF_DIGITS = 10;
private JButton[] buttons;
public CalculatorPanel() {
this.setLayout(new GridLayout(0, 4, 5, 5));
buttons = new JButton[operations.length + NUMBER_OF_DIGITS];
for (int i = 0; i < buttons.length; i++) {
if (i < NUMBER_OF_DIGITS) {
buttons[i] = new JButton(String.valueOf(i));
} else {
buttons[i] = new JButton(operations[i - NUMBER_OF_DIGITS]);
}
this.add(buttons[i]);
}
}
}

List of Buttons one below other inside JScrollPane

I want to make list of JButtons (with fixed dimensions, one beneath another) inside JScrollPane, using Swing. My idea was to make JPanel with GridBagLayout and add buttons in their suiting rows, and then create JScrollPane with that JPanel. That looks fine when number of buttons is large, but when the number of buttons is 2 or 3, I can't manage to align buttons one right below the other.
Also later I will add option to add new button (thus the + sign).
Works fine with 10 buttons
I get this empty space between button 0 and button 1 when it's just 2 buttons (this is the problem)
The code (creates upper east panel)
private JPanel createLayerPanel() {
JPanel layerPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// Label ------------------------------------------------
JLabel layersLabel = new JLabel("Buttons");
layersLabel.setHorizontalAlignment(SwingConstants.CENTER);
layersLabel.setFont(DEFAULT_FONT);
//layersLabel.setBorder(new LineBorder(Color.red, 3));
layersLabel.setBackground(new Color(0x22222));
layersLabel.setForeground(new Color(0xFFFFFF));
layersLabel.setOpaque(true);
c.gridx = c.gridy = 0;
c.ipadx = 180;
c.weightx = 1;
c.fill = GridBagConstraints.BOTH;
layerPanel.add(layersLabel, c);
// Button ------------------------------------------------
JButton newLayerBtn = new JButton("+");
newLayerBtn.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 18));
newLayerBtn.setBackground(new Color(0x222222));
newLayerBtn.setForeground(Color.white);
newLayerBtn.setFocusable(false);
c.gridx = 1;
c.gridy = 0;
c.ipadx = 0;
c.weightx = 0;
layerPanel.add(newLayerBtn, c);
// ScrollPane ------------------------------------------------
//------------------------------------------------------------
//------------------------------------------------------------
JPanel layerListPanel = new JPanel(new GridBagLayout());
layerListPanel.setBackground(Color.BLACK);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 1;
gbc.ipady = 40;
gbc.gridx = 0;
gbc.anchor = GridBagConstraints.NORTH;
for (gbc.gridy = 0; gbc.gridy < 10; gbc.gridy++) {
JButton btn = new JButton("Button " + gbc.gridy);
layerListPanel.add(btn, gbc);
}
JScrollPane js = new JScrollPane(layerListPanel);
js.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
// ...
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 2;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
layerPanel.add(js, c);
return layerPanel;
}
Do you absolutely need a GridBagLayout?
I just made a demo using a simple Box.
And please have a look at How to write an SSCCE.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class YY extends JFrame {
static String[] args;
public YY() {
setSize(160, 200);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
int icnt= args.length==0 ? 5 : Integer.parseInt(args[0]);
Box box= Box.createVerticalBox();
for (int i=1; i<=icnt; i++) {
JButton btn= new JButton("Button "+i);
btn.setMaximumSize(new Dimension(150, 30));
box.add(btn);
}
JScrollPane scroll= new JScrollPane(box);
scroll.setPreferredSize(new Dimension(150, 100));
add(scroll);
setVisible(true);
}
public static void main(String... args) {
YY.args= args;
EventQueue.invokeLater(YY::new);
}
}
The below code initially displays a JFrame that contains a single JButton that displays the text Add. Each time you click the button a new JButton appears above it. The text on each newly created button is a three digit number with leading zeros that is incremented each time the Add button is clicked. And whenever a new button is added, the JFrame increases in height in order to display the newly added button.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class GridBttn implements ActionListener, Runnable {
private int counter;
private JFrame frame;
private JPanel gridPanel;
#Override
public void run() {
showGui();
}
#Override
public void actionPerformed(ActionEvent event) {
addButtonToGridPanel();
}
private void addButtonToGridPanel() {
JButton button = new JButton(String.format("%03d", counter++));
gridPanel.add(button);
frame.pack();
}
private JButton createButton(String text) {
JButton button = new JButton(text);
button.addActionListener(this);
return button;
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(createButton("Add"));
return buttonsPanel;
}
private JPanel createGridPanel() {
gridPanel = new JPanel(new GridLayout(0, 1));
return gridPanel;
}
private void showGui() {
frame = new JFrame("Grid");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createGridPanel(), BorderLayout.CENTER);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new GridBttn());
}
}
Note the parameters to GridLayout constructor. Zero rows and one column. This means that whenever a Component is added to the JPanel it will be placed directly beneath the last Component added. In other words all the components added will appear in a single column. Also note that I call method pack() (of class JFrame) after adding a new button. This causes the JFrame to recalculate its size in order to display all the buttons.
EDIT
Due to OP's comment slightly modified above code so as to be more suitable to his requirements.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.WindowConstants;
public class GridBttn implements ActionListener, Runnable {
private int counter;
private JFrame frame;
private JPanel gridPanel;
private JPanel gridPanel2;
#Override
public void run() {
showGui();
}
#Override
public void actionPerformed(ActionEvent event) {
addButtonToGridPanel();
}
private void addButtonToGridPanel() {
JButton button = new JButton(String.format("%03d", counter++));
gridPanel2.add(button);
frame.pack();
}
private JButton createButton(String text) {
JButton button = new JButton(text);
button.addActionListener(this);
return button;
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(createButton("Add"));
return buttonsPanel;
}
private JPanel createMainPanel() {
gridPanel = new JPanel();
gridPanel.setPreferredSize(new Dimension(400, 300));
return gridPanel;
}
private JScrollPane createScrollPane() {
gridPanel2 = new JPanel();
BoxLayout layout = new BoxLayout(gridPanel2, BoxLayout.PAGE_AXIS);
gridPanel2.setLayout(layout);
JScrollPane scrollPane = new JScrollPane(gridPanel2,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setPreferredSize(new Dimension(70, 0));
return scrollPane;
}
private void showGui() {
frame = new JFrame("Grid");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.add(createScrollPane(), BorderLayout.LINE_END);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new GridBttn());
}
}

Why Are My Buttons Taking Up The Whole JFrame?

My code was working before, but now one JButton takes up the entire JFrame, any help would be appreciated!
I am using a FlowLayout called fl and a class called Ken
I have ten buttons called (oneButton, twoButton, threeButton, etc..)
MY CODE:
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Ken {
public static void frame(){
JFrame frame = new JFrame("Pow");
frame.setSize(500, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
FlowLayout fl = new FlowLayout(0, 50, 40);
JButton oneButton = new JButton(" 1 ");
oneButton.setPreferredSize(new Dimension(100, 90));
frame.add(oneButton);
JButton twoButton = new JButton(" 2 ");
twoButton.setPreferredSize(new Dimension(100, 90));
frame.add(twoButton);
JButton threeButton = new JButton(" 3 ");
threeButton.setPreferredSize(new Dimension(100, 90));
frame.add(threeButton);
JButton fourButton = new JButton(" 4 ");
fourButton.setPreferredSize(new Dimension(100, 90));
frame.add(fourButton);
JButton fiveButton = new JButton(" 5 ");
fiveButton.setPreferredSize(new Dimension(100, 90));
frame.add(fiveButton);
JButton sixButton = new JButton(" 6 ");
sixButton.setPreferredSize(new Dimension(100, 90));
frame.add(sixButton);
JButton sevenButton = new JButton(" 7 ");
sevenButton.setPreferredSize(new Dimension(100, 90));
frame.add(sevenButton);
JButton eightButton = new JButton(" 8 ");
eightButton.setPreferredSize(new Dimension(100, 90));
frame.add(eightButton);
JButton nineButton = new JButton(" 9 ");
nineButton.setPreferredSize(new Dimension(100, 90));
frame.add(nineButton);
JButton zeroButton = new JButton("
0 ");
zeroButton.setPreferredSize(new Dimension(400, 90));
frame.add(zeroButton);
frame.setComponentOrientation(
ComponentOrientation.LEFT_TO_RIGHT);
}
public static void main(String[] args){
frame();
}
}
Anything I can try?
I am using a FlowLayout called fl ...
You are not in fact using FlowLayout as you never call setLayout(...) on a container. Instead your Frame's contentPane is using the default layout for contentPanes, BorderLayout, which will cause the last component added in a default way to fill up the container's BorderLayout.CENTER location.
So one solution is to use your layout:
FlowLayout fl = new FlowLayout(0, 50, 40);
frame.getContentPane().setLayout(fl);
But having said that, you will probably be better off not setting the preferred sizes of your components but instead using a combination of nested containers each using its own layout in order to achieve a pleasing and complex GUI that will be much easier to maintain and extend.
Alternatively, you could play with more complex layouts such as the GridBagLayout. For example:
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;
public class Ken2 {
private static final String[][] NUMBERS = {
{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"},
{"0"}
};
private static final float BUTTON_FONT_PTS = 45f;
private static final int INSETS = 20;
private static final Insets BUTTON_INSETS = new Insets(INSETS, INSETS,
INSETS, INSETS);
private static final int IPAD = 20;
private JPanel mainPanel = new JPanel();
public Ken2() {
mainPanel.setLayout(new GridBagLayout());
for (int row = 0; row < NUMBERS.length; row++) {
addRowToPanel(row, NUMBERS[row]);
}
}
private void addRowToPanel(int row, String[] numbersRow) {
int columns = numbersRow.length;
for (int col = 0; col < numbersRow.length; col++) {
addNumberButton(row, col, columns, numbersRow[col]);
}
}
private void addNumberButton(int row, int col, int columns,
String numberText) {
JButton button = new JButton(numberText);
button.setFont(button.getFont().deriveFont(Font.BOLD, BUTTON_FONT_PTS));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = col;
gbc.gridy = row;
gbc.gridheight = 1;
gbc.gridwidth = 3 / columns;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = BUTTON_INSETS;
gbc.ipadx = IPAD;
gbc.ipady = IPAD;
mainPanel.add(button, gbc);
}
private static void createAndShowGui() {
Ken2 ken = new Ken2();
JFrame frame = new JFrame("Ken2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(ken.getMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private Component getMainPanel() {
return mainPanel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Call setLayout(fl) on your void frame() method.

about layouts in simple calculator

hi there i am trying to make a calculator with coding sizes,layouts etc. by myself (trying to not use NetBeans and it is not a homework). but i am facing with a problem about empty spaces. i have a TextArea and Buttons but as you can see below i cant handle this space problem. here is my code,
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
public class calculator extends JFrame {
public calculator(){
initComponents();
}
private void initComponents(){
JPanel panelScreen = new JPanel(new GridLayout(0,1));
JTextArea screen = new JTextArea();
panelScreen.add(screen);
JFrame frame = new JFrame("CALCULATOR");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panelButtons = new JPanel(new GridLayout(3,3));
JButton oneButton = new JButton("1");
panelButtons.add(oneButton);
JButton twoButton = new JButton("2");
panelButtons.add(twoButton);
JButton threeButton = new JButton("3");
panelButtons.add(threeButton);
JButton fourButton = new JButton("4");
panelButtons.add(fourButton);
JButton fiveButton = new JButton("5");
panelButtons.add(fiveButton);
JButton sixButton = new JButton("6");
panelButtons.add(sixButton);
JButton sevenButton = new JButton("7");
panelButtons.add(sevenButton);
JButton eightButton = new JButton("8");
panelButtons.add(eightButton);
JButton nineButton = new JButton("9");
panelButtons.add(nineButton);
frame.getContentPane().add(panelScreen, BorderLayout.NORTH);
//frame.getContentPane().add(new JSeparator(), BorderLayout.CENTER);
frame.getContentPane().add(panelButtons, BorderLayout.SOUTH);
frame.setBounds(50, 50, 500, 500);
frame.setResizable(false);
//frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new calculator();
}
}
and this the picture of programme;
i appreciate if you can help me. anyway thanks :)
A few suggestions:
Don't set the JFrame's size, and in fact don't set any sizes.
Call pack to all the components to set their own sizes.
If you want the buttons bigger, consider changing the size of their fonts.
e.g.,
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.*;
public class Calc2 {
public static final String[][] BUTTON_TEXTS = {
{"7", "8", "9", "+"},
{"4", "5", "6", "-"},
{"1", "2", "3", "*"},
{"0", ".", "/", "="}
};
public static final Font BTN_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 24);
private static void createAndShowGui() {
JTextField field = new JTextField(10);
field.setFont(BTN_FONT.deriveFont(Font.PLAIN));
JPanel btnPanel = new JPanel(new GridLayout(BUTTON_TEXTS.length,
BUTTON_TEXTS[0].length));
for (int i = 0; i < BUTTON_TEXTS.length; i++) {
for (int j = 0; j < BUTTON_TEXTS[i].length; j++) {
JButton btn = new JButton(BUTTON_TEXTS[i][j]);
btn.setFont(BTN_FONT);
btnPanel.add(btn);
}
}
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(field, BorderLayout.PAGE_START);
mainPanel.add(btnPanel, BorderLayout.CENTER);
JFrame frame = new JFrame("Calc2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
// no need to extend frame!
//public class Calculator extends JFrame {
public class Calculator {
public Calculator(){
initComponents();
}
private void initComponents(){
// I find it easier to create a panel and SET it as the content pane
JPanel gui = new JPanel(new BorderLayout(5,5));
// add some padding to the main GUI
gui.setBorder(new EmptyBorder(4,4,4,4));
// not needed if only a single compoinent is to be added!
//JPanel panelScreen = new JPanel(new GridLayout(0,1));
// add some constraints to make the output field bigger.
// if it is intended to be single line, a JTextField should be used.
JTextArea screen = new JTextArea(2,25);
gui.add(screen, BorderLayout.NORTH);
//panelScreen.add(screen);
JFrame frame = new JFrame("CALCULATOR");
frame.setContentPane(gui);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add padding around the buttons
JPanel panelButtons = new JPanel(new GridLayout(3,3,4,4));
JButton oneButton = new JButton("1");
panelButtons.add(oneButton);
JButton twoButton = new JButton("2");
panelButtons.add(twoButton);
JButton threeButton = new JButton("3");
panelButtons.add(threeButton);
JButton fourButton = new JButton("4");
panelButtons.add(fourButton);
JButton fiveButton = new JButton("5");
panelButtons.add(fiveButton);
JButton sixButton = new JButton("6");
panelButtons.add(sixButton);
JButton sevenButton = new JButton("7");
panelButtons.add(sevenButton);
JButton eightButton = new JButton("8");
panelButtons.add(eightButton);
JButton nineButton = new JButton("9");
panelButtons.add(nineButton);
//frame.getContentPane().add(new JSeparator(), BorderLayout.CENTER);
// Add the buttons to the CENTER and they will
// fill whatever space they are provided.
gui.add(panelButtons, BorderLayout.CENTER);
//frame.setBounds(50, 50, 500, 500);
//frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Calculator();
}
});
}
}
You might like to study this example that follows the suggestions of #HFOE and #mre. Note that "size" appears nowhere in the code.
Read Laying Out Components Within a Container
Implement appropriate layout(s)
EDIT -
Quick solution - replace the JFrame layout manager with BoxLayout (i.e. setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS))).

Categories

Resources