Getting textfile in a combobox - java

I haven't used comboBox much in java before and I'm having a bit of trouble getting my textfile to appear. I believe I have the files load correctly but it seems like I'm finding difficult to implement it in the code. I do have multiple movie names in the textfile. and when selecting a different movie in the combo box it changes the price,rating etc...
I did this correctly once using an initialize array.
example of the textfile[Taken,PG-13,8:00Am, 7,50
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;
import javax.swing.*;
public class MovieSelection extends JFrame {
private JPanel ratingPanel;
private JPanel panel;
private JLabel priceLabel;
private JLabel label;
private JButton addCart;
private JButton backButton;
private JButton resetButton;
private JTextField selectedRatingPanel;
private JTextField amountTextField;
private JComboBox movieBox;
private ArrayList<String> movieName;
private ArrayList<String> movieRating;
private ArrayList<String> movieTime;
private ArrayList<String> moviePrice;
public MovieSelection() {
super("Please select your movie");
setSize(575,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
buildMoviePanel();
buildRatingPanel();
add(panel);
setVisible(true);
movieName = new ArrayList<>();
movieRating = new ArrayList<>();
movieTime = new ArrayList<>();
moviePrice = new ArrayList<>();
}
private void readMovies() {
Scanner input=null;
try{
input = new Scanner(new File("TheMovies.txt"));
while(input.hasNext()){
String str = input.nextLine();
StringTokenizer strT = new StringTokenizer(str, ",");
movieName.add(strT.nextToken());
movieRating.add(strT.nextToken());
moviePrice.add(strT.nextToken());
movieTime.add(strT.nextToken());
}
}
catch(Exception element){
input.close();
JOptionPane.showMessageDialog(null, "Error");
}
}
private void buildMoviePanel() {
panel = new JPanel();
priceLabel = new JLabel("Cost:");
backButton = new JButton("Back");
resetButton = new JButton("Rest");
backButton.addActionListener(new BackButton());
resetButton.addActionListener(new ResetButton());
addCart = new JButton("Add to cart");
JTextField totalTextField = new JTextField(10);
JTextField priceTextField = new JTextField(5);
JTextField amountTextField = new JTextField(4);
priceTextField.setEditable(false);
priceTextField.setText(moviePrice);
totalTextField.setEditable(false);
JComboBox movieLists = new JComboBox(movieName);
movieLists.setSelectedIndex(0);
movieLists.addActionListener(new MovieLists());
panel.add(movieLists).setBounds(20,52,80,40);
panel.add(priceLabel).setBounds(375,0,80,40);
panel.add(priceTextField).setBounds(375,52,75,40);
panel.add(backButton).setBounds(20,310,80,40);
panel.add(addCart).setBounds(380,310,100,40);
panel.add(resetButton).setBounds(200, 310, 80, 40);
panel.add(amountTextField);
panel.setLayout(null);
}//buildPanel
private void buildRatingPanel(){
ratingPanel = new JPanel();
label = new JLabel("Rating:");
selectedRatingPanel = new JTextField(9);
selectedRatingPanel.setEditable(false);
selectedRatingPanel.setText("R");
panel.add(label).setBounds(245, 0, 100,40);
panel.add(selectedRatingPanel).setBounds(245,52,100,40);
}
private class MovieLists implements ActionListener {
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
String theMovie = (String) cb.getSelectedItem();
System.out.println(cb.getSelectedIndex());
}
}
private class BackButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
// return back to home page
if (e.getSource() == backButton)
new SelectUserWindow();
setVisible(false);
}
}
private class ResetButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
// return back to home page
if (e.getSource() == resetButton);
}
}
}

Learn to use layout managers
JComboBox does not take an ArrayList (or Collection) as a viable parameter (it can take Object[] or Vector)
movieName, movieRating, movieTime, moviePrice are all uninitialised when you create the UI because you initialise them AFTER the creation of the UI.
JTextField#setText does not take an ArrayList as a viable parameter
Learn to read the output of your application from the console or IDE
Learn to use a debugger - it will save you many hours of frustration and annoyance ;)

Related

StackOverflowError when adding JTextField to the constructor

So I do know what an StackOverflowError is, the problem however is I can't find it here. I am supposed to make a simple GUI with labels, text fields and buttons. One of these buttons is supposed to "clear" the text fields, so I add that by putting text field as an argument in the constructor, but when I actually add the text fields i just get an stack overflow error. Here is the code:
Orders class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Orders extends JFrame {
public Orders() {
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(4, 2, 2, 2));
JLabel name = new JLabel("Item name:");
JLabel number = new JLabel("Number of:");
JLabel cost = new JLabel("Cost:");
JLabel amount = new JLabel("Amount owed:");
JTextField nameJtf = new JTextField(10);
JTextField numberJtf = new JTextField(10);
JTextField costJtf = new JTextField(10);
JTextField amountJtf = new JTextField(10);
panel1.add(name);
panel1.add(nameJtf);
panel1.add(number);
panel1.add(numberJtf);
panel1.add(cost);
panel1.add(costJtf);
panel1.add(amount);
panel1.add(amountJtf);
JPanel panel2 = new JPanel();
JButton calculate = new JButton("Calculate");
JButton save = new JButton("Save");
JButton clear = new JButton("Clear");
JButton exit = new JButton("Exit");
panel2.add(calculate);
panel2.add(save);
panel2.add(clear);
panel2.add(exit);
OnClick action = new OnClick(exit, clear, save, calculate, nameJtf, numberJtf, costJtf, amountJtf);
exit.addActionListener(action);
this.setTitle("Otto's Items Orders Calculator");
this.add(panel1, BorderLayout.NORTH);
this.add(panel2, BorderLayout.SOUTH);
this.setSize(400, 200);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
new Orders();
}
}
OnClick class :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class OnClick extends Orders implements ActionListener {
private JButton exitModify = null;
private JButton clearModify = null;
private JButton saveModify = null;
private JButton calculateModify = null;
private JTextField nameModify = null;
private JTextField numberModify = null;
private JTextField costModify = null;
private JTextField amountModify = null;
public OnClick (JButton _exitModify, JButton _clearModify, JButton _saveModify, JButton _calculateModify, JTextField _nameModify, JTextField _numberModify, JTextField _costModify, JTextField _amountModify) {
exitModify = _exitModify;
clearModify = _clearModify;
saveModify = _saveModify;
calculateModify = _calculateModify;
nameModify = _nameModify;
numberModify = _numberModify;
costModify = _numberModify;
amountModify = _amountModify;
}
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o == this.exitModify) {
System.exit(0);
} else if (o == this.clearModify) {
amountModify = null;
nameModify = null;
costModify = null;
numberModify = null;
}
}
}
As soon as I add nameJtf I get this error.

formatting JTextfields using another class

this is the code of the Gui Design class and below is the Class that provides functionality to the program. Im trying to get user input from the textfields so i can remove the text using the clearAll method and also save user input using the saveit method.I tried using nameEntry.setText(""); in the clearAll method but it wont work can someone help me please!
//Import Statements
import javax.swing.*;
import java.awt.*;
import javax.swing.JOptionPane;
import java.awt.event.*;
//Class Name
public class Customer extends JFrame {
Function fun = new Function();
public static void main(String[]args){
Customer.setLookAndFeel();
Customer cust = new Customer();
}
public Customer(){
super("Resident Details");
setSize(500,500);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
FlowLayout two = new FlowLayout(FlowLayout.LEFT);
setLayout(two);
JPanel row1 = new JPanel();
JLabel name = new JLabel("First Name",JLabel.LEFT);
JTextField nameEntry = new JTextField("",20);
row1.add(name);
row1.add(nameEntry);
add(row1);
JPanel row2 = new JPanel();
JLabel surname = new JLabel("Surname ",JLabel.LEFT);
JTextField surnameEntry = new JTextField("",20);
row2.add(surname);
row2.add(surnameEntry);
add(row2);
JPanel row3 = new JPanel();
JLabel contact1 = new JLabel("Contact Details : Email ",JLabel.LEFT);
JTextField contact1Entry = new JTextField("",10);
FlowLayout newflow = new FlowLayout(FlowLayout.LEFT,10,30);
setLayout(newflow);
row3.add(contact1);
row3.add(contact1Entry);
add(row3);
JPanel row4 = new JPanel();
JLabel contact2 = new JLabel("Contact Details : Phone Number",JLabel.LEFT);
JTextField contact2Entry = new JTextField("",10);
row4.add(contact2);
row4.add(contact2Entry);
add(row4);
JPanel row5 = new JPanel();
JLabel time = new JLabel("Duration Of Stay ",JLabel.LEFT);
JTextField timeEntry = new JTextField("",10);
row5.add(time);
row5.add(timeEntry);
add(row5);
JPanel row6 = new JPanel();
JComboBox<String> type = new JComboBox<String>();
type.addItem("Type Of Room");
type.addItem("Single Room");
type.addItem("Double Room");
type.addItem("VIP Room");
row6.add(type);
add(row6);
JPanel row7 = new JPanel();
FlowLayout amt = new FlowLayout(FlowLayout.LEFT,100,10);
setLayout(amt);
JLabel amount = new JLabel("Amount Per Day ");
JTextField AmountField = new JTextField("\u20ac ",10);
row7.add(amount);
row7.add(AmountField);
add(row7);
JPanel row8 = new JPanel();
FlowLayout prc = new FlowLayout(FlowLayout.LEFT,100,10);
setLayout(prc);
JLabel price = new JLabel("Total Price ");
JTextField priceField = new JTextField("\u20ac ",10);
row8.add(price);
row8.add(priceField);
add(row8);
JPanel row9 = new JPanel();
JButton clear = new JButton("Clear");
row9.add(clear);
add(row9);
JPanel row10 = new JPanel();
JButton save = new JButton("Save");
save.addActionListener(fun);
row10.add(save);
add(row10);
//Adding ActionListners
nameEntry.addActionListener(fun);
clear.addActionListener(fun);
save.addActionListener(fun);
setVisible(true);
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore error
}
}
}
//Import Statements
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import javax.swing.JOptionPane;
import java.awt.event.*;
//Class Name
public class Function implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("Add Customer")) {
Login();
}
else if(command.equals("Register")){
Registration();
}
else if(command.equals("Exit")){
System.exit(0);
}
else if(command.equals("Clear")){
ClearAllFields();
}
else if(command.equals("Save")){
SaveIt();
}
}
public static void Login(){
Customer cust = new Customer();
}
public static void Registration(){
//Do Nothing
}
//This clears all the text from the JTextFields
public static void ClearAllFields(){
}
//This will save Info on to another Class
public static void SaveIt(){
}
}
Alternatively, you can make nameEntry known to the Function class by defining it before calling the constructor for Function and then passing it into the constructor, like:
JTextField nameEntry = new JTextField("",20);
Function fun = new Function(nameEntry);
Then, in Function, add nameEntry as a member variable of Function and make a constructor for Function which accepts nameEntry, (right after the "public class Function..." line), like:
JTextField nameEntry;
public Function(JTextField nameEntry) {
this.nameEntry = nameEntry;
}
Now, the following will compile:
public void ClearAllFields(){
nameEntry.setText("");
}
And, the Clear button will clear the name field.
Again as per comments, one simple way to solve this is to give the gui public methods that the controller (the listener) can call, and then pass the current displayed instance of the GUI into the listener, allowing it to call any public methods that the GUI might have. The code below is simpler than yours, having just one JTextField, but it serves to illustrate the point:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class GUI extends JPanel {
private JTextField textField = new JTextField(10);
private JButton clearButton = new JButton("Clear");
public GUI() {
// pass **this** into the listener class
MyListener myListener = new MyListener(this);
clearButton.addActionListener(myListener);
clearButton.setMnemonic(KeyEvent.VK_C);
add(textField);
add(clearButton);
}
// public method in GUI that will do the dirty work
public void clearAll() {
textField.setText("");
}
// other public methods here to get text from the JTextFields
// to set text, and do whatever else needs to be done
private static void createAndShowGui() {
GUI mainPanel = new GUI();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class MyListener implements ActionListener {
private GUI gui;
// use constructor parameter to set a field
public MyListener(GUI gui) {
this.gui = gui;
}
#Override
public void actionPerformed(ActionEvent e) {
gui.clearAll(); // call public method in field
}
}
A better and more robust solution is to structure your program in a Model-View-Controller fashion (look this up), but this would probably be overkill for this simple academic exercise that you're doing.

How to use single ActionListener for JCheckBox and JTextField

I am writing an eJuice Calculator. Its nowhere near finished as you will see below. My question is: I have 4 JCheckBoxes, and 5 editable JTextFields; can I use one ActionListener to do have the program execute stuff. Or do I need one listener for the CheckBoxes and one for the TextField?
This is a rough draft of code.
package ejuicecalculatorv2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EJuiceCalculatorV2 extends JFrame {
//Form Controls
private JCheckBox isPGbasedNic_CB = new JCheckBox("PG Based NIC");
private JCheckBox isPGbasedFlavor_CB = new JCheckBox("PG Based Flavor");
private JCheckBox isVGbasedNic_CB = new JCheckBox("VG Based NIC");
private JCheckBox isVGbasedFlavor_CB = new JCheckBox("VG Based Flavor");
private JTextField batchSize_TF = new JTextField(5);
private JLabel batchSize_LB = new JLabel("Batch Size:");
private JTextField baseNicStrength_TF = new JTextField(5);
private JLabel baseNicStrength_LB = new JLabel("Base NIC Strength:");
private JTextField targetNicStrength_TF = new JTextField(5);
private JLabel targetNicStrength_LB = new JLabel("Target NIC Strength:");
private JTextField totalNic_TF = new JTextField(5);
private JLabel totalNic_LB = new JLabel("Total NIC:");
private JTextField flavorStrength_TF = new JTextField(5);
private JLabel flavorStrength_LB = new JLabel("Flavoring Strength:");
private JTextField totalFlavor_TF = new JTextField(5);
private JLabel totalFlavor_LB = new JLabel("Total Flavoring:");
private JTextField vgRatio_TF = new JTextField(5);
private JLabel vgRatio_LB = new JLabel("VG Ratio:");
private JTextField pgRatio_TF = new JTextField(5);
private JLabel pgRatio_LB = new JLabel("PG Ratio:");
private JTextField additionalVG_TF = new JTextField(5);
private JLabel additionalVG_LB = new JLabel("Additional VG:");
private JTextField additionalPG_TF = new JTextField(5);
private JLabel additionalPG_LB = new JLabel("Additional PG:");
private JTextField totalVG_TF = new JTextField(5);
private JLabel totalVG_LB = new JLabel("Total VG:");
private JTextField totalPG_TF = new JTextField(5);
private JLabel totalPG_LB = new JLabel("Total PG:");
private JTextField vgBasedIng_TF = new JTextField(5);
private JLabel vgBasedIng_LB = new JLabel("Total VG Ingredients:");
private JTextField pgBasedIng_TF = new JTextField(5);
private JLabel pgBasedIng_LB = new JLabel("Total PG Ingredients:");
//Variables
private boolean _PGnicFlag;
private boolean _VGnicFlag;
private boolean _PGflavorFlag;
private boolean _VGflavorFlag;
private double baseNic;
private double targetNic;
private double totalNic;
private double flavorStrength;
private double totalFlavor;
private double batchSize;
private double totalPG;
private double totalVG;
private double additionalVG;
private double additionalPG;
private double pgBasedIng;
private double vgBasedIng;
private double pgRatio;
private double vgRatio;
public EJuiceCalculatorV2() {
super("EJuice Calculator V2");
setLayout(new FlowLayout());
//Add CheckBoxes
add(isPGbasedNic_CB);
add(isPGbasedFlavor_CB);
add(isVGbasedNic_CB);
add(isVGbasedFlavor_CB);
//Add TextFields and Labels
add(batchSize_LB);
add(batchSize_TF);
add(vgRatio_LB);
add(vgRatio_TF);
add(pgRatio_LB);
add(pgRatio_TF);
add(baseNicStrength_LB);
add(baseNicStrength_TF);
add(targetNicStrength_LB);
add(targetNicStrength_TF);
add(flavorStrength_LB);
add(flavorStrength_TF);
//Add ActionListeners
ActionListener actionListener = new ActionHandler();
isPGbasedNic_CB.addActionListener(actionListener);
isPGbasedFlavor_CB.addActionListener(actionListener);
isVGbasedNic_CB.addActionListener(actionListener);
isVGbasedFlavor_CB.addActionListener(actionListener);
batchSize_TF.addActionListener(actionListener);
vgRatio_TF.addActionListener(actionListener);
pgRatio_TF.addActionListener(actionListener);
baseNicStrength_TF.addActionListener(actionListener);
targetNicStrength_TF.addActionListener(actionListener);
flavorStrength_TF.addActionListener(actionListener);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class ActionHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent event){
//if event.getSource() == JCheckBox then execute the following code.
if(checkBox.isSelected()){
if(checkBox == isPGbasedNic_CB){
_PGnicFlag = true;
_VGnicFlag = false;
checkBox = isVGbasedNic_CB;
checkBox.setSelected(false);
}
else if(checkBox == isVGbasedNic_CB){
_VGnicFlag = true;
_PGnicFlag = false;
checkBox = isPGbasedNic_CB;
checkBox.setSelected(false);
}
else if(checkBox == isVGbasedFlavor_CB){
_VGflavorFlag = true;
_PGflavorFlag = false;
checkBox = isPGbasedFlavor_CB;
checkBox.setSelected(false);
}
else if(checkBox == isPGbasedFlavor_CB){
_PGflavorFlag = true;
_VGflavorFlag = false;
checkBox = isVGbasedFlavor_CB;
checkBox.setSelected(false);
}
}
else{
if(checkBox == isPGbasedNic_CB){
_PGnicFlag = false;
_VGnicFlag = true;
}
else if(checkBox == isVGbasedNic_CB){
_VGnicFlag = false;
_PGnicFlag = true;
}
else if(checkBox == isVGbasedFlavor_CB){
_VGflavorFlag = false;
_PGflavorFlag = true;
}
else if(checkBox == isPGbasedFlavor_CB){
_PGflavorFlag = false;
_VGflavorFlag = true;
}
}
}
}
public static void main(String[] args) {
// TODO code application logic here
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run (){
new EJuiceCalculatorV2().setVisible(true);
}
});
}
}
My question is: I have 4 JCheckBoxes, and 5 editable JTextFields; can I use one ActionListener to do have the program execute stuff. Or do I need one listener for the CheckBoxes and one for the TextField?
You have a bunch of control components, but none appear ones that would initiate an action from the GUI. Rather all of them, the JCheckBoxes and the JTextFields are there to get input, and you appear to be missing one final component, such as a JButton. I would add this component to your GUi, and I would add a single ActionListener to it and it alone. And then when pressed, it would check the state of the check boxes and the text components and then based on their state, give the user the appropriate response.
Also some, if not most or all of the JTextFields, I'd change to either JComboBoxes or JSpinners, to limit the input that the user can enter to something that is allowable since you don't want the user entering "yes" into the "Batch Size" JTextField.
For example:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.JSpinner.DefaultEditor;
#SuppressWarnings("serial")
public class JuiceTwo extends JPanel {
private static final String[] FLAVORS = {"Flavor 1", "Flavor 2", "Flavor 3", "Flavor 4"};
private static final Integer[] ALLOWABLE_BATCH_SIZES = {1, 2, 5, 10, 15, 20};
private static final String[] ALLOWABLE_VG_RATIOS = {"1/4", "1/3", "1/2", "1/1", "2/1", "3/1", "4/1", "8/1", "16/1"};
private List<JCheckBox> flavorBoxes = new ArrayList<>();
private JComboBox<Integer> batchSizeCombo;
private JSpinner vgRatioSpinner;
public JuiceTwo() {
// JPanel to hold the flavor JCheckBoxes
JPanel flavorPanel = new JPanel(new GridLayout(0, 1)); // hold them in vertical grid
flavorPanel.setBorder(BorderFactory.createTitledBorder("Flavors"));
for (String flavor : FLAVORS) {
JCheckBox flavorBox = new JCheckBox(flavor);
flavorBox.setActionCommand(flavor);
flavorPanel.add(flavorBox);
flavorBoxes.add(flavorBox);
}
batchSizeCombo = new JComboBox<>(ALLOWABLE_BATCH_SIZES);
SpinnerListModel vgRatioModel = new SpinnerListModel(ALLOWABLE_VG_RATIOS);
vgRatioSpinner = new JSpinner(vgRatioModel);
JComponent editor = vgRatioSpinner.getEditor();
if (editor instanceof DefaultEditor) {
((DefaultEditor)editor).getTextField().setColumns(4);
}
JButton getSelectionButton = new JButton("Get Selection");
getSelectionButton.setMnemonic(KeyEvent.VK_S);
getSelectionButton.addActionListener(new SelectionActionListener());
add(flavorPanel);
add(Box.createHorizontalStrut(20));
add(new JLabel("Batch Size:"));
add(batchSizeCombo);
add(Box.createHorizontalStrut(20));
add(new JLabel("VG Ratio:"));
add(vgRatioSpinner);
add(Box.createHorizontalStrut(20));
add(getSelectionButton);
}
private class SelectionActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
for (JCheckBox flavorBox : flavorBoxes) {
System.out.printf("%s selected: %b%n", flavorBox.getActionCommand(), flavorBox.isSelected());
}
System.out.println("Batch Size: " + batchSizeCombo.getSelectedItem());
System.out.println("VG Ration: " + vgRatioSpinner.getValue());
System.out.println();
}
}
private static void createAndShowGui() {
JuiceTwo mainPanel = new JuiceTwo();
JFrame frame = new JFrame("JuiceTwo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

trouble with creating JTable to display data [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am doing this payroll project for school.
The idea is for the user to input the employee's name, work hour, hourly rate, and select department from the ComboBox.
There will display 3 buttons, "Add More", "Display Result", and "exit".
"Add More" button will store the input into several arryalist and set the textfield to blank to allow more input.
"Display Result" will generate a JTable at the bottom JPanel to display the employee's name, department, and weekly salary.
I am running into the problem of nothing shows up after hitting the "Display Result" button. Maybe I have misunderstand the purpose of the button event, but I am really confused right now. Please help!
Here is a photobucket directURL PrtSc of the UI, hope it helps.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class PayrollFrame extends JFrame
{
private JLabel nameMessageLabel, hourMessageLabel, rateMessageLabel, boxMessageLabel;
private JTextField nameTextField, hourTextField, rateTextField;
private JPanel inputPanel, buttonPanel, outputPanel, inputPanel1, inputPanel2, inputPanel3, inputPanel4;
private JComboBox<String> departmentBox;
private JButton addButton, displayButton, exitButton;
private JTable resultTable;
private String[] columnNames = {"Employee name", "Department", "Weekly Salary"};
private Object[][] data;
private int WINDOW_WIDTH = 400;
private int WINDOW_HEIGHT = 500;
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> hour = new ArrayList<String>();
ArrayList<String> rate = new ArrayList<String>();
ArrayList<String> department = new ArrayList<String>();
ArrayList<String> salary = new ArrayList<String>();
private String[] departments = {"IT", "Marketing", "Human Resource", "Sales", "Customer Service", "Financial"};
/*default constructor*/
public PayrollFrame()
{
super("Payroll");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setLayout(new GridLayout(3,1));
buildInputPanel();
buildButtonPanel();
buildOutputPanel();
add(inputPanel);
add(buttonPanel);
add(outputPanel);
setVisible(true);
}
private void buildInputPanel()
{
nameMessageLabel = new JLabel("Employee Name: ");
hourMessageLabel = new JLabel("Work Hour: ");
rateMessageLabel = new JLabel("Hourly Rate: ");
boxMessageLabel = new JLabel("Department: ");
nameTextField = new JTextField(10);
hourTextField = new JTextField(10);
rateTextField = new JTextField(10);
departmentBox = new JComboBox<String>(departments);
inputPanel = new JPanel();
inputPanel1 = new JPanel();
inputPanel2 = new JPanel();
inputPanel3 = new JPanel();
inputPanel4 = new JPanel();
inputPanel1.add(nameMessageLabel);
inputPanel1.add(nameTextField);
inputPanel2.add(hourMessageLabel);
inputPanel2.add(hourTextField);
inputPanel3.add(rateMessageLabel);
inputPanel3.add(rateTextField);
inputPanel4.add(boxMessageLabel);
inputPanel4.add(departmentBox);
inputPanel.add(inputPanel1);
inputPanel.add(inputPanel2);
inputPanel.add(inputPanel3);
inputPanel.add(inputPanel4);
}
private void buildButtonPanel()
{
addButton = new JButton("Add More");
addButton.addActionListener(new ButtonAction());
displayButton = new JButton("Display Result");
displayButton.addActionListener(new ButtonAction());
exitButton = new JButton("Exit");
exitButton.addActionListener(new ButtonAction());
buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(displayButton);
buttonPanel.add(exitButton);
}
private void buildOutputPanel()
{
outputPanel = new JPanel();
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData()
{
for(int i=0; i<name.size(); i++)
{
data[i][0]=name.get(i);
data[i][2]=department.get(i);
data[i][2]=salary.get(i);
}
resultTable = new JTable(data, columnNames);
outputPanel = new JPanel();
outputPanel.add(resultTable);
}
/*Function of 3 buttons*/
private class ButtonAction implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()=="Add More")
{
name.add(nameTextField.getText());
hour.add(hourTextField.getText());
rate.add(rateTextField.getText());
department.add((String) departmentBox.getSelectedItem());
calculateSalary(hourTextField.getText(), rateTextField.getText());
nameTextField.setText("");
hourTextField.setText("");
rateTextField.setText("");
}
else if(e.getActionCommand()=="Display Result")
{
printData();
}
else if(e.getActionCommand()=="Exit")
{
System.exit(0);
}
}
/*Calculate the weekly salary*/
private void calculateSalary(String hourString, String rateString)
{
int tempHour = Integer.parseInt(hourString);
double tempRate = Double.parseDouble(rateString);
if(tempHour<=40)
{
salary.add(Double.toString(tempHour * tempRate));
}
else
{
salary.add(Double.toString(40 * tempRate + (tempHour - 40) * (tempRate * 1.5))); //all hour after 40 will pay 1.5
}
}
}
}
Let's start with...
if (e.getActionCommand() == "Add More") {
Is not how you compare Strings in Java, you need to use the equals method instead, something like...
if ("Add More".equals(e.getActionCommand())) {
for example
Next you do...
add(inputPanel);
add(buttonPanel);
add(outputPanel);
which, when using a BorderLayout, adds each of the components to the default position within the BorderLayout, you need to provide position constraints for each component, otherwise strange things begin to happen, for example...
add(inputPanel, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);
add(outputPanel, BorderLayout.SOUTH);
I just realised that you're using a GridLayout, personally, I think you'll get a better result from BorderLayout, but that's me
And then you create a new instance of resultTable and outputPanel, but you never add outputPanel to anything...
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData()
{
for(int i=0; i<name.size(); i++)
{
data[i][0]=name.get(i);
data[i][1]=department.get(i);
data[i][2]=salary.get(i);
}
resultTable = new JTable(data, columnNames);
outputPanel = new JPanel();
outputPanel.add(resultTable);
}
A better idea would be to create resultTable, wrap in a JScrollPane and add it to your screen.
When you want to "print" the data, create a new TableModel and apply it to the JTable
For example...
private void buildOutputPanel() {
outputPanel = new JPanel(new BorderLayout());
resultTable = new JTable();
outputPanel.add(new JScrollPane(resultTable));
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData() {
for (int i = 0; i < name.size(); i++) {
data[i][0] = name.get(i);
data[i][2] = department.get(i);
data[i][2] = salary.get(i);
}
DefaultTableModel model = new DefaultTableModel(data, columnNames);
resultTable.setModel(model);
}
Take a look at How to Use Tables and How to Use Scroll Panes for more details
Example
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class PayrollFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
PayrollFrame frame = new PayrollFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private JLabel nameMessageLabel, hourMessageLabel, rateMessageLabel, boxMessageLabel;
private JTextField nameTextField, hourTextField, rateTextField;
private JPanel inputPanel, buttonPanel, outputPanel, inputPanel1, inputPanel2, inputPanel3, inputPanel4;
private JComboBox<String> departmentBox;
private JButton addButton, displayButton, exitButton;
private JTable resultTable;
private String[] columnNames = {"Employee name", "Department", "Weekly Salary"};
private Object[][] data;
private int WINDOW_WIDTH = 400;
private int WINDOW_HEIGHT = 500;
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> hour = new ArrayList<String>();
ArrayList<String> rate = new ArrayList<String>();
ArrayList<String> department = new ArrayList<String>();
ArrayList<String> salary = new ArrayList<String>();
private String[] departments = {"IT", "Marketing", "Human Resource", "Sales", "Customer Service", "Financial"};
/*default constructor*/
public PayrollFrame() {
super("Payroll");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
buildInputPanel();
buildButtonPanel();
buildOutputPanel();
add(inputPanel, BorderLayout.NORTH);
add(buttonPanel);
add(outputPanel, BorderLayout.SOUTH);
setVisible(true);
}
private void buildInputPanel() {
nameMessageLabel = new JLabel("Employee Name: ");
hourMessageLabel = new JLabel("Work Hour: ");
rateMessageLabel = new JLabel("Hourly Rate: ");
boxMessageLabel = new JLabel("Department: ");
nameTextField = new JTextField(10);
hourTextField = new JTextField(10);
rateTextField = new JTextField(10);
departmentBox = new JComboBox<String>(departments);
inputPanel = new JPanel();
inputPanel1 = new JPanel();
inputPanel2 = new JPanel();
inputPanel3 = new JPanel();
inputPanel4 = new JPanel();
inputPanel1.add(nameMessageLabel);
inputPanel1.add(nameTextField);
inputPanel2.add(hourMessageLabel);
inputPanel2.add(hourTextField);
inputPanel3.add(rateMessageLabel);
inputPanel3.add(rateTextField);
inputPanel4.add(boxMessageLabel);
inputPanel4.add(departmentBox);
inputPanel.add(inputPanel1);
inputPanel.add(inputPanel2);
inputPanel.add(inputPanel3);
inputPanel.add(inputPanel4);
}
private void buildButtonPanel() {
addButton = new JButton("Add More");
addButton.addActionListener(new ButtonAction());
displayButton = new JButton("Display Result");
displayButton.addActionListener(new ButtonAction());
exitButton = new JButton("Exit");
exitButton.addActionListener(new ButtonAction());
buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(displayButton);
buttonPanel.add(exitButton);
}
private void buildOutputPanel() {
outputPanel = new JPanel(new BorderLayout());
resultTable = new JTable();
outputPanel.add(new JScrollPane(resultTable));
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData() {
for (int i = 0; i < name.size(); i++) {
data[i][0] = name.get(i);
data[i][2] = department.get(i);
data[i][2] = salary.get(i);
}
TableModel model = new DefaultTableModel(data, columnNames);
resultTable.setModel(model);
}
/*Function of 3 buttons*/
private class ButtonAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if ("Add More".equals(e.getActionCommand())) {
name.add(nameTextField.getText());
hour.add(hourTextField.getText());
rate.add(rateTextField.getText());
department.add((String) departmentBox.getSelectedItem());
calculateSalary(hourTextField.getText(), rateTextField.getText());
nameTextField.setText("");
hourTextField.setText("");
rateTextField.setText("");
} else if ("Display Result".equals(e.getActionCommand())) {
printData();
} else if ("Exit".equals(e.getActionCommand())) {
System.exit(0);
}
}
/*Calculate the weekly salary*/
private void calculateSalary(String hourString, String rateString) {
int tempHour = Integer.parseInt(hourString);
double tempRate = Double.parseDouble(rateString);
if (tempHour <= 40) {
salary.add(Double.toString(tempHour * tempRate));
} else {
salary.add(Double.toString(40 * tempRate + (tempHour - 40) * (tempRate * 1.5))); //all hour after 40 will pay 1.5
}
}
}
}
Thanks for #MadProgrammer 's help! His reply helps me to fix many problems I have, and really tried to explain things to me. After consulting with my instructor, I have successfully compile and run my program by editing the printData method.
private void printData()
{
DefaultTableModel model = new DefaultTableModel(columnNames,name.size());
resultTable.setModel(model);
for(int i=0; i<name.size(); i++)
{
resultTable.setValueAt(name.get(i),i,0);
resultTable.setValueAt(department.get(i),i,1);
resultTable.setValueAt(salary.get(i),i,2);
}
}

Storing JList selections in an array String[] in Java

I am creating a GUI, and can't figure out how to store the JList user selections in an array. I tried List<<Sting>>, Object[] etc... JRadioButtons and other GUIs are fine, only JList is not working...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame {
private JTextField num3;
private JLabel label3;
private JButton button;
private JRadioButton radio2;
private JRadioButton radio3;
private ButtonGroup radioGroup;
private JList statesList;
String[] states = {"Alabama", "Alaska", "Wyoming"};
String expression;
String frequency;
// no args constructor
public Test() {
createUI();
}
private void createUI() {
Container contentPane = getContentPane();
contentPane.setLayout(null);
label3 = new JLabel();
label3.setText("Search Expression");
label3.setBounds(16, 120, 200, 21);
contentPane.add(label3);
num3 = new JTextField();
num3.setText("(any expression)");
num3.setBounds(16, 144, 150, 21);
num3.setHorizontalAlignment(JTextField.LEFT);
contentPane.add(num3);
button = new JButton("Start!");
button.setBounds(90,430,126,24);
contentPane.add(button);
button.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event)
{
buttonActionPerformed(event);
}
}
);
// States Selection
statesList = new JList(states);
statesList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
statesList.setVisibleRowCount(5);
statesList.setBounds(400, 16, 100, 50);
JScrollPane statesScroll = new JScrollPane(statesList);
statesScroll.setBounds(180, 16, 135, 400);
contentPane.add(statesScroll);
// Radio Buttons
radio2 = new JRadioButton();
radio3 = new JRadioButton();
radio3.setSelected(true);
radioGroup = new ButtonGroup();
radioGroup.add(radio2);
radioGroup.add(radio3);
radio2.setText("Quarterly");
radio3.setText("Yearly");
radio2.setBounds(16,360,90,23);
radio3.setBounds(16,385,75,23);
contentPane.add(radio2);
contentPane.add(radio3);
// set the content Pane window
setTitle("Search Engine");
setSize(750,500);
setVisible(true);
}
// Getting the user's TextField and JRadioButton input
private void buttonActionPerformed(ActionEvent event) {
expression = num3.getText();
if (radio2.isSelected())
frequency = "quarterly";
else frequency = "yearly";
System.out.println(expression+","+frequency);
// The above "expression" and "frequency" work fine. But JList does not
// work. What am I doing wrong? I tried Object[] instead of List<String>...
List<String> values = statesList.getSelectedValues();
return values==null ? null : values.toArray(new String[values.size()]);
}
// main thread
public static void main(String[] args) {
Test application = new Test();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
This variant iterates the Object[] returned by getSelectedValues() to show expected values in the console. Next thing to fix is the layouts.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//public class Test extends JFrame {
public class Test {
private JTextField num3;
private JLabel label3;
private JButton button;
private JRadioButton radio2;
private JRadioButton radio3;
private ButtonGroup radioGroup;
private JList statesList;
String[] states = {"Alabama", "Alaska", "Wyoming"};
String expression;
String frequency;
// no args constructor
public Test() {
createUI();
}
private void createUI() {
JFrame f = new JFrame("Search Engine");
Container contentPane = f.getContentPane();
// This needs fixing NEXT!
contentPane.setLayout(null);
label3 = new JLabel();
label3.setText("Search Expression");
label3.setBounds(16, 120, 200, 21);
contentPane.add(label3);
num3 = new JTextField();
num3.setText("(any expression)");
num3.setBounds(16, 144, 150, 21);
num3.setHorizontalAlignment(JTextField.LEFT);
contentPane.add(num3);
button = new JButton("Start!");
button.setBounds(90,430,126,24);
contentPane.add(button);
button.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
buttonActionPerformed(event);
}
});
// States Selection
statesList = new JList(states);
statesList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
statesList.setVisibleRowCount(5);
statesList.setBounds(400, 16, 100, 50);
JScrollPane statesScroll = new JScrollPane(statesList);
statesScroll.setBounds(180, 16, 135, 400);
contentPane.add(statesScroll);
// Radio Buttons
radio2 = new JRadioButton();
radio3 = new JRadioButton();
radio3.setSelected(true);
radioGroup = new ButtonGroup();
radioGroup.add(radio2);
radioGroup.add(radio3);
radio2.setText("Quarterly");
radio3.setText("Yearly");
radio2.setBounds(16,360,90,23);
radio3.setBounds(16,385,75,23);
contentPane.add(radio2);
contentPane.add(radio3);
// set the content Pane window
f.setSize(750,500);
//f.pack();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setVisible(true);
}
// Getting the user's TextField and JRadioButton input
private void buttonActionPerformed(ActionEvent event) {
expression = num3.getText();
if (radio2.isSelected())
frequency = "quarterly";
else frequency = "yearly";
System.out.println(expression+","+frequency);
Object[] values = statesList.getSelectedValues();
for (Object state : values) {
System.out.println(state);
}
}
// main thread
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
Test application = new Test();
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
Tips
Don't extend frame, just use an instance.
J2SE GUIs (Swing & AWT) should be created and updated on the EDT. See Concurrency in Swing - Initial Threads especially.
contentPane.setLayout(null); This will not work in the real world (read probably the next PC as 'the real world'). Use layout managers for a robust GUI. See Laying Out Components Within a Container for details, and also this nested layout example for grouping layouts according to need.
According to the documentation, getSelectedValues returns an object array.
Object[] values = statesList.getSelectedValues();
If you're positive they're all strings, you can just type cast them.
String[] values = (String[]) statesList.getSelectedValues();
Edit: Try this:
Object[] values = statesList.getSelectedValues();
String[] strings = new String[values.length];
for(int i = 0; i < values.length; i++) {
if(values[i] instanceof String) {
strings[i] = ((String) values[i]);
}
}

Categories

Resources