Why does inherited methods only work for one class? - java

I am new to Java and programming in general and also new to Stack overflow. Im taking a course in object orientation and i am stuck at one assignment. Hope i can get some tips or feedback here.
I have written a fictive Banking program and now i am supposed to write an user interface.
The class SubMenuWindow have graphic components to draw a window in whitch i want to show all my Customers names and ID-numbers.
The Classes CustomerSubWindow and CreditAccountSubWindow inherits from SubMenuWindow since i want both of them to display the customers names and ID numbers.
When i create customer objects everthing works as its supossed to in the frame created from CustomerSubWindow, but the Frame created from CreditAccountWindow wont display the names and ID-numbers. Both inherit from the same parentclass, why dont they have the same behaviour?
I have tried to rewrite the code in different ways but the error persists. Can someone see what might be wrong?
I am aware that there are a bunch of formal convention errors (indentation, varabel names etc)
Here are the three classes:
First is the parent class:
public abstract class SubMenuWindow extends JFrame {
protected BankLogic bank = new BankLogic();
private JPanel customersDisplayPanel;
private JLabel customersDisplayLabel;
JTextArea customersDisplayText;
private GridBagLayout gridBag;
private GridBagConstraints customGrid;
private FlowLayout layout;
private JScrollPane scrollBarDisplayText;
private static final int TEXT_LENGTH = 30;
private static final int ROWS = 20;
private static final int COLUMNS = 50;
private static final int FRAME_HEIGHT = 900;
private static final int FRAME_WIDTH = 1600;
public SubMenuWindow(String title) {
super(title);
createComponents();
FlowLayout layout = new FlowLayout();
this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
this.setVisible(false);
this.setDefaultCloseOperation(HIDE_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setLayout(layout);//
this.add(customersDisplayPanel);
}
private void createComponents(){
gridBag = new GridBagLayout();
customGrid = new GridBagConstraints();
customersDisplayPanel = new JPanel(gridBag);
customersDisplayLabel = new JLabel("Within this frame you can find all
the Customers in the bank");
setCustomersDisplayText(new JTextArea(ROWS,COLUMNS));
scrollBarDisplayText = new JScrollPane(getCustomersDisplayText());
customGrid.gridx = 0;
customGrid.gridy = 1;
customersDisplayPanel.add(customersDisplayLabel, customGrid);
customGrid.gridx = 0;
customGrid.gridy = 2;
customersDisplayPanel.add(scrollBarDisplayText,customGrid);
}
public void createBankLogicCustomer(String firstNameString, String
surNameString, String pnumString ){
bank.createCustomer(firstNameString, surNameString, pnumString);
updateCustomersTextArea();
}
public void updateCustomersTextArea(){
customersDisplayText.setText("");
for(String customer : bank.getAllCustomers()){
customersDisplayText.append(customer + "\n");
}
}
public BankLogic getBank(){
return bank;
}
public static int getTextLength() {
return TEXT_LENGTH;
}
public JTextArea getCustomersDisplayText() {
return customersDisplayText;
}
public void setCustomersDisplayText(JTextArea customersDisplayText) {
this.customersDisplayText = customersDisplayText;
}
}
Second class
public class CustomerSubWindow extends SubMenuWindow {
private JPanel nameInputPanel;
private JTextField firstNameTextField;
private JTextField surNameTextField;
private JTextField pNumTextField;
private JLabel firstNameLabel;
private JLabel surNameLabel;
private JLabel pNumLabel;
private JButton finishButton;
private ActionListener createCustomerButtonPressed;
public CustomerSubWindow(String title) {
super(title);
createComponents();
this.add(nameInputPanel);
}
public void createComponents(){
nameInputPanel = new JPanel();
firstNameTextField = new JTextField(super.getTextLength());
surNameTextField= new JTextField(super.getTextLength());
pNumTextField= new JTextField(super.getTextLength());
firstNameLabel= new JLabel("First name: ");
surNameLabel= new JLabel("Surname: ");
pNumLabel= new JLabel("Person number: ");
finishButton = new JButton("Create customer");
createCustomerButtonPressed = new CustomerButtonListener();
finishButton.addActionListener(createCustomerButtonPressed);
nameInputPanel.add(firstNameLabel);
nameInputPanel.add(firstNameTextField);
nameInputPanel.add(surNameLabel);
nameInputPanel.add(surNameTextField);
nameInputPanel.add(pNumLabel);
nameInputPanel.add(pNumTextField);
nameInputPanel.add(finishButton);
}
private class CustomerButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent custButtonPressed){
if (custButtonPressed.getSource()==finishButton){
String firstNameString = firstNameTextField.getText();
String surNameString = surNameTextField.getText();
String pnumString = pNumTextField.getText();
createBankLogicCustomer(firstNameString, surNameString,
pnumString);
updateCustomersTextArea();
}
}
}
}
And finally the third Class
public class CreditAccountSubWindow extends SubMenuWindow {
private JPanel pNoInputPanel;
private JTextField pNoTextField;
private JLabel pNoLabel;
private JButton pNoButton;
private ActionListener createCreditAccountButtonPressed;
public CreditAccountSubWindow(String title)
super(title);
createComponents();
this.add(pNoInputPanel);
}
public void createComponents(){
pNoInputPanel = new JPanel();
pNoTextField = new JTextField(super.getTextLength());
pNoLabel = new JLabel("Input client ID number");
pNoButton = new JButton("Create Account");
createCreditAccountButtonPressed = new CreditAccButtonListener();
pNoButton.addActionListener(createCreditAccountButtonPressed);
pNoInputPanel.add(pNoLabel);
pNoInputPanel.add(pNoTextField);
pNoInputPanel.add(pNoButton);
}
private class CreditAccButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent creditAccButtonPressed){
if (creditAccButtonPressed.getSource()==pNoButton){
String pNo = pNoTextField.getText();
getBank().createCreditAccount(pNo);
System.out.println(getBank().createCreditAccount(pNo));
}
}
}
}

Related

Distance convertor issue

I can't obtain exact conversion due to unknown logical error. The program has three input fields. Where the user inputs desired value in desired field. Based on the entry and field of entry the data is converted.
package dist;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class DistanceConvertor extends JFrame
{
private JLabel KilometreLabel;
private JLabel MilesLabel;
private JLabel NauticalMilesLabel;
private JTextField KilometreTF;
private JTextField MilesTF;
private JTextField NauticalMilesTF;
private kiloHandler KilometreHandler;
private nauticalHandler NauticalMilesHandler;
private milesHandler MilesHandler;
private static final int WIDTH = 400;
private static final int HEIGHT = 100;
private static final double OFFSET = 0.0621;
private static final double OFFSET1 = 0.5399568;
public DistanceConvertor()
{
setTitle("Distance Convertor");
Container c = getContentPane();
c.setLayout(new GridLayout(3,4));
KilometreLabel = new JLabel("Distance in Kilometre:\n ",
SwingConstants.RIGHT);
MilesLabel = new JLabel("Distance in Miles: ",
SwingConstants.RIGHT);
NauticalMilesLabel = new JLabel("Distance in Nautical Miles: ",
SwingConstants.RIGHT);
KilometreTF = new JTextField(7);
MilesTF = new JTextField(7);
NauticalMilesTF = new JTextField(7);
c.add(KilometreLabel);
c.add(KilometreTF);
c.add(MilesLabel);
c.add(MilesTF);
c.add(NauticalMilesLabel);
c.add(NauticalMilesTF);
KilometreHandler = new kiloHandler();
MilesHandler = new milesHandler();
NauticalMilesHandler=new nauticalHandler();
KilometreTF.addActionListener(KilometreHandler);
MilesTF.addActionListener(MilesHandler);
NauticalMilesTF.addActionListener(NauticalMilesHandler);
setSize (WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class kiloHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double kilometre, miles,nauticalmiles;
kilometre =
Double.parseDouble(KilometreTF.getText());
nauticalmiles =
Double.parseDouble(NauticalMilesTF.getText());
miles = kilometre * OFFSET;
MilesTF.setText(String.format("%.4f", miles));
}
}
private class milesHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double kilometres, miles;
miles =
Double.parseDouble(MilesTF.getText());
kilometres = (miles / OFFSET) ;
KilometreTF.setText(String.format("%.4f", kilometres));
}
}
private class nauticalHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double kilometres, miles,nauticalmiles;
kilometres =
Double.parseDouble(KilometreTF.getText());
nauticalmiles= (kilometres / OFFSET1) ;
NauticalMilesTF.setText(String.format("%.4f", nauticalmiles));
}
}
public static void main(String[] args)
{
DistanceConvertor DistConv = new DistanceConvertor();
DistConv.setLocationRelativeTo(null);
}
}
When I enter any value in any of the three fields I want to get conversion value. But due to some error I don't get the converted value.

incompatible types - int cannot be converted in to java.lang.string -java - bluej [duplicate]

This question already has answers here:
How do I convert from int to String?
(20 answers)
Closed 4 years ago.
So as a part of java assignment - i am required to make CarRent Project - i am quite new to java - i am using blueJ - i am receiving an error that has confused me a bit - looking for some guidance
import java.util.ArrayList;
import java.util.ArrayList;
import java.awt.*;
import javax.swing.*;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.lang.String;
#author Mohsin
public class CarCompany implements ActionListener{
private JFrame frame;
private Container contentPane;
private JLabel descriptionLabel;
private JTextField descriptionTextField;
private JLabel downPayLabel;
private JTextField downPayTextField;
private JLabel dailyRateLabel;
private JTextField dailyRateTextField;
private JLabel priceLabel;
private JTextField priceTextField;
private JLabel yearOfRegLabel;
private JTextField yearOfRegTextField;
private JLabel mileageLabel;
private JTextField mileageTextField;
private JLabel customerNameLabel;
private JTextField customerNameTextField;
private JLabel dateOfHireLabel;
private JTextField dateOfHireTextField;
private JLabel dateOfReturnLabel;
private JTextField dateOfReturnTextField;
private JLabel numberOfDaysLabel;
private JTextField numberOfDaysTextField;
private JLabel carNumberLabel;
private JTextField carNumberTextField;
private JButton addCarToRentButton;
private JButton addCarToBuyButton;
private JButton clearButton;
private JButton displayAllButton;
private JButton rentCarButton;
private JButton sellCarButton;
private ArrayList <CAR>carList;
public static void main(String[] args){
CarCompany company = new CarCompany();
}
public CarCompany(){
carList = new ArrayList<CAR>()
frame = new JFrame("Car Company");
Container contentPane = frame.getContentPane();
contentPane.setLayout(new GridLayout(5,6));
JLabel descriptionLabel = new JLabel("Description"); //(1) the
description
contentPane.add(descriptionLabel);
contentPane.add(descriptionTextField);
JLabel downPayLabel = new JLabel("Down Payment"); //(2) the
down payment
contentPane.add(downPayLabel);
contentPane.add(downPayTextField);
JLabel dailyRateLabel = new JLabel("Daily Rate"); //(3) the
daily rate
contentPane.add(dailyRateLabel);
contentPane.add(dailyRateTextField);
JLabel priceLabel = new JLabel("Price"); //(4) the
price
contentPane.add(priceLabel);
contentPane.add(priceTextField);
JLabel yearOfRegLabel = new JLabel("Year Of Registration"); //(5) the
year of registration
contentPane.add(yearOfRegLabel);
contentPane.add(yearOfRegTextField);
JLabel mileageLabel = new JLabel("mileage"); //(6) the
mileage
contentPane.add(mileageLabel);
contentPane.add(mileageTextField);
JLabel customerNameLabel = new JLabel("Customer Name"); //(7) the
customer name
contentPane.add(customerNameLabel);
contentPane.add(customerNameTextField);
JLabel dateOfHireLabel = new JLabel("Date Of Hire"); //(8) the
date of hire
contentPane.add(dateOfHireLabel);
contentPane.add(dateOfHireTextField);
JLabel dateOfReturnLabel = new JLabel("Date Of Return"); //(9) the
date of return
contentPane.add(dateOfReturnLabel);
contentPane.add(dateOfReturnTextField);
JLabel numberOfDaysLabel = new JLabel("Number Of Days"); //(10) the
number of days
contentPane.add(numberOfDaysLabel);
contentPane.add(numberOfDaysTextField);
JLabel carNumberLabel = new JLabel("Car Number"); //(11) the
car number (its position in an array list of cars)
contentPane.add(carNumberLabel);
contentPane.add(carNumberTextField);
JButton addCarToRentButton = new JButton("Add Car To Rent");
contentPane.add(addCarToRentButton);
JButton addCarToBuyButton = new JButton("Add Car To Buy");
contentPane.add(addCarToBuyButton);
JButton rentCarButton = new JButton("Rent Car");
contentPane.add(rentCarButton);
JButton sellCarButton = new JButton("Sell Car");
contentPane.add(sellCarButton);
JButton clearButton = new JButton("Clear");
contentPane.add(clearButton);
JButton displayAllButton = new JButton("Display All Cars");
contentPane.add(displayAllButton);
frame.pack();
frame.setVisible(true);
clearButton.addActionListener(this);
addCarToRentButton.addActionListener(this);
addCarToBuyButton.addActionListener(this);
displayAllButton.addActionListener(this);
rentCarButton.addActionListener(this);
sellCarButton.addActionListener(this);
}
public void addCarToRent(){
CarToRent newCar = new CarToRent(descriptionTextField.getText(),
getDownPayment(),
getDailyRate());
carList.add(newCar);
}
/* Add Car To Sell
public void addCarToSell(){ //error is here getPrice -
CarToBuy newCar = new CarToBuy(getPrice(),getYearOfRegistration(),
getMileage(), descriptionTextField.getText());
carList.add(newCar);
}
public void rentCar(){
CarToRent thisCar;
thisCar = (CarToRent) carList.get(getCarNumber());
thisCar.rentCar(customerNameTextField.getText(),
dateOfHireTextField.getText(), dateOfReturnTextField.getText(),
getNumberOfDays());
}
/* Return a car
public void returnCar(){
CarToRent thisCar = (CarToRent) carList.get(getCarNumber());
thisCar.returnCar();
}
public void sellCar(){
CarToBuy thisCar = (CarToBuy) carList.get(getCarNumber());
if (carList.size() >= getCarNumber() && getCarNumber()>=0 && thisCar
instanceof CarToBuy){
thisCar = (CarToBuy) carList.get(getCarNumber());
thisCar.sellCar(customerNameTextField.getText());
}
}
public void displayAll(){ // Displays all the information relating to
properties is displayed
for (CAR thisCar: carList)
{
if (thisCar instanceof CarToRent){
CarToRent carToRent =(CarToRent)thisCar;
carToRent.displayDetails();
}
else if (thisCar instanceof CarToBuy){
CarToBuy carToBuy =(CarToBuy)thisCar;
carToBuy.displayDetails();
}
}
}
public void actionPerformed(ActionEvent event){
String command = event.getActionCommand();
if (command.equals("Add Car To Rent")){
addCarToRent();
}
else if (command.equals("Add Car To Buy")){
addCarToSell();
}
else if (command.equals("Clear")){
clear();
}
else if (command.equals("Display All Cars")){
displayAll();
}
else if (command.equals("Rent Car")){
rentCar();
}
else if (command.equals("Sell Car")){
sellCar();
}
}
public void clear(){ // Clears text from all eleven text fields
descriptionTextField.setText("");
downPayTextField.setText("");
dailyRateTextField.setText("");
priceTextField.setText("");
yearOfRegTextField.setText("");
mileageTextField.setText("");
customerNameTextField.setText("");
dateOfHireTextField.setText("");
dateOfReturnTextField.setText("");
numberOfDaysTextField.setText("");
carNumberTextField.setText("");
}
//*****accessors
public int getDailyRate(){
return Integer.parseInt(dailyRateTextField.getText());
}
public int getDownPayment(){
return Integer.parseInt(downPayTextField.getText());
}
public int getNumberOfDays(){
return Integer.parseInt(numberOfDaysTextField.getText());
}
public int getMileage(){
return Integer.parseInt(mileageTextField.getText());
}
public int getYearOfRegistration(){
return Integer.parseInt(yearOfRegTextField.getText());
}
public int getCarNumber(){
return Integer.parseInt(carNumberTextField.getText());
}
public int getPrice(){
return Integer.parseInt(priceTextField.getText());
}
}
just in case the code is to long to read : int cannot be converted into
java lang.String is the error when hovering over getPrice()
public void addCarToSell(){
CarToBuy newCar = new CarToBuy(getPrice(),getYearOfRegistration(),
getMileage(), descriptionTextField.getText());
carList.add(newCar);
}
The code of CarToBuy class cannot be seen but the first parameter of its constructor is probably String.
The return type of getPrice() is int.
To eliminate the problem either
change the return type of getPrice() to String (and remove integer parsing)
or change the constructor of CarToBuy to accept int instead of String
or change the constructor call to new CarToBuy(Integer.toString(getPrice()),getYearOfRegistration(),
getMileage(), descriptionTextField.getText());
the class CarToBuy seems to have no (accessible) constructor taking four parameters where the first is an int but one with a string as the first parameter. Either supply matching arguments or change the CarToBuy class accordingly, depending on which side is wrong.

Update JLabel text error [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm having some problems updating JLabel text. I have a AddCollection JDialog that calls it's controller and then updates the main view statusbar. However, when I apply the same technique to my AddHolding JDialog and controller I am getting a Null Pointer Exception. I have been at it for hours now, but can't see where I am going wrong. Is it something to do with my chaining?
Below is my code that relates to the problem at hand.
public class LMSDriver
{
public static void main(String[] args)
{
LMSModel model = new LMSFacade();
AddCollectionPanel colPanel = new AddCollectionPanel(model);
colPanel.setVisible(true);
}
}
public class AddCollectionPanel extends JDialog
{
private LMSModel model;
private AddCollectionController controller;
private LibraryView view;
private Box mainBox, hBox1, hBox2, hBox3;
private JLabel jlCode, jlTitle;
private JButton submitBtn;
private JTextField codeField;
private JTextField titleField;
public AddCollectionPanel(LMSModel model)
{
super();
this.model = model;
this.controller = new AddCollectionController(this);
setTitle("Add Collection");
setSize(300,160);
setLayout(new FlowLayout());
setLocationRelativeTo(null);
mainBox = Box.createVerticalBox();
hBox1 = Box.createHorizontalBox();
hBox2 = Box.createHorizontalBox();
hBox3 = Box.createHorizontalBox();
jlCode = new JLabel("Collection Code: ");
jlTitle = new JLabel("Collection Title: ");
codeField = new JTextField(10);
titleField = new JTextField(10);
submitBtn = new JButton("Submit");
submitBtn.addActionListener(controller);
hBox1.add(jlCode);
hBox1.add(Box.createHorizontalStrut(12));
hBox1.add(codeField);
hBox2.add(jlTitle);
hBox2.add(Box.createHorizontalStrut(10));
hBox2.add(titleField);
hBox3.add(Box.createHorizontalStrut(120));
hBox3.add(submitBtn);
mainBox.add(Box.createVerticalStrut(10));
mainBox.add(hBox1);
mainBox.add(Box.createVerticalStrut(10));
mainBox.add(hBox2);
mainBox.add(Box.createVerticalStrut(10));
mainBox.add(hBox3);
add(mainBox);
setVisible(true);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
this.view = new LibraryView(model);
}
public String getCodeField()
{
String codeText = new String(codeField.getText());
return codeText;
}
public void clearCodeField()
{
codeField.setText("");
}
public String getTitleField()
{
String titleText = new String(titleField.getText());
return titleText;
}
public void clearTitleField()
{
titleField.setText("");
}
public JButton getSubmitBtn()
{
return submitBtn;
}
public LMSModel getModel()
{
return model;
}
public AddCollectionController getController()
{
return controller;
}
public LibraryView getView()
{
return view;
}
}
public class AddCollectionController implements ActionListener
{
private AddCollectionPanel colPanel;
private LMSModel model;
private LibraryCollection lib;
private JLabel colCode;
private JLabel totalBooks;
private JLabel totalVideos;
public AddCollectionController(AddCollectionPanel collectionPanel)
{
this.colPanel = collectionPanel;
model = this.colPanel.getModel();
}
#Override
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == colPanel.getSubmitBtn())
{
lib = new LibraryCollection(colPanel.getCodeField(), colPanel.getTitleField());
model.addCollection(lib);
System.out.println(lib);
System.out.println(model.getCollection());
colCode = colPanel.getView().getLibraryStatusbar().getColCode();
colCode.setText("CollectionCode: " + colPanel.getCodeField() + " | ");
totalBooks = colPanel.getView().getLibraryStatusbar().getTotalBooks();
totalBooks.setText("Total Books: " + model.countBooks() + " | ");
totalVideos = colPanel.getView().getLibraryStatusbar().getTotalVideos();
totalVideos.setText("Total Videos: " + model.countVideos());
colPanel.dispose();
}
}
}
public class LibraryView extends JFrame
{
private LMSModel model;
private LibraryToolbar toolbar;
private LibraryPanel panel;
private LibraryStatusbar statusbar;
private LibraryMenu menu;
private LibraryViewController controller;
private AddCollectionPanel addCollectionPanel;
private AddBookPanel addBookPanel;
public LibraryView(LMSModel model)
{
this.model = model;
this.controller = new LibraryViewController(this);
toolbar = new LibraryToolbar(this);
panel = new LibraryPanel(this);
statusbar = new LibraryStatusbar(this);
menu = new LibraryMenu(this);
JFrame library = new JFrame("Library");
library.setSize(1024, 720);
library.setLayout(new BorderLayout(5,5));
library.setLocationRelativeTo(null);
library.add(toolbar, BorderLayout.WEST);
library.add(menu, BorderLayout.NORTH);
library.add(panel, BorderLayout.CENTER);
library.add(statusbar, BorderLayout.SOUTH);
library.setVisible(true);
library.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public LMSModel getModel()
{
return model;
}
public void setModel(LMSModel model)
{
this.model = model;
}
public LibraryMenu getLibraryMenu()
{
return menu;
}
public LibraryToolbar getLibraryToolbar()
{
return toolbar;
}
public LibraryPanel getLibraryPanel()
{
return panel;
}
public LibraryStatusbar getLibraryStatusbar()
{
return statusbar;
}
public LibraryViewController getController()
{
return controller;
}
public void setController(LibraryViewController controller)
{
this.controller = controller;
}
public AddCollectionPanel getAddCollectionPanel()
{
return addCollectionPanel;
}
public void setAddCollectionPanel(AddCollectionPanel addCollectionPanel)
{
this.addCollectionPanel = addCollectionPanel;
}
public AddBookPanel getAddBookPanel()
{
return addBookPanel;
}
public void setAddBookPanel(AddBookPanel addBookPanel)
{
this.addBookPanel = addBookPanel;
}
}
public class AddBookPanel extends JDialog
{
private LMSModel model;
private AddBookController controller;
private LibraryView view;
private Box mainBox, hBox1, hBox2, hBox3;
private JLabel jlCode, jlTitle;
private JButton addBookBtn;
private JTextField codeField;
private JTextField titleField;
public AddBookPanel(LMSModel model)
{
super();
this.model = model;
this.controller = new AddBookController(this);
setTitle("Add Book");
setSize(300,160);
setLayout(new FlowLayout());
setLocationRelativeTo(null);
mainBox = Box.createVerticalBox();
hBox1 = Box.createHorizontalBox();
hBox2 = Box.createHorizontalBox();
hBox3 = Box.createHorizontalBox();
jlCode = new JLabel("Book Code: ");
jlTitle = new JLabel("Book Title: ");
codeField = new JTextField(10);
titleField = new JTextField(10);
addBookBtn = new JButton("Add Book");
addBookBtn.addActionListener(controller);
hBox1.add(jlCode);
hBox1.add(Box.createHorizontalStrut(12));
hBox1.add(codeField);
hBox2.add(jlTitle);
hBox2.add(Box.createHorizontalStrut(10));
hBox2.add(titleField);
hBox3.add(Box.createHorizontalStrut(120));
hBox3.add(addBookBtn);
mainBox.add(Box.createVerticalStrut(10));
mainBox.add(hBox1);
mainBox.add(Box.createVerticalStrut(10));
mainBox.add(hBox2);
mainBox.add(Box.createVerticalStrut(10));
mainBox.add(hBox3);
add(mainBox);
setVisible(true);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
}
public String getCodeField()
{
String codeText = new String(codeField.getText());
return codeText;
}
public void clearCodeField()
{
codeField.setText("");
}
public String getTitleField()
{
String titleText = new String(titleField.getText());
return titleText;
}
public void clearTitleField()
{
titleField.setText("");
}
public JButton getAddBookBtn()
{
return addBookBtn;
}
public LMSModel getModel()
{
return model;
}
public AddBookController getController()
{
return controller;
}
public LibraryView getView()
{
return view;
}
}
public class AddBookController implements ActionListener {
private AddBookPanel bookPanel;
private LMSModel model;
private int code;
private LibraryView view;
private JLabel colCode;
private JLabel totalBooks;
private JLabel totalVideos;
public AddBookController(AddBookPanel bookPanel) {
this.bookPanel = bookPanel;
model = this.bookPanel.getModel();
}
#Override
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == bookPanel.getAddBookBtn())
{
code = Integer.parseInt(bookPanel.getCodeField().trim());
Holding h = new Book(code, bookPanel.getTitleField());
model.addHolding(h);
System.out.println(h);
colCode = bookPanel.getView().getLibraryStatusbar().getColCode();
colCode.setText("CollectionCode: " + bookPanel.getCodeField() + " | ");
totalBooks = bookPanel.getView().getLibraryStatusbar().getTotalBooks();
totalBooks.setText("Total Books: " + model.countBooks() + " | ");
totalVideos = bookPanel.getView().getLibraryStatusbar().getTotalVideos();
totalVideos.setText("Total Videos: " + model.countVideos());
bookPanel.dispose();
}
}
}
The problem is probably in all the methods where you are doing JLabel.setText. You probably need to first call the initialization method before setting the text. A NullPointerException exception happens when the object you are changing is null, and if you are getting a NullPointerException when you are changing the text of a JLabel, it means your JLabel is null.
I noticed you are using getters to initialize your objects...Don't... Why getters and setters are evil, but that's a topic that you should get into later. For now, you need to initialize your JLabel!
Look, there is a big difference between declaring and initializing variables. Here is the simplist way I can put it:
Object imAnObject; //Declaring
Now, because you didn't do:
Object imAnObject = new Object(); //Initializing
Then, imAnObject is still null! So obviously there will be a NullPointerException.
How to in initialize your JLabels:
So, right now, you only declare it by doing the following:
private JLabel jlCode, jlTitle;
But you never initialize jlCode or jlTitle. So, somewhere before you try changing the text
You need to initialize it. How?
jlCode = new JLabel();

How can I read a String array index from a JComboBox into a JLabel?

I have a ComboBox holding a String[]'s values. I have several other String[]'s holding numbers. I want the user to be able to select a item from the ComboBox(holding my String[] names) and according to which one they pick, I want that index associated with one of my other arrays to be printed out in a JLabel for display. Here's what I have so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class NewBuild extends JFrame
{
private static final int WIDTH = 900;
private static final int HEIGHT = 350;
//Create array constants
private static final String[] WARRIOR = {"7","6","6","5","15","11","5","5","5"};
private static final String[] KNIGHT = {"12","6","7","4","11","8","9","3","6"};
private static final String[] SWORDSMAN = {"4","8","4","6","9","16","6","7","5"};
private static final String[] BANDIT = {"9","7","11","2","9","14","3","1","8"};
private static final String[] CLERIC = {"10","3","8","10","11","5","4","4","12"};
private static final String[] SORCERER = {"5","6","5","12","3","7","8","14","4"};
private static final String[] EXPLORER = {"7","6","9","7","6","6","12","5","5"};
private static final String[] DEPRIVED = {"6","6","6","6","6","6","6","6","6"};
private static final String[] CLASS_NAMES = {" ", "Warrior", "Knight", "SwordsMan", "Bandit", "Cleric", "Sorcerer", "Explorer", "Deprived"};
private int num;
private int count = 0;
private String classes;
Container newBuildWindow = getContentPane();
private JLabel lblBuildName, lblStartingClass, lblDisplayStartingStats;
private JTextField txtBuildName;
private JComboBox cStartingClasses;
public NewBuild()
{
GUI();
}//End of Constructor
public void GUI()
{
this.setSize(WIDTH, HEIGHT);
newBuildWindow.setBackground(Color.DARK_GRAY);
setTitle("New Build");
setLayout(new GridLayout(5,2));
setVisible(true);
// setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
JPanel panel1 = new JPanel(new GridLayout());
JPanel panel2 = new JPanel(new GridLayout(2,3));
lblBuildName = new JLabel("Build Name");
lblBuildName.setForeground(Color.YELLOW);
panel1.setBackground(Color.DARK_GRAY);
panel1.add(lblBuildName);
txtBuildName = new JTextField(15);
txtBuildName.setBackground(Color.LIGHT_GRAY);
panel1.add(txtBuildName);
lblStartingClass = new JLabel("Pick a starting class:");
lblStartingClass.setForeground(Color.YELLOW);
lblDisplayStartingStats = new JLabel("Default");
lblDisplayStartingStats.setForeground(Color.YELLOW);
cStartingClasses = new JComboBox(CLASS_NAMES);
cStartingClasses.addItemListener(new itemChangeListener());
panel2.setBackground(Color.DARK_GRAY);
panel2.add(lblStartingClass);
panel2.add(cStartingClasses);
panel2.add(lblDisplayStartingStats);
//add panels to pane
newBuildWindow.add(panel1);
newBuildWindow.add(panel2);
// pack();
}//End of GUI method
class itemChangeListener implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
}
}
}
}//End of class NewBuild
Any help would be very much appreciated...Please don't just post a solution, I want to understand the code not copy it.
First, create a "wrapper" class which can bind the String values to a particular name (before anyone rushes at me says you can use a Map of some kind, you could, but this "carries" the associated information within a neat package)
public class ClassType {
private String description;
private String[] values;
public ClassType(String description, String[] values) {
this.description = description;
this.values = values;
}
public String[] getValues() {
return values;
}
#Override
public String toString() {
return description;
}
}
Build an array of these ClassTypes and give this to the JComboBox
ClassType[] types = new ClassType[]{
new ClassType("Warrior", WARRIOR),
new ClassType("Knight", KNIGHT),
new ClassType("Swordsman", SWORDSMAN),
new ClassType("Bandit", BANDIT),
new ClassType("Cleric", CLERIC),
new ClassType("Socerer", SORCERER),
new ClassType("Explorer", EXPLORER),
new ClassType("Deprived", DEPRIVED)
};
cStartingClasses = new JComboBox(types);
And when the ItemListener is notified, extract the values from the selected item...
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
ClassType classType = (ClassType) ((JComboBox)e.getSource()).getSelectedItem();
if (classType != null) {
String values[] = classType.getValues();
}
}
}
You can get the index and item as:
public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
int index = cStartingClasses.getSelectedIndex();
String item = String.valueOf(cStartingClasses.getSelectedItem());
}
}
Here cStartingClasses is JcomboBox.

ArrayList prints out a code from gui

I am having some serious trouble.
My program that I have to write is a GUI that essentially asks for:
A Course (ex: cpsc130)
The name (ex: computer programming 2)
The amount of credits you receive for the class (ex 3)
And your grade (ex A, B).
I'm not very good with ActionListeners, escentially I have no idea what I'm doing with it. I have to make an ArrayList for the information
One ArrayList<Course> (instance variable) e.g. courseList, to store the courses you add;
Four inner ActionListener classes, with each of them implements its method of
actionPerformed. Specically,
AddCourseListener: read the inputs and create a course object, add the course
object into the courseList, and append this into the output area;
CalGPAListener: read all course credits and grades from the courseList, add
them up and compute the overall GPA. You are assuming that A is 4, B is 3, C is 2,
D is 1, and E is 0. GPA = Sum(creditpoint)=totalCredits. For instance (Figure
1), you have taken 3 courses: 130 (3 credits, grade of A), 131 ( 3 credits, grade of
B), and 370 (4 credits, grade of B), then your GPA = (3*4+3*3+4*3)/(3+3+4)
= 3.3.
ResetInputListener: reset all input elds;
ResetOutputListener: reset output area.
Those are all the ActionListeners I need. I will show you my code so far. When compiled it will show all the Buttons and TextAreas, the ActionListeners are the only thing I need help with.
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class DegreeWorksFrame extends JFrame {
private JLabel courseCodeLabel;
private JTextField courseCodeField;
private JLabel courseNameLabel;
private JTextField courseNameField;
private JLabel courseCreditLabel;
private JTextField courseCreditField;
private JLabel courseGradeLabel;
private JTextField courseGradeField;
private JTextArea resultArea;
private double sum =0;
private double totalCredits=0;
private String code = "";
private String name = "";
private String credit = "";
private String grade = "";
private String heading = ("Code\tName\tCredit\tGrade" + "\n");
private ArrayList<Course> courseList;
private JButton AddCourse;
private JButton CalculateGPA;
private JButton ResetInput;
private JButton ResetOutput;
private static final int AREA_ROWS = 15;
private static final int AREA_COLUMNS = 35;
private final int FRAME_HEIGHT =400;
private final int FRAME_WIDTH = 500;
final int FIELD_WIDTH = 30;
public DegreeWorksFrame() {
resultArea = new JTextArea(AREA_ROWS, AREA_COLUMNS);
resultArea.setText(heading);
resultArea.setEditable(false);
createTextField1();
createTextField2();
createTextField3();
createTextField4();
createButtonAddCourse();
createButtonCalculateGPA();
createButtonResetInput();
createButtonResetOutput();
createPanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void createTextField1() {
courseCodeLabel = new JLabel("Enter Course Code: ");
courseCodeField = new JTextField(FIELD_WIDTH);
courseCodeField.setText(code);
}
private void createTextField2() {
courseNameLabel = new JLabel("Enter Course Name: ");
courseNameField = new JTextField(FIELD_WIDTH);
courseNameField.setText(name);
}
private void createTextField3() {
courseCreditLabel = new JLabel("Enter Course Credit: ");
courseCreditField = new JTextField(FIELD_WIDTH);
courseCreditField.setText(credit);
}
private void createTextField4() {
courseGradeLabel = new JLabel("Enter Course Grade: ");
courseGradeField = new JTextField(FIELD_WIDTH);
courseGradeField.setText(grade);
}
private void createButtonAddCourse() {
AddCourse = new JButton ("Add Courses: ");
ActionListener listener = new addCourseListener();
AddCourse.addActionListener(listener);
}
class addCourseListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
courseList = new ArrayList();
String receiveList = userList.get
}
}
private void createButtonCalculateGPA() {
CalculateGPA = new JButton ("Calculate GPA");
ActionListener listener = new addCourseListener();
AddCourse.addActionListener(listener);
}
class calculateGPAListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
}
}
private void createButtonResetInput() {
ResetInput = new JButton ("Reset Input");
ActionListener listener = new addCourseListener();
AddCourse.addActionListener(listener);
}
class resetInputListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
}
}
private void createButtonResetOutput() {
ResetOutput = new JButton ("Reset Output");
ActionListener listener = new addCourseListener();
AddCourse.addActionListener(listener);
}
class resetOutputListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
}
}
private void createPanel() {
JPanel panel = new JPanel();
panel.add(courseCodeLabel);
panel.add(courseCodeField);
panel.add(courseNameLabel);
panel.add(courseNameField);
panel.add(courseCreditLabel);
panel.add(courseCreditField);
panel.add(courseGradeLabel);
panel.add(courseGradeField);
//buttons
panel.add(AddCourse);
panel.add(CalculateGPA);
panel.add(ResetInput);
panel.add(ResetOutput);
//Scroll bar
JScrollPane scrollPane = new JScrollPane(resultArea);
panel.add(scrollPane);
add(panel);
}
}
Side-note: Note you're adding multiple listeners to your AddCourse button which is not correct. You need to add the listeners to the proper buttons.
As stated in this answer a good approach to implement listeners is by using Anonymous Inner classes (see the linked answer for a better explanation about why).
For instance:
private void createButtonAddCourse() {
AddCourse = new JButton ("Add Courses: ");
AddCourse.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Create a new Course object and add it to the ArrayList here
}
});
}
...
private void createButtonCalculateGPA() {
CalculateGPA = new JButton ("Calculate GPA");
CalculateGPA.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Iterate over the ArrayList and calculate the overall GPA for each course
}
});
}
Suggested readings
Anonymous Classes
Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods
in Java
Swing?
Using Layout
Managers

Categories