Using Layout Manager and JFrame, NullPointerException [duplicate] - java

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.

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);

Trying to layout JPanels. Java program layout changes every time I run

First time posting so go easy on me.
I am new to Java and am trying to get 3 JPanels to line up on top of each other. The first image is how I want it to look and it does sometimes when I run the program but as you can see by the other images it doesn't line up every time I run it. Sometimes not even showing some of the images/components.
So how can I get three JPanels to line up one after the other vertically?
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;
public class FrameMain {
static final int MY_MINIMUM = 0;
static final int MY_MAXIMUM = 100;
public static void main(String[] args) {
JFrame frame1 = new JFrame("Harvest Frame Test");
frame1.setVisible(true);
frame1.setSize(800,700);
frame1.setResizable(false);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Container Panel
JPanel container = new JPanel();
container.setSize(800,700);
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
frame1.add(container);
//First Panel
JPanel panel1 = new JPanel();
panel1.setAlignmentX( Component.LEFT_ALIGNMENT );//0.0
container.add(panel1);
JButton button1 = new JButton("Add Water");
panel1.add(button1);
JButton button2 = new JButton("Add Food");
panel1.add(button2);
JButton button3 = new JButton("Add Medicine");
panel1.add(button3);
ImageIcon image = new ImageIcon("C:/Users/Nick/Documents/EclipseArt/plant.gif");
JLabel imagelabel = new JLabel(image);
panel1.add(imagelabel);
JProgressBar pbar = new JProgressBar();
pbar.setMinimum(MY_MINIMUM);
pbar.setMaximum(MY_MAXIMUM);
// add to JPanel
panel1.add(pbar);
// Second Panel
JPanel panel2 = new JPanel();
panel2.setAlignmentX( Component.LEFT_ALIGNMENT );//0.0
container.add(panel2);
JButton button4 = new JButton("Add Water");
panel2.add(button4);
JButton button5 = new JButton("Add Food");
panel2.add(button5);
JButton button6 = new JButton("Add Medicine");
panel2.add(button6);
ImageIcon image1 = new ImageIcon("C:/Users/Nick/Documents/EclipseArt/plant.gif");
JLabel imagelabel1 = new JLabel(image1);
panel2.add(imagelabel1);
JProgressBar pbar1 = new JProgressBar();
pbar1.setMinimum(MY_MINIMUM);
pbar1.setMaximum(MY_MAXIMUM);
// add to JPanel
panel2.add(pbar1);
// Third Panel
JPanel panel3 = new JPanel();
panel3.setAlignmentX( Component.LEFT_ALIGNMENT );//0.0
container.add(panel3);
JButton button7 = new JButton("Add Water");
panel3.add(button7);
JButton button8 = new JButton("Add Food");
panel3.add(button8);
JButton button9 = new JButton("Add Medicine");
panel3.add(button9);
ImageIcon image2 = new ImageIcon("C:/Users/Nick/Documents/EclipseArt/plant.gif");
JLabel imagelabel2 = new JLabel(image2);
panel3.add(imagelabel2);
JProgressBar pbar2 = new JProgressBar();
pbar2.setMinimum(MY_MINIMUM);
pbar2.setMaximum(MY_MAXIMUM);
// add to JPanel
panel3.add(pbar2);
}
//static class Action implements ActionListener {
//public void actionPerformed (ActionEvent e){
//}
//}
}
Move the frame1.setVisible(true); all the way to the bottom. Changing Components on a frame that is already visible can cause issues.

Jpanel is not appearing in JFrame

So I am trying to get a JFrame to display a JPanel that has 5 other JPanels in it. I dont have any syntax errors and all that displays is a very small screen. I have been at this all day and have yet to find a solution.
public class addressPanel extends JPanel {
private JTextField nameT;
private JTextField addressT;
private JTextField cityT;
private JTextField stateT;
private JTextField zipCodeT;
private JTextField phoneNumberT;
private JLabel Title;
private JLabel addressTitle;
private JLabel nameL;
private JLabel addressL;
private JLabel stateL;
private JLabel cityL;
private JLabel zipCodeL;
private JLabel phoneNumberL;
private JLabel orderType;
private JRadioButton takeOut;
private JRadioButton delivery;
private JButton clear;
private JButton submit;
private JPanel addressTextPanel;
private JPanel addressLabelPanel;
private JPanel orderTypePanel;
private JPanel titlePanel;
private JPanel buttonsPanel;
public JPanel addressTextPanel() {
nameT = new JTextField(1);
addressT = new JTextField(2);
cityT = new JTextField(3);
stateT = new JTextField(4);
zipCodeT = new JTextField(5);
phoneNumberT = new JTextField(6);
Font font = new Font(Font.SERIF, Font.PLAIN, 24);
nameT.setFont(font);
addressT.setFont(font);
cityT.setFont(font);
stateT.setFont(font);
zipCodeT.setFont(font);
phoneNumberT.setFont(font);
JPanel addressTextPanel = new JPanel();
addressTextPanel.setPreferredSize(new Dimension(125, 250));
addressTextPanel.setLayout(new BoxLayout(addressTextPanel, BoxLayout.Y_AXIS));
addressTextPanel.add(nameT);
addressTextPanel.add(addressT);
addressTextPanel.add(cityT);
addressTextPanel.add(stateT);
addressTextPanel.add(zipCodeT);
addressTextPanel.add(phoneNumberT);
return addressTextPanel;
}
public JPanel addressLabelPanel() {
nameL = new JLabel("Name:");
addressL = new JLabel("Address:");
cityL = new JLabel("City:");
zipCodeL = new JLabel("Zip Code:");
stateL = new JLabel("State:");
phoneNumberL = new JLabel("Phone Number:");
nameL.setFont(nameL.getFont().deriveFont(24.0f));
addressL.setFont(addressL.getFont().deriveFont(24.0f));
cityL.setFont(cityL.getFont().deriveFont(24.0f));
zipCodeL.setFont(zipCodeL.getFont().deriveFont(24.0f));
stateL.setFont(stateL.getFont().deriveFont(24.0f));
phoneNumberL.setFont(phoneNumberL.getFont().deriveFont(24.0f));
JPanel addressLabelPanel = new JPanel();
addressLabelPanel.setPreferredSize(new Dimension(125, 250));
addressLabelPanel.setLayout(new BoxLayout(addressLabelPanel, BoxLayout.Y_AXIS));
addressLabelPanel.add(nameL);
addressLabelPanel.add(addressL);
addressLabelPanel.add(cityL);
addressLabelPanel.add(stateL);
addressLabelPanel.add(zipCodeL);
addressLabelPanel.add(phoneNumberL);
return addressLabelPanel;
}
public JPanel orderTypePanel() {
orderType = new JLabel("Order Type:");
takeOut = new JRadioButton("Take Out");
delivery = new JRadioButton("Delivery");
orderType.setFont(takeOut.getFont().deriveFont(24.0f));
takeOut.setFont(takeOut.getFont().deriveFont(24.0f));
delivery.setFont(delivery.getFont().deriveFont(24.0f));
JPanel orderTypePanel = new JPanel();
orderTypePanel.setPreferredSize(new Dimension(250, 125));
orderTypePanel.setLayout(new BoxLayout(orderTypePanel, BoxLayout.Y_AXIS));
orderTypePanel.add(orderType);
orderTypePanel.add(takeOut);
orderTypePanel.add(delivery);
return orderTypePanel;
}
public JPanel titlePanel() {
Title = new JLabel("Pizza Order Form");
addressTitle = new JLabel("Address");
Title.setFont(Title.getFont().deriveFont(36.0f));
addressTitle.setFont(addressTitle.getFont().deriveFont(36.0f));
JPanel titlePanel = new JPanel();
titlePanel.setPreferredSize(new Dimension(500, 100));
titlePanel.setLayout(new BoxLayout(titlePanel, BoxLayout.Y_AXIS));
titlePanel.add(Title);
titlePanel.add(addressTitle);
return titlePanel;
}
public JPanel buttonsPanel() {
clear = new JButton("Clear");
submit = new JButton("Submit");
clear.setFont(clear.getFont().deriveFont(24.0f));
submit.setFont(submit.getFont().deriveFont(24.0f));
JPanel buttonsPanel = new JPanel();
buttonsPanel.setPreferredSize(new Dimension(500, 100));
buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS));
buttonsPanel.add(clear);
buttonsPanel.add(submit);
return buttonsPanel;
}
public addressPanel() {
JPanel addressParent = new JPanel(new BorderLayout());
addressParent.add(new titlePanel(), BorderLayout.NORTH);
addressParent.add(new orderTypePanel(), BorderLayout.WEST);
addressParent.add(new addressLabelPanel(), BorderLayout.CENTER);
addressParent.add(new addressTextPanel(), BorderLayout.EAST);
addressParent.add(new buttonsPanel(), BorderLayout.SOUTH);
}
public static void main(String[] args) {
// Create Main Panel
JFrame frame = new JFrame("");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.getContentPane().add(new addressPanel());
// Color background = new Color(238,233,191);
// frame.getContentPane().setBackground(background);
frame.pack();
frame.setVisible(true);
}
}
Read your code. The program creates a JFrame. It creates an instance of addressPanel (which should be named AddressPanel). ANd it adds this addressPanel instance to the frame conent pane.
Now what is added to the addressPanel? Nothing:
public addressPanel()
{
JPanel addressParent = new JPanel(new BorderLayout());
addressParent.add (new titlePanel(), BorderLayout.NORTH);
addressParent.add (new orderTypePanel(), BorderLayout.WEST);
addressParent.add (new addressLabelPanel(), BorderLayout.CENTER);
addressParent.add (new addressTextPanel(), BorderLayout.EAST);
addressParent.add (new buttonsPanel(), BorderLayout.SOUTH);
}
The constructor of addressPanel creates another panel (addressParent), adds plenty of things to this addressParent panel, but doesn't add anything to this, the addressPanel. So the addressPanel is empty.
Please respect the Java naming conventions to make your code readable. Classes start with an uppercase letter.

can't get a simple layout in 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.

Creating an ActionListener to search through TextArea of NotepadGUI using MVC

Here is the VIEW of my notepad application. I need to create a controller that searches through the textarea in the centerPanel. I have a JButton defined, as well as a textfield, and want the user to be able to type text into the field and press the button to highlight the searched text. I have all my ActionListeners defined in a new class.
public NotepadView() {
super();
//WINDOW
setSize (750,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Chad's Notepad");
setLocationRelativeTo(null);
setBackground(Color.BLACK);
//CENTER PANEL
centerPanel = new JPanel();
centerPanel.setLayout(new FlowLayout());
textArea = new JTextArea();
centerPanel.add(textArea);
add(centerPanel, BorderLayout.CENTER);
scrollPaneText = new JScrollPane(textArea);
add(scrollPaneText);
textArea.setLineWrap(true);
textArea.setFont(new Font("Garamond", Font.PLAIN, 18));
//BOTTOM PANEL
bottomPanel = new JPanel();
bottomPanel.setLayout(new GridLayout(1,2));
setButton = new JButton("Find");
textField = new JTextField("EnterText");
bottomPanel.add(setButton);
bottomPanel.add(textField);
add(bottomPanel, BorderLayout.SOUTH);
//MENU BAR
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
newItem = new JMenuItem("New");
openItem = new JMenuItem("Open");
saveItem = new JMenuItem("Save");
closeItem = new JMenuItem("Close");
menuBar.add(fileMenu);
fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(closeItem);
setJMenuBar(menuBar);
newItem.addActionListener(new NewMenuCommand(textArea));
openItem.addActionListener(new OpenMenuCommand(textArea));
closeItem.addActionListener(new QuitMenuCommand());
saveItem.addActionListener(new SaveMenuCommand(textArea));
}
}
//ActionListener new class for Button
public class ButtonCommand implements ActionListener {
private JTextArea textArea;
private String hText;
int ind = 0;
private String findString;
public ButtonCommand (JTextArea ta){
textArea = ta;
}
public void actionPerformed (ActionEvent e){
hText = textArea.getText();
findString=JOptionPane.showInputDialog(null,"Find what","Find",JOptionPane.INFORMATION_MESSAGE);
ind = hText.indexOf(findString,0);
textArea.setCaretPosition(ind);
textArea.setSelectionStart(ind);
int a = ind+findString.length();
textArea.setSelectionEnd(a);
}
}

Categories