can't get a simple layout in java - java

I am trying to make an GUI in java ,this is my first venture with GUI in java and I am trying to learn
Above is what I trying to create.But I simple can't get to design it in that way ,here is my code:
//Frame:
JFrame frame;
//Menu :
JMenuBar menuBar;
JMenu menu1,menu2;
JMenuItem menuItem;
//Panels:
JPanel topPanel;
JPanel centerPanel;
JPanel bpttomPanel;
String[] vTypeStrings = { "Select vehicle","Car", "Boat", "Truck", };
//Labels:
JLabel typeLabel;
//ComboBoxes:
JComboBox vList;;
//Frame creation
frame= new JFrame("frame1");
frame.setSize(450,250);
frame.setLocation(200,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3,1));
//Create the menu bar.
menuBar = new JMenuBar();
//Create menu bar items
menu1 = new JMenu("File");
menu1.setMnemonic('F');
menuBar.add(menu1);
menu2 = new JMenu("Help");
menu2.setMnemonic('H');
menuBar.add(menu2);
//Adding items to each menu
menuItem = new JMenuItem("Load", 'L');
menu1.add(menuItem);
menuItem = new JMenuItem("Exit", 'X');
menu1.add(menuItem);
//Second menu
menuItem = new JMenuItem("About",'A');
menu2.add(menuItem);
//Adding menu to frame
frame.setJMenuBar(menuBar);
//Top Panel
topPanel = new JPanel(new FlowLayout());
frame.add(topPanel,BorderLayout.NORTH);
JLabel headLabel=new JLabel("Snedden's Ordering system");//Heading label
topPanel.add(headLabel);
headLabel.setFont(new Font("Serif", Font.PLAIN, 24));
headLabel.setForeground(new Color(0xff0000));
//Center Panel
centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(2,2,2,2));
vList = new JComboBox(vTypeStrings);
vList.setSelectedIndex(0);
typeLabel=new JLabel("Vehicle Type");
typeLabel.setLabelFor(vList);
centerPanel.add(typeLabel);
centerPanel.add(vList);
frame.add(centerPanel,BorderLayout.CENTER);
frame.setVisible(true);
Here is what I get
THing is I get the label and the field on the same line, don't understand why,please help thanks.

frame.setLayout(new GridLayout(3,1));
This is your first mistake. The cells of a GridLayout are all the same size, while you want the central part to be higher.
frame.add(topPanel,BorderLayout.NORTH);
....
frame.add(centerPanel,BorderLayout.CENTER);
This is the second one, you set frame to have a GridLayout, so you shouldn't use BorderLayout constraints.
The correct thing to do, in my opinion, is to remove the first line, and leave the frame with the default border layout.
As for your issue with the grid, it's due to the fact that you're not filling the grid.
If you insert 4 controls in the grid, or initialize the grid with (1,2), you will get the expected outcome.
This is with centerPanel.setLayout(new GridLayout(1,2));:
And this is with `
centerPanel.add(typeLabel);
centerPanel.add(vList);
centerPanel.add(new JLabel());
centerPanel.add(new JLabel());

What about this:
import javax.swing.*;
import java.awt.*;
public class Gui extends JFrame {
public Gui()
{
super("Gui");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setLocationRelativeTo(null);
setVisible(true);
add(new Form(), BorderLayout.EAST);
add(new ButtonRow(), BorderLayout.SOUTH);
}
private class ButtonRow extends JPanel {
private JButton button1;
private JButton button2;
private JButton button3;
private JButton button4;
public ButtonRow()
{
setLayout(new FlowLayout());
button1 = new JButton("button 1");
button2 = new JButton("button 2");
button3 = new JButton("button 3");
button4 = new JButton("button 4");
add(button1);
add(button2);
add(button3);
add(button4);
}
}
public static void main(String args[])
{
new Gui();
}
private class Form extends JPanel {
String[] vTypeStrings = { "Select vehicle","Car", "Boat", "Truck", };
public Form()
{
setLayout(new VerticalLayout());
JComboBox vList = new JComboBox(vTypeStrings);
add(new Control("choose", vList));
add(new Control("label 1"));
add(new Control("label 2"));
add(new Control("label 3"));
add(new Control("label 4"));
}
}
private class Control extends JPanel {
private JLabel label;
private JTextField text;
public Control(String lbl)
{
label = new JLabel(lbl);
text = new JTextField(15);
setLayout(new FlowLayout());
add(label);
add(text);
}
public Control(String lbl, JComboBox list)
{
label = new JLabel(lbl);
setLayout(new FlowLayout());
add(label);
add(list);
}
}
}
I think you get the idea.
NOTE: I've used this VerticalLayout class.

Not good answers I see from others, now this one is good. Just type:
JPanel panel = new JPanel();
panel.setLayout(null);
And set the LOCATIONS and SIZES to the objects on the JPANEL and you can place them anywhere.

Related

Place label for text box above the box and not to the side

As stated in the title i need to move the label for the text box to be above the box and not to the side. attached i have a picutres of what i mean. what i have vs what i want i have tried searching for it but i cannot seem to find the answer im looking for/not exactly sure what to look up. I have tried using JFrame but it made a separate window unless i need to make the entire GUI a JFrame for me to get the result i want?
Also the actionPerformed method has things but it is irrelevant to the question but displays correctly still.
import java.awt.event.\*;
import javax.swing.\*;
import java.text.DecimalFormat;
public class Project4 extends JFrame implements ActionListener {
private JTextArea taArea = new JTextArea("", 30, 20);
ButtonGroup group = new ButtonGroup();
JTextField name = new JTextField(20);
boolean ch = false;
boolean pep = false;
boolean sup = false;
boolean veg = false;
DecimalFormat df = new DecimalFormat("##.00");
double cost = 0.0;
public Project4() {
initUI();
}
public final void initUI() {
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
getContentPane().add(panel1, "North");
getContentPane().add(panel2, "West");
getContentPane().add(panel3, "Center");
getContentPane().add(panel4, "East");
panel4.setLayout(new BoxLayout(panel4, BoxLayout.Y_AXIS));
getContentPane().add(panel5, "South");
JButton button = new JButton("Place Order");
button.addActionListener(this);
panel5.add(button);
JButton button2 = new JButton("Clear");
button2.addActionListener(this);
panel5.add(button2);
panel3.add(taArea);
JCheckBox checkBox1 = new JCheckBox("Cheese Pizza") ;
checkBox1.addActionListener(this);
panel4.add(checkBox1);
JCheckBox checkBox2 = new JCheckBox("Pepperoni Pizza");
checkBox2.addActionListener(this);
panel4.add(checkBox2);
JCheckBox checkBox3 = new JCheckBox("Supreme Pizza");
checkBox3.addActionListener(this);
panel4.add(checkBox3);
JCheckBox checkBox4 = new JCheckBox("Vegetarian Pizza");
checkBox4.addActionListener(this);
panel4.add(checkBox4);
JRadioButton radioButton1 = new JRadioButton("Pick Up");
group.add(radioButton1);
radioButton1.addActionListener(this);
panel1.add(radioButton1);
JRadioButton radioButton2 = new JRadioButton("Delivery");
group.add(radioButton2);
radioButton2.addActionListener(this);
panel1.add(radioButton2);
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
panel5.add(name_label);
panel5.add(name);
setSize(600, 300);
setTitle("Pizza to Order");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent action) {
}
public static void main(String[] args) {
Project4 ex = new Project4();
ex.setVisible(true);
}
}
You can use a nested JPanel with another layout in order to achieve that. I would go with BorderLayout here. You can also other layouts that allow vertical orientation. Visiting the visual guide to Layout Managers will help you spot them.
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
JPanel verticalNestedPanel = new JPanel(new BorderLayout());
verticalNestedPanel.add(name_label, BorderLayout.PAGE_START);
verticalNestedPanel.add(name, BorderLayout.PAGE_END);
panel5.add(verticalNestedPanel);

Using Layout Manager and JFrame, NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am attempting to create a basic grid layout in a tabbed pane with a menu bar.
The menu bar will have a basic File JMenu with an exit menuItem and a Color JMenu that will change the color of the font and background color.
One tab will calculate the PMT function as used in Excel.
The second tab will calculate Future Value as used in Excel.
The Final Tab is a simple help layout.
When trying to view the layout and basic functionality i receive a NullPointerException. The Exception seems to be called at line 208 ( which is where the TextArea will display the calculations for the PMT function ) at line 52 ( which is where createPage1() is called ) and at line 263 ( which is where mainframe is instantiated as Finance ).
The last of which i don't truly understand it purpose nor its functionality. This is a work in progress and no formulas have been added nor have all the actionListeners been added. The only thing I want now is to be able to view the Layout.
public class Finance extends JFrame{
private JTabbedPane tabPane;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenu colorMenu;
private JMenuItem exitItem;
private JRadioButtonMenuItem blueItem;
private JRadioButtonMenuItem blackItem;
private JRadioButtonMenuItem redItem;
private JRadioButtonMenuItem whiteItem;
private JRadioButtonMenuItem defItem;
private JButton calc1;
private JButton calc2;
TextArea text;
public Finance(){
setTitle("Finance");
setBackground(Color.GRAY);
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
createPage1();
createPage2();
createPage3();
tabPane = new JTabbedPane();
tabPane.addTab("Loan Payment", panel1);
tabPane.addTab("Future Value", panel2);
tabPane.addTab("Help", panel3);
topPanel.add(tabPane, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildMenuBar();
pack();
}
public void buildMenuBar(){
menuBar = new JMenuBar();
buildFileMenu();
buildColorMenu();
menuBar.add(fileMenu);
menuBar.add(colorMenu);
setJMenuBar(menuBar);
}
public void buildFileMenu(){
exitItem = new JMenuItem("Exit");
exitItem.setMnemonic(KeyEvent.VK_X);
exitItem.addActionListener(new ExitListener());
// Create a JMenu object for the File menu.
fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
// Add the Exit menu item to the File menu.
fileMenu.add(exitItem);
}
public void buildColorMenu(){
defItem = new JRadioButtonMenuItem("Deafult", true);
defItem.setMnemonic(KeyEvent.VK_D);
defItem.addActionListener(new ColorListener());
blueItem = new JRadioButtonMenuItem("Blue");
blueItem.setMnemonic(KeyEvent.VK_B);
blueItem.addActionListener(new ColorListener());
blackItem = new JRadioButtonMenuItem("Black");
blackItem.setMnemonic(KeyEvent.VK_L);
blackItem.addActionListener(new ColorListener());
whiteItem = new JRadioButtonMenuItem("White");
whiteItem.setMnemonic(KeyEvent.VK_W);
whiteItem.addActionListener(new ColorListener());
redItem = new JRadioButtonMenuItem("Red");
redItem.setMnemonic(KeyEvent.VK_R);
redItem.addActionListener(new ColorListener());
ButtonGroup group = new ButtonGroup();
group.add(blueItem);
group.add(blackItem);
group.add(whiteItem);
group.add(redItem);
colorMenu = new JMenu("Color");
colorMenu.setMnemonic(KeyEvent.VK_C);
colorMenu.add(defItem);
colorMenu.addSeparator();
colorMenu.add(blueItem);
colorMenu.add(blackItem);
colorMenu.add(whiteItem);
colorMenu.add(redItem);
}
private class ExitListener implements ActionListener{
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
private class ColorListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if(blackItem.isSelected()){
panel1.setForeground(Color.WHITE);
panel2.setForeground(Color.WHITE);
panel3.setForeground(Color.WHITE);
panel1.setBackground(Color.BLACK);
panel2.setBackground(Color.BLACK);
panel3.setBackground(Color.BLACK);
}
else if(redItem.isSelected()){
panel1.setForeground(Color.WHITE);
panel2.setForeground(Color.WHITE);
panel3.setForeground(Color.WHITE);
panel1.setBackground(Color.RED);
panel2.setBackground(Color.RED);
panel3.setBackground(Color.RED);
}
else if(whiteItem.isSelected()){
panel1.setForeground(Color.BLACK);
panel2.setForeground(Color.BLACK);
panel3.setForeground(Color.BLACK);
panel1.setBackground(Color.WHITE);
panel2.setBackground(Color.WHITE);
panel3.setBackground(Color.WHITE);
}
else if(blueItem.isSelected()){
panel1.setForeground(Color.WHITE);
panel2.setForeground(Color.WHITE);
panel3.setForeground(Color.WHITE);
panel1.setBackground(Color.BLUE);
panel2.setBackground(Color.BLUE);
panel3.setBackground(Color.BLUE);
}
else if(defItem.isSelected()){
panel1.setForeground(Color.GRAY);
panel2.setForeground(Color.GRAY);
panel3.setForeground(Color.GRAY);
panel1.setBackground(Color.BLACK);
panel2.setBackground(Color.BLACK);
panel3.setBackground(Color.BLACK);
}
}
}
public void createPage1(){
panel1 = new JPanel();
panel1.setLayout(new GridLayout(5, 2));
calc1 = new JButton("Calculate Payments");
JTextField loan = new JTextField();
JTextField months = new JTextField();
JTextField irp1 = new JTextField();
JTextField pymnt = new JTextField();
text = new TextArea();
panel1.add(new JLabel("Loan Amount:"));
panel1.add(loan);
panel1.add(new JLabel("Payment Length in Months:"));
panel1.add(months);
panel1.add(new JLabel("Interest Rate Percentage:"));
panel1.add(irp1);
panel1.add(new JLabel("Payment Amount (Fixed):"));
panel1.add(pymnt);
panel1.add(calc1);
panel2.add(text);
}
public void createPage2(){
panel2 = new JPanel();
panel2.setLayout(new GridLayout(5,2));
calc2 = new JButton("Calculate Future Value");
JTextField length = new JTextField();
JTextField value = new JTextField();
JTextField monthly = new JTextField();
JTextField irp2 = new JTextField();
JTextField fv = new JTextField();
panel2.add(new JLabel("Initial Value:"));
panel2.add(value);
panel2.add(new JLabel("Monthly Contribution:"));
panel2.add(monthly);
panel2.add(new JLabel("Interest Rate Percentage:"));
panel2.add(irp2);
panel2.add(new JLabel("Length in Years:"));
panel2.add(length);
panel1.add(calc2);
panel2.add(fv);
}
public void createPage3(){
panel3 = new JPanel();
panel3.setLayout(new GridLayout(3,3));
JButton button1 = new JButton("Input");
JButton button2 = new JButton("Output");
JButton button3 = new JButton("Input");
JButton button4 = new JButton("Output");
JButton button5 = new JButton("Navigation");
JButton button6 = new JButton("Information");
panel3.add(new JLabel("Loan Payment:"));
panel3.add(button1);
panel3.add(button2);
panel3.add(new JLabel("Future Value:"));
panel3.add(button3);
panel3.add(button4);
panel3.add(new JLabel("Basic Info:"));
panel3.add(button5);
panel3.add(button6);
}
public static void main(String args[]){
#SuppressWarnings("unused")
Finance mainFrame = new Finance();
}
The complete output is as follows:
Exception in thread "main" java.lang.NullPointerException
at Finance.createPage1(Finance.java:208)
at Finance.<init>(Finance.java:52)
at Finance.main(Finance.java:263)
All Help is welcome and appreciated. I am more looking for the reason of the error and general ways to fix it than for a specific solution. Feel free to be as judgmental of the coding as you wish, but if something can be simplified or altered please comment on how to do so.
At last statement of createPage1, panel2 is null. I guess you try to add text field to panel1. So, changed it to panel1 instead of panel2.
public void createPage1(){
panel1 = new JPanel();
panel1.setLayout(new GridLayout(5, 2));
.....
panel2.add(text); //Here panel2 is null, use panel1 instead.
}
In your last statement of createPage1(), you had what I believe is probably a typo. You used panel2 instead of panel1.
public void createPage1(){
panel1 = new JPanel();
...
panel2.add(text);
}
At that point in the code, panel2 had not been initialized yet which is why it threw a NullPointerException.

UPDATE THE EVENTS ARE NOT WORKING....

UPDATE UPDATE UPDATE
thank you :))) I did What u told me
I put frame.add(FirstScreen) first
they appeared .....
but now the events are not working , why???????
Can u help me again???
I'm sorry ........
..................
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class InterFace extends JFrame implements ActionListener,ItemListener
{
JFrame frame = new JFrame("Al-murshed Dictionary");
JPanel FirstScreen = new JPanel();
JPanel SecondScreen = new JPanel();
JPanel ThirdScreen = new JPanel();
JPanel ForthScreen = new JPanel();
JButton Translate = new JButton ("Translate");
JButton About = new JButton ("About");
JButton Help= new JButton ("Help");
JButton Quit= new JButton ("Quit");
JButton Quit1= new JButton ("Quit");
JButton Quit2= new JButton ("Quit");
JButton Back= new JButton ("Back");
JButton Back1= new JButton ("Back");
JTextField WordField = new JTextField("Write Your Word Here",50);
JTextArea ArbField = new JTextArea(40,40);
JTextArea EngField = new JTextArea(40,40);
CardLayout c1 = new CardLayout ();
public InterFace()
{
FirstScreen.setLayout(c1);
SecondScreen.add(WordField);
SecondScreen.add(Translate);
ThirdScreen.add(Back);
ForthScreen.add(Back1);
ThirdScreen.add(Quit1);
ForthScreen.add(Quit2);
FirstScreen.add(SecondScreen,"1");
FirstScreen.add(ThirdScreen,"2");
FirstScreen.add(ForthScreen,"3");
JPanel controlButtons = new JPanel();
controlButtons.add(Help);
controlButtons.add(About);
controlButtons.add(Quit);
JPanel wordTranslate = new JPanel();
wordTranslate.add(WordField);
wordTranslate.add(Translate);
JPanel controlTextArea = new JPanel();
controlTextArea.add(EngField);
controlTextArea.add(ArbField);
c1.show(FirstScreen,"1");
About.addActionListener(this);
Back.addActionListener(this);
Help.addActionListener(this);
Back1.addActionListener(this);
Quit.addActionListener(this);
Quit1.addActionListener(this);
Quit2.addActionListener(this);
frame.add(FirstScreen);
Container pane = frame.getContentPane();
pane.add(wordTranslate, BorderLayout.NORTH);
pane.add(controlTextArea, BorderLayout.CENTER);
pane.add(controlButtons, BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
//EventHandler
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==About)
c1.show(FirstScreen,"2");
if(e.getSource()==Help)
c1.show(FirstScreen,"3");
if(e.getSource()==Quit)
System.exit(0);
if(e.getSource()==Quit1)
System.exit(0);
if(e.getSource()==Quit2)
System.exit(0);
if(e.getSource()==Back)
c1.show(FirstScreen,"1");
if(e.getSource()==Back1)
c1.show(FirstScreen,"1");
}
public static void main (String args[])
{
InterFace d = new InterFace ();
}
}
pane.add(controlTextArea, BorderLayout.CENTER);
...
frame.add(FirstScreen);
First you add the text area panel to the content pane.
Then you add the "FirstScreen" to the frame.
The problem is that when you add the "FirstScreen" to the frame you are really adding it to the content pane of the frame. So basically you are replacing the text area panel with the first screen.
Also, follow Java naming conventions. Variable names should NOT start with an upper case character.

Java Swing JButton must create 4 new objects and add to JPanel

Okay, so when I press the JButton menuselect1, I want it to create 4 new objecs, attack1 2 3 and 4, and then add them to the JPanel fightmenu.
This is my code so far, it's a mini pokemon game.
First I create all my objects, and then I set the sizes and adds them to the different JPanels
public class MainFrame extends JFrame {
JPanel mainwindow = new JPanel();
JPanel bottom = new JPanel();
JPanel combat = new JPanel();
JPanel selectionmenu = new JPanel();
JPanel fightmenu = new JPanel();
JButton menuselect1 = new JButton("Fight");
JButton menuselect2 = new JButton("Minimons");
JButton menuselect3 = new JButton("Bag");
JButton menuselect4 = new JButton("Run");
JButton attack1 = new JButton("Tackle");
JButton attack2 = new JButton("Lightningbolt");
JButton attack3 = new JButton("Thunder-Shock");
JButton attack4 = new JButton("Hyper-Beam");
JButton poke1 = new JButton("Ekans");
JButton poke2 = new JButton("Pikachu");
public static void main(String[] args){
new MainFrame();
}
public MainFrame(){
super("MiniMon");
setSize(640,640);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(mainwindow);
// SIZES
combat.setPreferredSize(new Dimension(640,452));
bottom.setPreferredSize(new Dimension(640,160));
selectionmenu.setPreferredSize(new Dimension(320,160));
fightmenu.setPreferredSize(new Dimension(320,160));
mainwindow.setLayout(new BorderLayout());
mainwindow.add(combat, BorderLayout.NORTH);
mainwindow.add(bottom, BorderLayout.SOUTH);
combat.setLayout(new BorderLayout());
combat.add(poke1, BorderLayout.NORTH);
combat.add(poke2, BorderLayout.SOUTH);
bottom.setLayout(new BorderLayout());
bottom.add(selectionmenu, BorderLayout.EAST);
bottom.add(fightmenu, BorderLayout.WEST);
selectionmenu.setLayout(new GridLayout(2,2));
selectionmenu.add(menuselect1);
selectionmenu.add(menuselect2);
selectionmenu.add(menuselect3);
selectionmenu.add(menuselect4);
fightmenu.setLayout(new GridLayout(2,2));
setVisible(true);
}
}
I set up my fightmenu to use a 2x2 gridlayout, so I just need to add the 4 objects whenever I press the JButton menuselect1. I'm not really sure how to go about this. I know I should add an eventlistener, but when I tried, it did nothing at all.
I tried doing this:
fightmenu.setLayout(new GridLayout(2,2));
menuselect1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fightmenupress();
}
private void fightmenupress() {
fightmenu.add(attack1);
fightmenu.add(attack2);
fightmenu.add(attack3);
fightmenu.add(attack4);
}
} );
But it just did nothing.
When you add (or remove) components to a visible GUI, the basic code is:
panel.add(...);
panel.revalidate(); // to invoke the layout manager
panel.repaint(); // to repaint all the components on the panel
I added revalidate and repaint, and it worked!
private void fightmenupress() {
fightmenu.add(attack1);
fightmenu.add(attack2);
fightmenu.add(attack3);
fightmenu.add(attack4);
fightmenu.revalidate();
fightmenu.repaint();
}
} );

Not all components showing

When I run this program, the window blocks out the buttons in panel2 when I use setSize to determine window size.
In addition, if I use frame.pack() instead of setSize(), all components are on one horizontal line but I'm trying to get them so that panel1 components are on one line and panel2 components are on a line below them.
Could someone explain in detail the answers to both of these problems?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Exercise16_4 extends JFrame{
// FlowLayout components of top portion of calculator
private JLabel jlbNum1 = new JLabel("Number 1");
private JTextField jtfNum1 = new JTextField(4);
private JLabel jlNum2 = new JLabel("Number 2");
private JTextField jtfNum2 = new JTextField(4);
private JLabel jlbResult = new JLabel("Result");
private JTextField jtfResult = new JTextField(8);
// FlowLayout Components of bottom portion of calculator
private JButton jbtAdd = new JButton("Add");
private JButton jbtSubtract = new JButton("Subtract");
private JButton jbtMultiply = new JButton("Multiply");
private JButton jbtDivide = new JButton("Divide");
public Exercise16_4(){
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 3));
panel1.add(jlbNum1);
panel1.add(jtfNum1);
panel1.add(jlNum2);
panel1.add(jtfNum2);
panel1.add(jlbResult);
panel1.add(jtfResult);
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 10));
panel1.add(jbtAdd);
panel1.add(jbtSubtract);
panel1.add(jbtMultiply);
panel1.add(jbtDivide);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.CENTER);
}
public static void main(String[] args){
Exercise16_4 frame = new Exercise16_4();
frame.setTitle("Caculator");
frame.setSize(400, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setResizable(false);
frame.setVisible(true);
}
}
You're problem is likely a typographical error in that you're adding all components to panel1 and none to panel2:
// you create panel2 just fine
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 10));
// but you don't use it! Change below to panel2.
panel1.add(jbtAdd);
panel1.add(jbtSubtract);
panel1.add(jbtMultiply);
panel1.add(jbtDivide);
Add the buttons to panel2, and then call pack() before setVisible(true). Do not set the size of the GUI.

Categories