Getting JButton To Work - java

right now I have some buttons on a calculator and they are not setup. I am confused as to how to get them to print something in the JTextField when clicked. I am aware that you need to use ActionListener, but I cannot seem to get it working. Thanks for your help!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JPanel implements ActionListener {
private JTextField tf = null;
private JButton[] arrBtn = null;
private String[] btnNames = { "1", "2", "3", "4", "5", "6", "7", "CE", "-", "+", "/", "%", "*", "=" };
private JPanel jp = new JPanel();
private char op = ' ';
private int num1 = 0;
private int num2 = 0;
private int result = 0;
private boolean isOpPressed = false;
private JPanel btnPl;
public Calculator() {
super();
jp = new JPanel();
jp.setLayout(new GridLayout(3, 3));
btnPl = new JPanel();
btnPl.setLayout(new GridLayout(4, 4));
jp.add(new JTextField());
jp.add(new JTextField());
jp.add(new JTextField());
jp.add(new JTextField());
jp.add(new JTextField());
jp.add(new JTextField());
arrBtn = new JButton[btnNames.length];
for (int i = 0; i < arrBtn.length; i++) {
arrBtn[i] = new JButton(btnNames[i]);
arrBtn[i].addActionListener(this);
btnPl.add(arrBtn[i]);
}
this.setLayout(new BorderLayout());
this.add(jp, BorderLayout.NORTH);
this.add(btnPl, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
}
public static void main(String args[]) {
new Calculator();
JFrame frame = new JFrame("Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RomanCalculator cal = new RomanCalculator();
frame.add(cal);
frame.pack();
frame.setSize(500, 500);
frame.setVisible(true);
}
}

I suggest first taking a looking at this, this, and this.
Here is how you should be creating a new TextField
JTextField textField = new JTextField();
You should then create a button and action listener similar to this
JButton someBtn = new JButton("Some Text");
someBtn.addActionListener(this);
Your ActionPerformed
#Override
public void actionPerformed(ActionEvent e) {
textField.setText("New Text");
}
If you would like to stay with the approach of using an Array of JButtons I suggest doing something similar.
String[] btnNames = {"1", "2", "3", etc.};
JButton[] allBtns = new JButton[10];
for(int i = 0; i < 10; i++){
allBtns[i] = new JButton(btnNames[i]);
allBtns[i].addActionListener(this);
//Using the previous actionPerformed
}
If you would like to customize what each button does you can do this
anyBtn.addActionListener(e -> textField.setText("Anything"));
Take a look at lambda's for more info.

the way I usually go about it in java is to have an inner class that handles the button clicks
public x extends JFrame(){
//I like to store my buttons in an array if possible.
JButton [] buttonArray = new JButton [2];
//instantialize each of the arrays buttons
buttonArray[0] = new JButton("hello");
buttonArray[1] = new JButton("world");
//create a listener of type buttonpress (currently undefined)
buttonPress Listener = new buttonPress();
//attach the button action listeners to the listener I created above.
buttonArray[0].addActionListener(Listener);
buttonArray[1].addActionListener(Listener);
//Create a private inner class called "buttonPress" which will handle the clicks for its listeners
private class buttonPress implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == buttonArray[0]){
try
{
..some logic
}
catch (Exception e1)
{
JOptionPane.showMessageDialog(null, e1.getMessage());
}
}
else if( e.getSource() == buttonArray[1])
{
...some other logic
}
}
}//close inner class
}//close outer class

Related

Use of JButton array Java

I am not sure what I am doing wrong. I am trying to create 4 buttons using the arrays and passing the method to the Set Panel class. When I run it I only get one button. Any help would be great. Essentially what I want is a Panel with four buttons, through the use of Methods.
public class SetButtons extends JButton implements ActionListener {
JButton [] buttonArray = new JButton[4];
JButton exitBtn, newGameBtn, checkBtn, clearBtn;
Font myFont = new Font("ink free", Font.BOLD,22);
public SetButtons(){
this.exitBtn = new JButton("Exit");
this.newGameBtn = new JButton("New Game");
this.checkBtn = new JButton("Check Answer");
this.clearBtn = new JButton("Clear");
this.buttonArray[0] = exitBtn;
this.buttonArray[1] = newGameBtn;
this.buttonArray[2] = checkBtn;
this.buttonArray[3] = clearBtn;
for (int i = 0; i < 4; i++){
this.buttonArray[i].addActionListener(this);
this.buttonArray[i].setFont(myFont);
this.buttonArray[i].setFocusable(false);
this.buttonArray[i].setLayout(new FlowLayout());
}
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == this){
System.exit(0);
}
}
}
import javax.swing.*;
import java.awt.*;
public class SetPanel extends JPanel {
Font myFont = new Font("ink free", Font.BOLD,22);
SetLabels labels;
SetButtons exitButton;
SetPanel(){
SetButtons btn = new SetButtons();
this.add(btn);
this.setBackground(Color.darkGray);
this.setLayout(new FlowLayout());
}
}

Numberpad Not Displaying Correctly

I have a Java GUI project where I am creating an ATM. I have everything setup, but for some reason my number pad on the left is not displaying properly. It should appear as a 4x3 grid of numbers, but it is just displaying a 9. I have checked to make sure it is in a GridLayout and I have checked my loop, but I possibly may have looked over something. Any help is appreciated, thanks!
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.*;
public class ATMProject extends JPanel implements ActionListener {
private JPanel mainPanel = null;
private JPanel btnPanel = null;
private JPanel userBtns = null;
private JTextArea textArea = null;
private JPanel keyPanel = null;
private JTextField numField = null;
private JPanel numpadPanel = null;
private JButton[] userButtons = null;
private JButton[] keypadButtons = null;
private String[] btnPanelbtns = { "A", "B", "C" };
private String[] numpadPanelbtns = { "7", "4", "1", "8", "5", "2", "9", "6", "3", "0", ".", "CE" };
public ATMProject() {
super();
mainPanel = new JPanel();
this.setLayout(new BorderLayout());
this.add(mainPanel);
btnPanel = new JPanel();
btnPanel.setLayout(new GridLayout(3, 1));
this.add(btnPanel, BorderLayout.EAST);
textArea = new JTextArea();
this.add(textArea, BorderLayout.CENTER);
keyPanel = new JPanel();
keyPanel.setLayout(new BorderLayout());
this.add(keyPanel, BorderLayout.WEST);
numpadPanel = new JPanel();
numpadPanel.setLayout(new GridLayout(0, 3));
keyPanel.add(numpadPanel, BorderLayout.CENTER);
numField = new JTextField();
keyPanel.add(numField, BorderLayout.NORTH);
userButtons = new JButton[btnPanelbtns.length];
for (int i = 0; i < userButtons.length; i++) {
userButtons[i] = new JButton(btnPanelbtns[i]);
userButtons[i].addActionListener(this);
btnPanel.add(userButtons[i]);
}
keypadButtons = new JButton[numpadPanelbtns.length];
for (int i = 0; i < userButtons.length; i++) {
keypadButtons[i] = new JButton(numpadPanelbtns[i]);
keypadButtons[i].addActionListener(this);
numpadPanel.add(keypadButtons[i]);
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
MyFrame mf = new MyFrame();
}
}
import javax.swing.JFrame;
public class MyFrame extends JFrame {
private ATMProject atm = null;
public MyFrame(){
super();
atm = new ATMProject();
this.add(atm);
this.setTitle("ATM");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setSize(800,300);
this.setVisible(true);
}
}
This is how it is supposed to appear:
You're adding you buttons to keyPanel...
keyPanel.add(keypadButtons[i]);
which is using a BorderLayout...
keyPanel = new JPanel();
keyPanel.setLayout(new BorderLayout());
so only the last component added to it will be laid out by the panel.
One imagines you should be adding them to numpadPanel instead...
numpadPanel.add(keypadButtons[i]);
Yeah, I have that numpadPanel.add(keypadButtons[i]); and I am getting just 7 8 9 vertically.
That's kind of how GridLayout works, you could force into a horizontal priority mode by using something more like
numpadPanel.setLayout(new GridLayout(0, 3));
My loop was incorrectly written. for (int i = 0; i < userButtons.length; i++) my program was only outputting 3 buttons because userButtons.length only had 3 elements. I changed userButtons.length to numpadPanelbtns.length and it fixed it because there are 12 elements in the numpadPanelbtns array.

Comparing two JTextFields with an ActionListener

what I am trying to do is compare two inputs from TextFields within a JFrame using an ActionListener. If the two inputs are equal and the user hits the button, a MessageDialog will pop up and say "equal". If they are not equal, a MessageDialog will pop up and say "not equal". I have the frame and ActionListener running, I just do not know how to take the inputs from the TextFields and compare them.
For example, if the user enters something like this,
Equal TextFields, this will pop up, Equal Message
Here is my Main Class:
public class LabFiveOne
{
public static void main(String[] args)
{
JFrame frame = new JFrame("String Equality Program");
JTextField tf1 = new JTextField(10);
tf1.setActionCommand(tf1.toString());
tfListener tfListen = new tfListener(tf1);
JTextField tf2 = new JTextField(10);
tf2.setActionCommand(tf2.toString());
JButton chEq = new JButton("Check Equality");
chEq.addActionListener(tfListen);
JPanel nPanel = new JPanel();
nPanel.add(tf1);
nPanel.add(tf2);
frame.add(nPanel, BorderLayout.NORTH);
JPanel sPanel = new JPanel();
sPanel.add(chEq);
frame.add(sPanel, BorderLayout.SOUTH);
nPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
And here is my ActionListener Class:
class tfListener implements ActionListener
{
private final JTextField tf3;
public tfListener(JTextField nameTF)
{
tf3 = nameTF;
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("abc"))
{
JOptionPane.showMessageDialog(null, "equal");
}
else
{
JOptionPane.showMessageDialog(null, "not equal");
}
}
}
EDIT: ok than try to change the constructor in your ActionListener Class to
public tfListener(JTextField tf1, JTextField tf2){
{
Hi :) just don't overthink and you should be fine. The simple way would be to implement the ActionListener directly to your Main Class like this:
public class LabFiveOne
{
public static void main(String[] args)
{
JFrame frame = new JFrame("String Equality Program");
final JTextField tf1 = new JTextField(10);
tf1.setActionCommand(tf1.toString());
tfListener tfListen = new tfListener(tf1);
final JTextField tf2 = new JTextField(10);
tf2.setActionCommand(tf2.toString());
JButton chEq = new JButton("Check Equality");
chEq.addActionListener(tfListen);
JPanel nPanel = new JPanel();
nPanel.add(tf1);
nPanel.add(tf2);
frame.add(nPanel, BorderLayout.NORTH);
JPanel sPanel = new JPanel();
sPanel.add(chEq);
frame.add(sPanel, BorderLayout.SOUTH);
nPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
{
class tfListener implements ActionListener
{
private final String tf1text;
private final String tf2text;
public tfListener(JTextField tf1, JTextField tf2)
{
tf1text = new String(tf1.getText());
tf1text = new String(tf2.getText());
}
#Override
public void actionPerformed(ActionEvent e)
{
if(tf1text.equal(tf2text))
{
JOptionPane.showMessageDialog(null, "equal");
}
else
{
JOptionPane.showMessageDialog(null, "not equal");
}
}
}
}
tf1.toString();
Shows you some information from the JTextField.
use another methods to get your input from the field. I mean it's the method:
tfi.getText();
Better look in a JTextField javadoc
To be honest with you, I don't think you need two classes; one for implementing the GUI and one for handling the ActionListener when you can have everything in one class like the class below
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
public class LabFiveOne implements ActionListener
{
private JFrame frame;
private JPanel nPanel, sPanel;
private JTextField tf1, tf2;
private JButton chEq;
public static void main(String[] args)
{
new LabFiveOne();
}
public LabFiveOne(){
frame = new JFrame("String Equality Program");
tf1 = new JTextField(10);
tf2 = new JTextField(10);
chEq = new JButton("Check Equality");
chEq.addActionListener(this);
nPanel = new JPanel();
nPanel.add(tf1);
nPanel.add(tf2);
frame.add(nPanel, BorderLayout.NORTH);
sPanel = new JPanel();
sPanel.add(chEq);
frame.add(sPanel, BorderLayout.SOUTH);
nPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String action = e.getActionCommand();
if(action.equals("Check Equality")){
String number1 = tf1.getText();
String number2 = tf2.getText();
int num1 = Integer.valueOf(number1);
int num2 = Integer.valueOf(number2);
if(num1 == num2){
JOptionPane.showMessageDialog(null, "Equal");
}
else{
JOptionPane.showMessageDialog(null, "Not Equal");
}
}
}
}
I have everything declared globally so that the ActionPerformed method will have access the values in the Textfields.

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