So for school, we have to make 2 separate JFrames that interact with each other. From within the first JFrame, a button gets pressed which opens the second one, where a name, speed, and position can be filled in.
When pressing OK on the second JFrame, I save the filled-in text and numbers but I have no clue how to use them in the code of the first JFrame. I had tried to use a "getter" from the second JFrame to check in the first one if the "OK" button had been pressed. But this gets checked immediately after opening the window. That means it isn't true YET and it doesn't check it again.
CONTEXT:
We are forced to use 2 separate JFrame.
We are not allowed to add extra methods.
We are not allowed to change the constructor.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TourFrame extends JFrame implements ActionListener{
private Etappe etappe;
private JLabel jlAantal;
private JTextField jtfAantal;
private JButton knopPrint;
private JButton knopStap;
private JButton knopVoegFietsenToe;
private JButton knopVoegCustomFietsToe;
public TourFrame(Etappe etappe){
this.etappe = etappe;
setTitle("Tour de Windesheim: " + etappe.toString());
setSize(650, 550);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jlAantal = new JLabel("aantal:");
add(jlAantal);
jtfAantal = new JTextField(10);
add(jtfAantal);
knopPrint = new JButton("print");
add(knopPrint);
knopPrint.addActionListener(this);
knopStap = new JButton("stap");
add(knopStap);
knopStap.addActionListener(this);
knopVoegFietsenToe = new JButton("voeg fietsen toe");
add(knopVoegFietsenToe);
knopVoegFietsenToe.addActionListener(this);
knopVoegCustomFietsToe = new JButton("voeg custom fiets toe");
add(knopVoegCustomFietsToe);
knopVoegCustomFietsToe.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == knopPrint){
etappe.print();
} else if(e.getSource() == knopStap){
etappe.stap();
setTitle("Tour de Windesheim: " + etappe.toString());
} else if(e.getSource() == knopVoegFietsenToe){
try {
int aantal = Integer.parseInt(jtfAantal.getText());
for(int i = 0; aantal > i; i++){
Fiets tijdelijk = new Fiets();
etappe.voegDeelnemerToe(tijdelijk);
}
} catch (NumberFormatException nfe){
jlAantal.setText("Voer een getal in");
}
} else if(e.getSource() == knopVoegCustomFietsToe){
FietsDialoog fietsdialoog = new FietsDialoog();
}
}
}
The Second one looks as follwed:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FietsDialoog extends JFrame implements ActionListener {
private JLabel jlNaam;
private JTextField jtfNaam;
private JLabel jlStartPositie;
private JTextField jtfStartPositie;
private JLabel jlSnelheid;
private JTextField jtfSnelheid;
private JButton knopOk;
private JButton knopCancel;
private String naam;
private int startpositie;
private int snelheid;
private boolean ok;
private boolean cancel;
public FietsDialoog(){
setTitle("FietsDialoog");
setSize(600, 100);
setLayout(new FlowLayout());
setDefaultCloseOperation(HIDE_ON_CLOSE);
jlNaam = new JLabel("naam");
add(jlNaam);
jtfNaam = new JTextField(10);
add(jtfNaam);
jlStartPositie = new JLabel("startpositie");
add(jlStartPositie);
jtfStartPositie = new JTextField(10);
add(jtfStartPositie);
jlSnelheid = new JLabel("snelheid");
add(jlSnelheid);
jtfSnelheid = new JTextField(10);
add(jtfSnelheid);
knopOk = new JButton("ok");
add(knopOk);
knopOk.addActionListener(this);
knopCancel = new JButton("cancel");
add(knopCancel);
knopCancel.addActionListener(this);
setVisible(true);
}
public String getNaam() {
return naam;
}
public int getStartpositie() {
return startpositie;
}
public int getSnelheid() {
return snelheid;
}
public boolean isOk() {
return ok;
}
public boolean isCancel() {
return cancel;
}
public JButton getKnopOk() {
return knopOk;
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == knopOk){
this.naam = jtfNaam.getText();
this.startpositie = Integer.parseInt(jtfStartPositie.getText());
this.snelheid = Integer.parseInt(jtfSnelheid.getText());
this.ok = true;
this.cancel = false;
} else if(e.getSource() == knopCancel){
this.ok = false;
this.cancel = true;
dispose();
}
}
}
Try and print fietsdialoog.getNaam(), fietsdialoog.getStartpositie()...etc, the getter from the fietsdialoog class after closing the window.
Also, rather than dispose the window: use setVisible to false. JFrame.setVisible(true/false);
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.
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));
}
}
}
}
I am trying to write a GUI temperature converter. It has one JTextField and two JButtons. TextField accepts the temperature which the user wants to convert and the user presses the appropriate button. Whenever I click on anyone of the buttons, I get a "Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String" error. Please Help!
public class tempcon extends JFrame {
private JPanel panel;
private JLabel messageLabel;
public JTextField tempC;
private JButton calcButton, calcButton1;
private final int WINDOW_WIDTH = 300;
private final int WINDOW_HEIGHT = 140;
public tempcon() {
setTitle("Temperature convertion");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
public double getTempC(){
return Double.parseDouble(tempC.getText());
}
private void buildPanel() {
tempC = new JTextField(10);
messageLabel = new JLabel("Enter tempurture");
calcButton = new JButton("Convert to Fahrenheit");
calcButton1 = new JButton("Convert to Celcius");
calcButton.addActionListener(new CalcButtonListener());
calcButton1.addActionListener(new CalcButtonListener1());
panel = new JPanel();
panel.add(messageLabel);
panel.add(tempC);
panel.add(calcButton);
panel.add(calcButton1);
}
public static void main(String[] args){
new tempcon().buildPanel();
}
}
class CalcButtonListener1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
double input;
double temp;
input = new tempcon().getTempC();
temp = input * 1.8 + 32;
JOptionPane.showMessageDialog(null, "That is " + temp + "
degrees Celsius.");
}
}
class CalcButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
double input;
double temp;
input = new tempcon().getTempC();
temp = (input - 32)*1.8;
JOptionPane.showMessageDialog(null, "That is " + temp + "
degrees Fehrenheit.");
}
public static void main(String[] args) {
tempcon myTempWindowInstance = new tempcon();
}
}
The problem is that you are recreating a new frame in your action listeners : new tempcon().getTempC() .
The textfields in these new frames are obviously empty and you get your error.
Consider referring to the same instance of tempcon everywhere, that is simply replace
new tempcon().getTempC();
with
getTempC();
, which will call the getTempC() method of the outer tempcon instance .
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.