Numberpad Not Displaying Correctly - java

I have a Java GUI project where I am creating an ATM. I have everything setup, but for some reason my number pad on the left is not displaying properly. It should appear as a 4x3 grid of numbers, but it is just displaying a 9. I have checked to make sure it is in a GridLayout and I have checked my loop, but I possibly may have looked over something. Any help is appreciated, thanks!
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.*;
public class ATMProject extends JPanel implements ActionListener {
private JPanel mainPanel = null;
private JPanel btnPanel = null;
private JPanel userBtns = null;
private JTextArea textArea = null;
private JPanel keyPanel = null;
private JTextField numField = null;
private JPanel numpadPanel = null;
private JButton[] userButtons = null;
private JButton[] keypadButtons = null;
private String[] btnPanelbtns = { "A", "B", "C" };
private String[] numpadPanelbtns = { "7", "4", "1", "8", "5", "2", "9", "6", "3", "0", ".", "CE" };
public ATMProject() {
super();
mainPanel = new JPanel();
this.setLayout(new BorderLayout());
this.add(mainPanel);
btnPanel = new JPanel();
btnPanel.setLayout(new GridLayout(3, 1));
this.add(btnPanel, BorderLayout.EAST);
textArea = new JTextArea();
this.add(textArea, BorderLayout.CENTER);
keyPanel = new JPanel();
keyPanel.setLayout(new BorderLayout());
this.add(keyPanel, BorderLayout.WEST);
numpadPanel = new JPanel();
numpadPanel.setLayout(new GridLayout(0, 3));
keyPanel.add(numpadPanel, BorderLayout.CENTER);
numField = new JTextField();
keyPanel.add(numField, BorderLayout.NORTH);
userButtons = new JButton[btnPanelbtns.length];
for (int i = 0; i < userButtons.length; i++) {
userButtons[i] = new JButton(btnPanelbtns[i]);
userButtons[i].addActionListener(this);
btnPanel.add(userButtons[i]);
}
keypadButtons = new JButton[numpadPanelbtns.length];
for (int i = 0; i < userButtons.length; i++) {
keypadButtons[i] = new JButton(numpadPanelbtns[i]);
keypadButtons[i].addActionListener(this);
numpadPanel.add(keypadButtons[i]);
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
MyFrame mf = new MyFrame();
}
}
import javax.swing.JFrame;
public class MyFrame extends JFrame {
private ATMProject atm = null;
public MyFrame(){
super();
atm = new ATMProject();
this.add(atm);
this.setTitle("ATM");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setSize(800,300);
this.setVisible(true);
}
}
This is how it is supposed to appear:

You're adding you buttons to keyPanel...
keyPanel.add(keypadButtons[i]);
which is using a BorderLayout...
keyPanel = new JPanel();
keyPanel.setLayout(new BorderLayout());
so only the last component added to it will be laid out by the panel.
One imagines you should be adding them to numpadPanel instead...
numpadPanel.add(keypadButtons[i]);
Yeah, I have that numpadPanel.add(keypadButtons[i]); and I am getting just 7 8 9 vertically.
That's kind of how GridLayout works, you could force into a horizontal priority mode by using something more like
numpadPanel.setLayout(new GridLayout(0, 3));

My loop was incorrectly written. for (int i = 0; i < userButtons.length; i++) my program was only outputting 3 buttons because userButtons.length only had 3 elements. I changed userButtons.length to numpadPanelbtns.length and it fixed it because there are 12 elements in the numpadPanelbtns array.

Related

Java JFrame button organization

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.

Adding new comboboxes Java

I have a problem with Swing interface on java. Explaination: I have a Combobox with 1, 2, 3, 4, 5 items. When an exact item is selected I need to create some more comboboxes the number of which depends on the selected item. So, if number 5 is selected, 5 more comboboxes must appear in the frame. I used ActionListener but it did not work properly. However, the same code but outside Actionlistener works well. What a problem can it be?
public class FrameClass extends JFrame {
JPanel panel;
JComboBox box;
String[] s = {"1", "2", "3", "4", "5"};
String[] s1 = {"0", "1", "2", "3", "4", "5"};
public FrameClass() {
panel = new JPanel();
box = new JComboBox(s);
JComboBox adults = new JComboBox(s);
JComboBox children = new JComboBox(s1);
panel.add(box, BorderLayout.CENTER);
box.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i <= box.getSelectedIndex(); i++) {
panel.add(adults, BorderLayout.WEST);
panel.add(children, BorderLayout.WEST);
}
}
});
add(panel);
}
}
public class MainClass {
public static void main(String[] args) {
JFrame frame = new FrameClass();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.getContentPane().setBackground(Color.WHITE);
frame.setVisible(true);
}
}
The problem that you don't inform the layout manager about new elements in your panel.
Here is the correct variant of your action listener:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class FrameClass extends JFrame {
JPanel panel;
JComboBox<String> box;
String[] s = {"1", "2", "3", "4", "5"};
String[] s1 = {"0", "1", "2", "3", "4", "5"};
public FrameClass() {
panel = new JPanel();
box = new JComboBox(s);
JComboBox[] adults = new JComboBox[5];
JComboBox[] children = new JComboBox[5];
for (int i = 0; i < 5; i++) {
adults[i] = new JComboBox<>(s);
children[i] = new JComboBox<>(s1);
}
panel.add(box, BorderLayout.CENTER);
JPanel nested = new JPanel();
add(nested, BorderLayout.EAST);
box.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
nested.removeAll();
nested.setLayout(new GridLayout(box.getSelectedIndex() + 1, 2));
for (int i = 0; i <= box.getSelectedIndex(); i++) {
nested.add(adults[i]);
nested.add(children[i]);
}
getContentPane().revalidate();
getContentPane().repaint();
pack();
}
});
add(panel);
}
public static void main(String[] args) {
JFrame frame = new FrameClass();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.getContentPane().setBackground(Color.WHITE);
frame.setLocationRelativeTo(null); // center the window
frame.setVisible(true);
}
}

How do I resize JComponents in GridLayout?

I'm new to Java programming. Can you help me with the layout of my first application (which is a simple calculator) please?
Here's the code I wrote:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class InputPad extends JFrame {
private JLabel statusLabel;
private JTextArea expTextArea;
InputPad() {
prepareGUI();
}
private void prepareGUI(){
JFrame mainFrame = new JFrame("My Calculator");
mainFrame.setSize(450,450);
mainFrame.setLayout(new GridLayout(3,2));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
JLabel headerLabel = new JLabel("Put your expression here:", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
expTextArea = new JTextArea("1+(2^3*4)");
//Digits Panel
JPanel digitPanel = new JPanel();
GroupLayout layoutDigits = new GroupLayout(digitPanel);
digitPanel.setLayout(layoutDigits);
layoutDigits.setAutoCreateGaps(true);
layoutDigits.setAutoCreateContainerGaps(true);
//Operators Panel
JPanel operatorPanel = new JPanel();
GroupLayout layoutOperators = new GroupLayout(operatorPanel);
operatorPanel.setLayout(layoutOperators);
layoutOperators.setAutoCreateGaps(true);
layoutOperators.setAutoCreateContainerGaps(true);
JButton[] numButtons= new JButton[10];
int i;
for (i=0;i<10;i++){
numButtons[i] = new JButton(Integer.toString(i));
numButtons[i].addActionListener(e -> {
// TODO
});
}
JButton bEquals = new JButton("=");
bEquals.addActionListener(e -> {
// TODO
});
JButton bPlus = new JButton("+");
bPlus.addActionListener(e -> {
// TODO
});
JButton bMinus = new JButton("-");
bMinus.addActionListener(e -> {
// TODO
});
JButton bMultiply = new JButton("*");
bMultiply.addActionListener(e -> {
// TODO
});
JButton bDivide = new JButton("/");
bDivide.addActionListener(e -> {
// TODO
});
JButton bLeftParenthesis = new JButton("(");
bLeftParenthesis.addActionListener(e -> {
// TODO
});
JButton bRightParenthesis = new JButton(")");
bRightParenthesis.addActionListener(e -> {
// TODO
});
JButton bPower = new JButton("^");
bPower.addActionListener(e -> {
// TODO
});
JButton bDel = new JButton("←");
bDel.addActionListener(e -> {
// TODO
});
layoutDigits.setHorizontalGroup(
layoutDigits.createSequentialGroup()
.addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(numButtons[7])
.addComponent(numButtons[4])
.addComponent(numButtons[1])
.addComponent(numButtons[0]))
.addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(numButtons[8])
.addComponent(numButtons[5])
.addComponent(numButtons[2])
.addComponent(bEquals))
.addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(numButtons[9])
.addComponent(numButtons[6])
.addComponent(numButtons[3]))
);
layoutDigits.setVerticalGroup(
layoutDigits.createSequentialGroup()
.addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(numButtons[7])
.addComponent(numButtons[8])
.addComponent(numButtons[9]))
.addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(numButtons[4])
.addComponent(numButtons[5])
.addComponent(numButtons[6]))
.addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(numButtons[1])
.addComponent(numButtons[2])
.addComponent(numButtons[3]))
.addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(numButtons[0])
.addComponent(bEquals))
);
layoutOperators.setHorizontalGroup(
layoutOperators.createSequentialGroup()
.addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(bPlus)
.addComponent(bMinus)
.addComponent(bLeftParenthesis)
.addComponent(bPower))
.addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(bMultiply)
.addComponent(bDivide)
.addComponent(bRightParenthesis)
.addComponent(bDel))
);
layoutOperators.setVerticalGroup(
layoutOperators.createSequentialGroup()
.addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(bPlus)
.addComponent(bMultiply))
.addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(bMinus)
.addComponent(bDivide))
.addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(bLeftParenthesis)
.addComponent(bRightParenthesis))
.addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(bPower)
.addComponent(bDel))
);
mainFrame.add(headerLabel);
mainFrame.add(expTextArea);
mainFrame.add(digitPanel);
mainFrame.add(operatorPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
}
I tried the GridLayout for my JFrame, but I couldn't resize and of my JComponent except the main JFrame. Even I can't place two JPanels (side by side) in one cell of the GridLayout or expand a JLabel to two cells of the GridLayout.
This is what I got:
And here's what I want:
Let's start from the use of Layout Managers, from the link on the part of GridLayout
GridLayout simply makes a bunch of components equal in size and displays them in the requested number of rows and columns
So, this isn't what you want, but if you read the GridBagLayout part it says:
GridBagLayout is a sophisticated, flexible layout manager. It aligns components by placing them within a grid of cells, allowing components to span more than one cell. The rows in the grid can have different heights, and grid columns can have different widths.
We can combine both of them, along with a BoxLayout and you will get a similar output to what you're trying to achieve:
PLEASE NOTE:
Before posting the code, take note of the following tips:
You're extending JFrame and at the same time you're creating a JFrame object, this is discouraged, remove one of them, in this case as you're using the object and this is the recommended thing to do, simply remove the extends JFrame from your class. If you really need to extend something, don't extend JFrame but a JPanel instead.
Place your program inside the EDT, as I did in the main() method
Don't use System.exit(0); instead call setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) as shown in the above code
And now the code
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class CalculatorExample {
private JFrame frame;
private JTextArea area;
private JButton[][] digitsButtons, symbolsButtons;
private String[][] digitsText = {{"7", "8", "9"}, {"4", "5", "6"}, {"1", "2", "3"}, {"0", "="}}; //Looks strange but this will make the button adding easier
private String[][] symbolsText = {{"+", "*"}, {"-", "/"}, {"(", ")"}, {"^", "←"}};
private JPanel buttonsPane, areaAndResultsPane, digitsPane, symbolsPane;
private JLabel label;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new CalculatorExample().createAndShowGui();
}
});
}
public void createAndShowGui() {
frame = new JFrame("Calculator Example");
area = new JTextArea();
area.setRows(5);
area.setColumns(20);
label = new JLabel("Results go here");
digitsButtons = new JButton [4][3];
symbolsButtons= new JButton [4][2];
areaAndResultsPane = new JPanel();
areaAndResultsPane.setLayout(new BoxLayout(areaAndResultsPane, BoxLayout.PAGE_AXIS));
buttonsPane = new JPanel();
buttonsPane.setLayout(new GridLayout(1, 2, 10, 10));
digitsPane = new JPanel();
digitsPane.setLayout(new GridBagLayout());
symbolsPane = new JPanel();
symbolsPane.setLayout(new GridLayout(4, 2));
GridBagConstraints c = new GridBagConstraints();
for (int i = 0; i < digitsText.length; i++) {
for (int j = 0; j < digitsText[i].length; j++) {
digitsButtons[i][j] = new JButton(digitsText[i][j]);
}
}
for (int i = 0; i < symbolsText.length; i++) {
for (int j = 0; j < symbolsText[i].length; j++) {
symbolsButtons[i][j] = new JButton(symbolsText[i][j]);
}
}
areaAndResultsPane.add(area);
areaAndResultsPane.add(label);
boolean shouldBreak = false;
for (int i = 0; i < digitsButtons.length; i++) {
for (int j = 0; j < digitsButtons[i].length; j++) {
c.gridx = j;
c.gridy = i;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
if (i == 3) {
if (j == 1) {
c.gridwidth = 2; //This makes the "=" button larger
shouldBreak = true;
}
}
digitsPane.add(digitsButtons[i][j], c);
if (shouldBreak) {
break;
}
}
}
for (int i = 0; i < symbolsButtons.length; i++) {
for (int j = 0; j < symbolsButtons[i].length; j++) {
symbolsPane.add(symbolsButtons[i][j]);
}
}
frame.add(areaAndResultsPane, BorderLayout.NORTH);
buttonsPane.add(digitsPane);
buttonsPane.add(symbolsPane);
frame.add(buttonsPane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
This was done nesting JPanels, each with a different layout, I hope it helps you to continue from here.
According to the Oracle documentation :
Each component takes all the available space within its cell, and each cell is exactly the same size.
So sadly, you can't resize any components inside a GridLayout.
You could instead use a GridBagLayout. It is a little bit more complicated to understand but offers more features. I let you make some tests with the documentation to get in touch with it !

Getting JButton To Work

right now I have some buttons on a calculator and they are not setup. I am confused as to how to get them to print something in the JTextField when clicked. I am aware that you need to use ActionListener, but I cannot seem to get it working. Thanks for your help!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JPanel implements ActionListener {
private JTextField tf = null;
private JButton[] arrBtn = null;
private String[] btnNames = { "1", "2", "3", "4", "5", "6", "7", "CE", "-", "+", "/", "%", "*", "=" };
private JPanel jp = new JPanel();
private char op = ' ';
private int num1 = 0;
private int num2 = 0;
private int result = 0;
private boolean isOpPressed = false;
private JPanel btnPl;
public Calculator() {
super();
jp = new JPanel();
jp.setLayout(new GridLayout(3, 3));
btnPl = new JPanel();
btnPl.setLayout(new GridLayout(4, 4));
jp.add(new JTextField());
jp.add(new JTextField());
jp.add(new JTextField());
jp.add(new JTextField());
jp.add(new JTextField());
jp.add(new JTextField());
arrBtn = new JButton[btnNames.length];
for (int i = 0; i < arrBtn.length; i++) {
arrBtn[i] = new JButton(btnNames[i]);
arrBtn[i].addActionListener(this);
btnPl.add(arrBtn[i]);
}
this.setLayout(new BorderLayout());
this.add(jp, BorderLayout.NORTH);
this.add(btnPl, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
}
public static void main(String args[]) {
new Calculator();
JFrame frame = new JFrame("Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RomanCalculator cal = new RomanCalculator();
frame.add(cal);
frame.pack();
frame.setSize(500, 500);
frame.setVisible(true);
}
}
I suggest first taking a looking at this, this, and this.
Here is how you should be creating a new TextField
JTextField textField = new JTextField();
You should then create a button and action listener similar to this
JButton someBtn = new JButton("Some Text");
someBtn.addActionListener(this);
Your ActionPerformed
#Override
public void actionPerformed(ActionEvent e) {
textField.setText("New Text");
}
If you would like to stay with the approach of using an Array of JButtons I suggest doing something similar.
String[] btnNames = {"1", "2", "3", etc.};
JButton[] allBtns = new JButton[10];
for(int i = 0; i < 10; i++){
allBtns[i] = new JButton(btnNames[i]);
allBtns[i].addActionListener(this);
//Using the previous actionPerformed
}
If you would like to customize what each button does you can do this
anyBtn.addActionListener(e -> textField.setText("Anything"));
Take a look at lambda's for more info.
the way I usually go about it in java is to have an inner class that handles the button clicks
public x extends JFrame(){
//I like to store my buttons in an array if possible.
JButton [] buttonArray = new JButton [2];
//instantialize each of the arrays buttons
buttonArray[0] = new JButton("hello");
buttonArray[1] = new JButton("world");
//create a listener of type buttonpress (currently undefined)
buttonPress Listener = new buttonPress();
//attach the button action listeners to the listener I created above.
buttonArray[0].addActionListener(Listener);
buttonArray[1].addActionListener(Listener);
//Create a private inner class called "buttonPress" which will handle the clicks for its listeners
private class buttonPress implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == buttonArray[0]){
try
{
..some logic
}
catch (Exception e1)
{
JOptionPane.showMessageDialog(null, e1.getMessage());
}
}
else if( e.getSource() == buttonArray[1])
{
...some other logic
}
}
}//close inner class
}//close outer class

How can i add two class that extends JPanel in One JFrame

I created two class that extends JPanel and want to add that two class in one Frame. But i am unable to do it. Anyone help please.
my classes are -->
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CalButton extends JPanel {
private JButton[] buttons;
private static final String[] buttonNames = { "7", "8", "9", "/", "4", "5",
"6", "*", "1", "2", "3", "-", "0", ".", "=", "+" };
private JPanel buttonPanel;
public CalButton() {
// TODO Auto-generated constructor stub
buttons = new JButton[buttonNames.length];
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 3, 3));
for(int i=0; i<buttonNames.length; i++){
buttons[i] = new JButton(buttonNames[i]);
buttonPanel.add(buttons[i]);
}
}
}
Another Class-->
import java.awt.GridLayout;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CalField extends JPanel {
private JPanel panelField;
private JTextField field;
public CalField() {
// TODO Auto-generated constructor stub
panelField = new JPanel();
panelField.setLayout(new GridLayout(1, 1,5,5));
field = new JTextField(20);
panelField.add(field);
}
}
Main class-->
public class Calculator {
public static void main(String[] args) {
JFrame application = new JFrame("Calculator");
CalField calField = new CalField();
CalButton calButton = new CalButton();
application.setLayout(new GridLayout(2, 1));
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.setSize(400, 450);
application.setVisible(true);
}
}
Anyone kindly solve this problem please. i'm stuck with this problem.
public CalButton() {
// TODO Auto-generated constructor stub
buttons = new JButton[buttonNames.length];
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 3, 3));
for(int i=0; i<buttonNames.length; i++){
buttons[i] = new JButton(buttonNames[i]);
buttonPanel.add(buttons[i]);
}
}
The CalButton class already "is a" JPanel because you extend JPanel so there is no need to create another JPanel. Just add your buttons to the class:
public CalButton() {
// TODO Auto-generated constructor stub
buttons = new JButton[buttonNames.length];
//buttonPanel = new JPanel();
//buttonPanel.setLayout(new GridLayout(4, 4, 3, 3));
setLayout(new GridLayout(4, 4, 3, 3));
for(int i=0; i<buttonNames.length; i++){
buttons[i] = new JButton(buttonNames[i]);
//buttonPanel.add(buttons[i]);
add(buttons[i]);
}
}
Same with your CalcField class except in this case you probably don't need to set the layout manager. You can probably use the default FlowLayout.
Then the second problem is that you never add these panels to the frame:
CalField calField = new CalField();
CalButton calButton = new CalButton();
//application.setLayout(new GridLayout(2, 1));
application.add(calField, BorderLayout.PAGE_START);
application.add(calButton, BorderLayout.CENTER);

Categories

Resources