Java JFrame button organization - java

How do i create a jframe that organizes the text box and jbuttons, with the textbox on top and a 3 by 4 grid layout of buttons 1-10?
"TEXT BOX HERE"
[1][2][3]
[4][5][6]
[7][8][9]
[(][0][)]
This is what I have so far:
setTitle("Test");
setSize(400, 400);
// Create JButton and JPanel
JButton[] buttons = new JButton[12];
JButton buttonLpar = new JButton("(");
JButton buttonRpar = new JButton(")");
JPanel panel = new JPanel();
JPanel panel2 = new JPanel(new GridLayout(3, 4));
// adding 10 buttons
for(int i = 0; i < 10; i++) {
buttons[i] = new JButton(String.valueOf(i));
}
buttons[11].add(buttonLpar);
buttons[12].add(buttonRpar);
JTextField text = new JTextField("",10);
text.setFont(new Font("Helvetica Neue", Font.BOLD, 12));
panel.add(text, BorderLayout.NORTH);
panel.add(panel2, BorderLayout.CENTER);
this.getContentPane().add(panel);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
But that's where I'm stuck.
Okay I should note that I need a for loop to populate 3 by 4 gridlayout. But I don't know what I need in the loop.

For this kind of grid, assuming you create it on the go, you just need to have an if-else to see if you're on the last row of data.
For example:
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GridLayoutWithEmptyComponents {
private JFrame frame;
private JPanel pane;
private JPanel buttonsPane;
private JButton[] buttons;
private void createAndShowGUI() {
frame = new JFrame(getClass().getSimpleName());
pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
buttonsPane = new JPanel();
buttonsPane.setLayout(new GridLayout(4, 3));
buttons = new JButton[10];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton("" + (i + 1));
if (i == buttons.length - 1) {
buttonsPane.add(new JButton("("));
buttonsPane.add(buttons[i]);
buttonsPane.add(new JButton(")"));
} else {
buttonsPane.add(buttons[i]);
}
}
pane.add(new JLabel("Text box"));
pane.add(buttonsPane);
frame.add(pane);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new GridLayoutWithEmptyComponents()::createAndShowGUI);
}
}
Or you could have all the data in a String[] like:
String[] buttonValues = {"1", "2", "3", ..., "8", "9", "(", "0", ")"};
And then use those values as the JButtons values without the need for an if-else inside the loop.

Related

Vertically center GridBagLayout like BoxLayout

I am trying to center components using a GridBagLayout in the same manner that a Box centers components when you use Box.createVerticalGlue(). I initially did use a vertical Box:
Box box = Box.createVerticalBox();
box.add(Box.createVerticalGlue());
box.add(add);
box.add(remove);
box.add(edit);
box.add(Box.createVerticalGlue());
JPanel internalPanel = new JPanel(new BorderLayout());
internalPanel.add(keywordsScrollPane, BorderLayout.CENTER);
internalPanel.add(box, BorderLayout.EAST);
But as you can see, it looks sloppy because my buttons are different sizes:
I decided to switch to GridBagLayout so I can utilize GridBagConstraints.fill. This approach fixes my button width issue, but I cannot figure out how to vertically center the buttons. I changed the grid size and placed the buttons in the middle three rows, but the buttons were still appearing at the top of the panel. I tried making use of GridBagConstraints.anchor and GridBagConstraints.weighty as well. The latter almost worked, but there are very large margins between the buttons:
I am looking for the buttons to be grouped together as they were in my Box approach. How can I achieve this with a GridBadLayout?
I am using a class I created called ConstraintsBuilder which works exactly as you would expect. It's for creating GridBagContraints with nice one-liners. Here is all the (relevant) code for your viewing pleasure:
public class KeywordsDialog extends JDialog implements ActionListener, ListSelectionListener {
private JList<String> keywords;
private JScrollPane keywordsScrollPane;
private JButton add;
private JButton remove;
private JButton edit;
private Set<String> keywordsList;
public KeywordsDialog(Window parent, Collection<String> keywordsList) {
super(parent);
this.keywordsList = keywordsList == null ? new HashSet<String>() : new HashSet<String>(keywordsList);
if (keywordsList != null && !keywordsList.isEmpty()) {
this.keywords = new JList<String>(toListModel(keywordsList));
} else {
this.keywords = new JList<String>(new DefaultListModel<String>());
}
this.keywordsScrollPane = new JScrollPane(keywords);
this.add = new JButton("Add");
this.remove = new JButton("Remove");
this.edit = new JButton("Edit");
this.edit.setEnabled(false);
this.add.setEnabled(false);
ConstraintsBuilder builder = LayoutUtils.gridBagConstraintsBuilder();
JPanel internalPanel = new JPanel(new GridBagLayout());
internalPanel.add(this.keywordsScrollPane, builder.gridX(0).gridY(0).gridHeight(3).margins(0, 0, 0, 5)
.fill(GridBagConstraints.BOTH).weightX(1D).weightY(1D).build());
internalPanel.add(this.add,
builder.reset().gridX(1).gridY(0).fill(GridBagConstraints.HORIZONTAL).weightX(1D).weightY(1D).build());
internalPanel.add(this.remove,
builder.reset().gridX(1).gridY(1).fill(GridBagConstraints.HORIZONTAL).weightX(1D).weightY(1D).build());
internalPanel.add(this.edit,
builder.reset().gridX(1).gridY(2).fill(GridBagConstraints.HORIZONTAL).weightX(1D).weightY(1D).build());
this.keywords.setBorder(BorderFactory.createTitledBorder("Keywords"));
internalPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
this.setLayout(new BorderLayout());
this.add(internalPanel, BorderLayout.CENTER);
Dimension screen = GuiHelper.getScreenSize(parent);
this.setSize((int) (screen.getWidth() / 4), (int) (screen.getHeight() / 3));
this.setLocationRelativeTo(parent);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
// ...
}
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the How to Use GridBagLayout section.
The easiest way to create this GUI is to treat the JTextArea separately from the JButton area.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class ExampleGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new ExampleGUI());
}
#Override
public void run() {
JFrame frame = new JFrame("Example GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTextArea(), BorderLayout.CENTER);
frame.add(createButtonPanel(), BorderLayout.EAST);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JScrollPane createTextArea() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JTextArea textArea = new JTextArea(10, 30);
textArea.setText("keyword");
panel.add(textArea, BorderLayout.CENTER);
return new JScrollPane(panel);
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(0, 5, 5, 5);
gbc.gridy = 0;
JButton button = new JButton("Add");
panel.add(button, gbc);
gbc.gridy++;
button = new JButton("Remove");
panel.add(button, gbc);
gbc.gridy++;
button = new JButton("Edit");
panel.add(button, gbc);
return panel;
}
}
I would make the GUI simpler. Put the three buttons into a JPanel that uses a GridLayout, one declared to use 1 column and variable number of rows, one with a desired spacing between buttons, here, 5 pixels: JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 5, 5)); and then put that JPanel into the center of a another JPanel, and GridBagLayout without constraints works well for this:
JPanel sidePanel = new JPanel(new GridBagLayout());
sidePanel.add(buttonPanel);
and put that JPanel into the right side of a border layout using JPanel. For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FooSwing01 extends JPanel {
public FooSwing01() {
JTextArea textArea = new JTextArea(20, 50);
JScrollPane scrollPane = new JScrollPane(textArea);
JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 5, 5));
int maxButtons = 3;
for (int i = 0; i < maxButtons; i++) {
buttonPanel.add(new JButton("Button " + (i + 1)));
}
JPanel sidePanel = new JPanel(new GridBagLayout());
sidePanel.add(buttonPanel);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout(5, 5));
add(scrollPane);
add(sidePanel, BorderLayout.LINE_END);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("GUI");
frame.add(new FooSwing01());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}

Nesting FlowLayout Panels

I'm trying to create a GUI using JAVA for a BMR calculator.
I'm having some problems with getting the GUI right so I have been experimenting with different layout managers/nesting Jpanels.
My current code has an age and gender label, both contained in separate JPanels in a flow layout, but the problem is that they appear next to eachother rather than on seperate lines as I want them to.
How can I acheive this with my code? My current laoyut is as below, I want Gender to be below age, and have been playing with this for some time but can't get it to work.
Cheers.
package v2;
import javax.swing.*;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.FlowLayout;
public class BmrCalcv2 extends JFrame {
static JFrame mainFrame;
static JPanel mainPanel;
static JMenuBar menuBar;
static JMenu fileMenu, editMenu;
static JPanel agePanel;
private JLabel ageLabel;
private JTextField ageTextField;
static JPanel genderPanel;
private JLabel genderLabel;
public BmrCalcv2() {
// Main JFrame
mainFrame = new JFrame("BMR/TDEE Calculator");
mainPanel = new JPanel();
// All JPanel declarations
menuBar = new JMenuBar();
agePanel = new JPanel();
genderPanel = new JPanel();
// JPanel layout managers
agePanel.setLayout(new FlowLayout(10));
genderPanel.setLayout(new FlowLayout(10));
// Menu JPanel
fileMenu = new JMenu("File");
editMenu = new JMenu("Edit");
menuBar.add(fileMenu);
menuBar.add(editMenu);
// Age JPanel
ageLabel = new JLabel("Age:");
ageTextField = new JTextField(5);
agePanel.add(ageLabel);
agePanel.add(ageTextField);
// Gender JPanel
genderLabel = new JLabel("Gender:");
genderPanel.add(genderLabel);
// Adding sub JPanels to main JPanel
mainPanel.add(agePanel);
mainPanel.add(genderPanel);
// Adding main JPanel/menubar to JFrame
mainFrame.setJMenuBar(menuBar);
mainFrame.add(mainPanel);
}
public static void main(String[] args) {
BmrCalcv2 frame = new BmrCalcv2();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
mainFrame.setSize(330, 300);;
mainFrame.setResizable(false);
}
}
If you don't care about alignment:
mainFrame.getContentPane().setLayout(new BoxLayout(mainFrame.getContentPane(), BoxLayout.X_AXIS));
// quick pseudocode incoming
for(int x = 0; x < components.size(); x++) {
JPanel j = new JPanel();
j.setLayout(new FlowLayout(FlowLayout.CENTER)); // I think CENTER is the default anyhow
j.add(getLabel(x));
j.add(getField(x));
mainFrame.add(j);
}
If you care about alignment, swap the FlowLayout for a BoxLayout along the Y_AXIS and put some horizontal glue between the label and the input field(s).
Something like this should do it:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class GridBagLayoutExample {
public static void main(String[] args) {
init();
}
private static void init() {
// create the jframe
JFrame jframe = new JFrame("BMI Calculator");
// create the gui elements
JLabel ageLabel = new JLabel("Age:");
JTextField ageTxt = new JTextField(20);
JLabel genderLabel = new JLabel("Gender:");
JTextField genderTxt = new JTextField(20);
// create gridbag layout and constraints
GridBagLayout gbl = new GridBagLayout();
// create the panel using the gbl
JPanel pan = new JPanel(gbl);
// create the constraints
GridBagConstraints cons = new GridBagConstraints();
cons.fill = GridBagConstraints.HORIZONTAL;
// age label
cons.gridx = 0;
cons.gridy = 0;
pan.add(ageLabel, cons);
// age text
cons.gridx = 1;
cons.gridy = 0;
pan.add(ageTxt, cons);
// gender label
cons.gridx = 0;
cons.gridy = 1;
pan.add(genderLabel, cons);
// gender text
cons.gridx = 1;
cons.gridy = 1;
pan.add(genderTxt, cons);
// add the panel to the jframe
jframe.add(pan, BorderLayout.CENTER);
// show the jframe
jframe.setSize(400, 200);
jframe.setVisible(true);
}
}
Looks like this:

Java GUI Moving buttons to bottom of the page

I was wondering how I would move my buttons to the bottom of the frame/window.
What I have now is this:
And what I want it to look like is this:
Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Font;
public class checkbook{
static JButton Button[] = new JButton[8];
JLabel begin, accountName, balance;
JFrame frame;
JPanel jpanel, jpanel1;
Container contentPane;
private JTextField textAccount, textBalance;
public static void main(String[] args){
checkbook checkbook = new checkbook();
checkbook.startFrame();
}
checkbook(){
frame = new JFrame("Checkbook");
}
public void startFrame(){
String bottomButtons[] = {
"Create a New Account", "Load Trans from a file", "Add New Transactions", "Search Transactions",
"Sort Transactions", "View/Delete Transactions", "Backup Transactions", "Exit"
};
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
Font beginFont = new Font("Arial", Font.PLAIN + Font.BOLD, 22);
textAccount = new JTextField(" ", 15);
textBalance = new JTextField("0.0", 15);
begin = new JLabel("Use The Buttons below To Manage Transactions");
begin.setFont(beginFont);
contentPane.add(begin);
//Container contentPane1 = frame.getContentPane();
//contentPane1.setLayout(new FlowLayout());
JPanel jpanel = new JPanel();
accountName = new JLabel ("Account Name: ");
jpanel.add(accountName);
jpanel.add(textAccount);
balance = new JLabel ("Balance: ");
jpanel.add(balance);
jpanel.add(textBalance);
JPanel jpanel1 = new JPanel();
jpanel1.setLayout(new GridLayout(2,4));
for(int i = 0; i < 8; i++){
Button[i] = new JButton(bottomButtons[i]);
jpanel1.add(Button[i]);
//Button[i].addActionListener(AL);
}
frame.pack();
frame.setSize(800, 300);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(jpanel);
frame.add(jpanel1);
}
}
So I was wondering what would I do to move the buttons down to the bottom. Would I have to use a BorderLayout and use BorderLayout.SOUTH etc or is there a way to do this with the GridLayout I already have. If I have to use the BorderLayout how would I keep my buttons in order (2 rows, 4 columns).
Would I have to use a BorderLayout and use BorderLayout.SOUTH
Yes, but the best answer is for you to try it and see what happens. Why don't you?
If I have to use the BorderLayout how would I keep my buttons in order(2 rows, 4 columns).
Nest JPanels. Put the buttons in a GridLayout using JPanel, and place that JPanel BorderLayout.SOUTH, or better, BorderLayout.PAGE_END
e.g.,
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class NestedPanels extends JPanel {
private static final String TITLE_TEXT = "Use The Buttons Below To Manage Transactions";
private static final String[] BTN_TEXTS = { "Create a New Account",
"Load a Trans from a File", "Add New Transactions",
"Search Transactions", "Sort Transactions",
"View/Delete Transactions", "Backup Transaction", "Exit" };
private static final int TITLE_POINTS = 24;
public NestedPanels() {
JLabel titleLabel = new JLabel(TITLE_TEXT, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD,
TITLE_POINTS));
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel); // put it in a JPanel so it will expand to fill BoxLayout
JPanel accountBalancePanel = new JPanel();
accountBalancePanel.add(new JLabel("Account Name:"));
accountBalancePanel.add(new JTextField(10));
accountBalancePanel.add(Box.createHorizontalStrut(20));
accountBalancePanel.add(new JLabel("Balance:"));
accountBalancePanel.add(new JTextField(10));
JPanel northPanel = new JPanel();
northPanel.setLayout(new BoxLayout(northPanel, BoxLayout.PAGE_AXIS));
northPanel.add(titlePanel);
northPanel.add(accountBalancePanel);
JPanel southBtnPanel = new JPanel(new GridLayout(2, 4, 1, 1));
for (String btnText : BTN_TEXTS) {
southBtnPanel.add(new JButton(btnText));
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
setLayout(new BorderLayout());
add(northPanel, BorderLayout.NORTH);
add(Box.createRigidArea(new Dimension(400, 400))); // just an empty placeholder
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {
NestedPanels mainPanel = new NestedPanels();
JFrame frame = new JFrame("Nested Panels Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Which displays as:

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