How to close my program when exiting the frame - java

I am having some issues getting my GUI to exit on close. I have tried
frame.setDefaultCloseOperation(JFrame.CLOSE_ON_EXIT);
I have tried it with DISPOSE_ON_EXIT and it is not working.
when I run the program without any of that code and I click "X" it closes the window, but it is still running.
When I put that code in it will not compile and I get this error.
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: <any>
at InvestmentFrame2.main(InvestmentFrame2.java:103)
I have tried reading suggestions on here as well as on other websites. The book I am using to learn this stuff didn't really explain anything about it, but just had it in some example code So I have just been trying some various suggestions.
I couldn't figure out if I maybe needed to import something else or if there is some other issue?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class InvestmentFrame2 extends JFrame
{
private static final int FRAME_WIDTH = 450;
private static final int FRAME_HEIGHT = 250;
private static final double DEFAULT_RATE = 0;
private static final double INITIAL_BALANCE = 0;
private static final double YEARS = 0;
private JLabel rateLabel;
private JLabel balanceLabel;
private JLabel yearsLabel;
private JTextField rateField;
private JTextField balanceField;
private JTextField yearsField;
private JButton button;
private JLabel resultLabel;
private double balance;
public InvestmentFrame2()
{
balance = INITIAL_BALANCE;
resultLabel = new JLabel("Balance: " + balance);
createTextField();
createButton();
createPanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void createTextField()
{
rateLabel = new JLabel("Interest Rate: ");
balanceLabel = new JLabel("Account Balance: ");
yearsLabel = new JLabel("Number of Years Saving: ");
final int FIELD_WIDTH = 10;
rateField = new JTextField(FIELD_WIDTH);
rateField.setText ("" + DEFAULT_RATE);
balanceField = new JTextField(FIELD_WIDTH);
balanceField.setText("" + INITIAL_BALANCE);
yearsField = new JTextField(FIELD_WIDTH);
yearsField.setText("" + YEARS);
}
class AddInterestListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
double rate = Double.parseDouble(rateField.getText());
double accountBalance = Double.parseDouble(balanceField.getText());
double years = Double.parseDouble(yearsField.getText());
double interest = (accountBalance * rate / 100) * years;
balance = accountBalance + interest;
resultLabel.setText("Balance: " + balance);
}
}
private void createButton()
{
button = new JButton("Calculate Balance");
ActionListener listener = new AddInterestListener();
button.addActionListener(listener);
}
private void createPanel()
{
JPanel panel = new JPanel();
panel.add(rateLabel);
panel.add(rateField);
panel.add(balanceLabel);
panel.add(balanceField);
panel.add(yearsLabel);
panel.add(yearsField);
panel.add(button);
panel.add(resultLabel);
add(panel);
}
public static void main(String[] args)
{
JFrame frame = new InvestmentFrame2();
frame.setTitle("Savings Frame");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_EXIT);
frame.setVisible(true);
}
}

You're trying to run a class which is uncompilable...JFrame.DISPOSE_ON_EXIT doesn't exist. You are actually looking for JFrame.EXIT_ON_CLOSE
Take a minute to read the JavaDocs for JFrame
public void setDefaultCloseOperation(int operation) Sets the
operation that will happen by default when the user initiates a
"close" on this frame. You must specify one of the following
choices: * DO_NOTHING_ON_CLOSE (defined in WindowConstants):
Don't do anything; require the program to handle the operation in the
windowClosing method of a registered WindowListener object. *
HIDE_ON_CLOSE (defined in WindowConstants): Automatically hide the
frame after invoking any registered WindowListener objects. *
DISPOSE_ON_CLOSE (defined in WindowConstants): Automatically hide and
dispose the frame after invoking any registered WindowListener
objects. * EXIT_ON_CLOSE (defined in JFrame): Exit the
application using the System exit method. Use this only in
applications. The value is set to HIDE_ON_CLOSE by default.
Changes to the value of this property cause the firing of a property
change event, with property name "defaultCloseOperation".
You might also find How to Make Frames (Main Windows) of some use...
You should also ensure that your UI is created within the context of the Event Dispatching Thread, take a look at Initial Threads for more details
Updated with example
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class InvestmentFrame2 extends JFrame {
private static final int FRAME_WIDTH = 450;
private static final int FRAME_HEIGHT = 250;
private static final double DEFAULT_RATE = 0;
private static final double INITIAL_BALANCE = 0;
private static final double YEARS = 0;
private JLabel rateLabel;
private JLabel balanceLabel;
private JLabel yearsLabel;
private JTextField rateField;
private JTextField balanceField;
private JTextField yearsField;
private JButton button;
private JLabel resultLabel;
private double balance;
public InvestmentFrame2() {
balance = INITIAL_BALANCE;
resultLabel = new JLabel("Balance: " + balance);
createTextField();
createButton();
createPanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void createTextField() {
rateLabel = new JLabel("Interest Rate: ");
balanceLabel = new JLabel("Account Balance: ");
yearsLabel = new JLabel("Number of Years Saving: ");
final int FIELD_WIDTH = 10;
rateField = new JTextField(FIELD_WIDTH);
rateField.setText("" + DEFAULT_RATE);
balanceField = new JTextField(FIELD_WIDTH);
balanceField.setText("" + INITIAL_BALANCE);
yearsField = new JTextField(FIELD_WIDTH);
yearsField.setText("" + YEARS);
}
class AddInterestListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
double rate = Double.parseDouble(rateField.getText());
double accountBalance = Double.parseDouble(balanceField.getText());
double years = Double.parseDouble(yearsField.getText());
double interest = (accountBalance * rate / 100) * years;
balance = accountBalance + interest;
resultLabel.setText("Balance: " + balance);
}
}
private void createButton() {
button = new JButton("Calculate Balance");
ActionListener listener = new AddInterestListener();
button.addActionListener(listener);
}
private void createPanel() {
JPanel panel = new JPanel();
panel.add(rateLabel);
panel.add(rateField);
panel.add(balanceLabel);
panel.add(balanceField);
panel.add(yearsLabel);
panel.add(yearsField);
panel.add(button);
panel.add(resultLabel);
add(panel);
}
public static void main(String[] args) {
JFrame frame = new InvestmentFrame2();
frame.setTitle("Savings Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Compiles and runs just fine for me...

Related

Remove Java Panels without crashing your program

So basically I am writing a GUI program that uses a JComboBox to display various finance formulas. I have everything in place in terms of it displaying the formulas but here is my problem. Everytime I go to choose a new formula in my comboBox it the other ones stay displayed. I've tried to write an if statement to disable, remove and invalidate these (not all at once) but none have worked...I need to get it so when I click a option the other panels disappear if there are any at all. Thanks!
Here is the full program the problem I am having is that when I choose a new formula the one that I chose before it is still active...I want to disable or remove it. Thanks.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.text.DecimalFormat;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class newFinanceFullClass extends JFrame {
private JMenu fileMenu;
private JMenuItem exitItem;
private JPanel presentValuePanel;
private JPanel financeFinderPanel;// A panel container
private JLabel principalMessage;
private JLabel yearlyRateMessage;
private JLabel termYearMessage;
private JPanel simpleInterestPanel;
private JPanel doublingTimePanel;
private JPanel compoundInterestPanel;
private JLabel NONEMessage;
private JLabel imageLabel;
private JLabel label;// A message to display
private JMenuBar menuBar;
private JTextField principalText; // To hold user input
private JButton calcButton; // Performs calculation
private final int WINDOW_WIDTH = 600; // Window width
private final int WINDOW_HEIGHT = 600; // Window height
private JTextField yearlyRateText;
private JTextField termYearText;
DecimalFormat dc =new DecimalFormat("####0.00"); //formater
private JComboBox financeBox;
double principal = 400.0;
double yearlyRate = .04;
double termYears = 4.0;
private String[] financeFormulas = { "NONE", "Present value", "Simple interest",
"Doubling time", "Compound interest", "Decaf"};
financeFormulaClass financeFormula = new financeFormulaClass(principal, yearlyRate, termYears);
/**
* Constructor
*/
public newFinanceFullClass()
{
// Call the JFrame constructor.
super("Finance Class");
// Set the size of the window.
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
// Specify what happens when the close
// button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Build the panel and add it to the frame.
financeFinderPanel();
setLayout(new BorderLayout());
//buildPanel();
menuBar = new JMenuBar();
buildFileMenu();
menuBar.add(fileMenu);
setJMenuBar(menuBar);
// Add the panel to the frame's content pane.
add(financeFinderPanel);
//add(panel);
// Display the window.
setVisible(true);
}
private void financeFinderPanel()
{
// Create a panel to hold the combo box.
financeFinderPanel = new JPanel();
//create label
label = new JLabel("Pick your formula");
ImageIcon funnyImage = new ImageIcon("funny.gif");
imageLabel = new JLabel();
imageLabel.setLocation(50, 55);
label.setForeground(Color.BLUE);
// Create the combo box
financeBox = new JComboBox(financeFormulas);
imageLabel.setIcon(funnyImage);
// Register an action listener.
financeBox.addActionListener(new financeBoxListener());
exitItem = new JMenuItem("Exit");
exitItem.setMnemonic(KeyEvent.VK_X);
// Add the combo box to the panel.
financeFinderPanel.add(financeBox);
financeFinderPanel.add(label);
financeFinderPanel.add(imageLabel);
}
/** private void menuList(){
exitItem = new JMenuItem("Exit");
exitItem.setMnemonic(KeyEvent.VK_X);
menuList.add(exitItem);
} **/
private void buildMenuBar()
{
// Create the menu bar.
menuBar = new JMenuBar();
// Create the file and text menus.
buildFileMenu();
// buildTextMenu();
// Add the file and text menus to the menu bar.
menuBar.add(fileMenu);
//menuBar.add(textMenu);
// Set the window's menu bar.
setJMenuBar(menuBar);
}
private void buildFileMenu()
{
// Create an Exit menu item.
exitItem = new JMenuItem("Exit");
exitItem.setMnemonic(KeyEvent.VK_X);
exitItem.addActionListener(new ExitListener());
// Create a JMenu object for the File menu.
fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
// Add the Exit menu item to the File menu.
fileMenu.add(exitItem);
}
private void presentValuePanel()
{
// Create the label, text field, and button components.
principalMessage = new JLabel("principal");
principalText = new JTextField(10);
yearlyRateMessage = new JLabel("Yearly Rate");
yearlyRateText = new JTextField(10);
termYearMessage = new JLabel("Term Year");
termYearText = new JTextField(10);
calcButton = new JButton("Calc Present Value");
// Add an action listener to the button.
//calcButton.addActionListener(new CalcButtonListener());
calcButton.addActionListener(new financeFormListener());
// Create a panel to hold the components.
presentValuePanel = new JPanel();
// Add the label, text field, and button to the panel.
presentValuePanel.add(principalMessage);
presentValuePanel.add(principalText);
presentValuePanel.add(yearlyRateMessage);
presentValuePanel.add(yearlyRateText);
presentValuePanel.add(termYearMessage);
presentValuePanel.add(termYearText);
presentValuePanel.add(calcButton);
}
private void simpleInterestPanel(){
principalMessage = new JLabel("principal");
principalText = new JTextField(10);
yearlyRateMessage = new JLabel("Yearly Rate");
yearlyRateText = new JTextField(10);
termYearMessage = new JLabel("Term Year");
termYearText = new JTextField(10);
calcButton = new JButton("Calc Simple Interest");
simpleInterestPanel = new JPanel();
calcButton.addActionListener(new financeFormListener());
simpleInterestPanel.add(principalMessage);
simpleInterestPanel.add(principalText);
simpleInterestPanel.add(yearlyRateMessage);
simpleInterestPanel.add(yearlyRateText);
simpleInterestPanel.add(termYearMessage);
simpleInterestPanel.add(termYearText);
simpleInterestPanel.add(calcButton);
}
private void doublingTimePanel(){
yearlyRateMessage = new JLabel("Yearly Rate");
yearlyRateText = new JTextField(10);
calcButton = new JButton("Calc Doubling Time");
calcButton.addActionListener(new financeFormListener());
doublingTimePanel = new JPanel();
doublingTimePanel.add(yearlyRateMessage);
doublingTimePanel.add(yearlyRateText);
doublingTimePanel.add(calcButton);
}
private void compoundInterestPanel(){
principalMessage = new JLabel("principal");
principalText = new JTextField(10);
yearlyRateMessage = new JLabel("Yearly Rate");
yearlyRateText = new JTextField(10);
termYearMessage = new JLabel("Term Year");
termYearText = new JTextField(10);
calcButton = new JButton("Calc Compound Interest");
compoundInterestPanel = new JPanel();
calcButton.addActionListener(new financeFormListener());
compoundInterestPanel.add(principalMessage);
compoundInterestPanel.add(principalText);
compoundInterestPanel.add(yearlyRateMessage);
compoundInterestPanel.add(yearlyRateText);
compoundInterestPanel.add(termYearMessage);
compoundInterestPanel.add(termYearText);
compoundInterestPanel.add(calcButton);
}
//Listener to choose which formula
private class financeBoxListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Object actionCommand = e.getSource();
String selection = (String) financeBox.getSelectedItem();
if(selection.equals("Present value")){
//financeFinderPanel.removeAll();
presentValuePanel();
add(presentValuePanel, BorderLayout.SOUTH);
pack();
}
else if(selection.equals("Simple interest")){
simpleInterestPanel();
add(simpleInterestPanel, BorderLayout.NORTH);
pack();
}
else if(selection.equals("Doubling time")){
doublingTimePanel();
add(doublingTimePanel, BorderLayout.SOUTH);
pack();
}
else if(selection.equals("Compound interest")){
compoundInterestPanel();
add(compoundInterestPanel, BorderLayout.NORTH);
pack();
}
else if(selection.equals("NONE")){
setSize(200, 150);
financeFinderPanel();
add(financeFinderPanel, BorderLayout.NORTH);
NONEMessage = new JLabel("PICK A SELECTION");
}
}
}
private class financeFormListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Calc Simple Interest")){
try{
double principal = Double.parseDouble(principalText.getText());
double yearlyRate = Double.parseDouble(yearlyRateText.getText());
double termYears = Double.parseDouble(termYearText.getText());
double interestRate = (principal * yearlyRate * termYears);
String msg = "Simple interest is: $" + dc.format(interestRate);
JOptionPane.showMessageDialog(null, msg);
}
catch(NumberFormatException r){
JOptionPane.showMessageDialog(null, "Please insert formula information");
}
}
else if(actionCommand.equals("Calc Present Value"))
{
try{
double principal = Double.parseDouble(principalText.getText());
double yearlyRate = Double.parseDouble(yearlyRateText.getText());
double termYears = Double.parseDouble(termYearText.getText());
double pValue = financeFormula.presentValue(principal, yearlyRate, termYears);
//double pValue = principal * (((1- Math.pow(1 + yearlyRate, -termYears))/ yearlyRate));
String msg = "Present value is: $" + dc.format(pValue);
JOptionPane.showMessageDialog(null, msg);
}
catch(NumberFormatException r){
JOptionPane.showMessageDialog(null, "Please insert formula information");
}
}
else if(actionCommand.equals("Calc Doubling Time")){
try{
double yearlyRate = Double.parseDouble(yearlyRateText.getText());
double dValue = financeFormula.doublingTime(yearlyRate);
String msg = "Doubling Time is: " + dc.format(dValue);
JOptionPane.showMessageDialog(null, msg);
}
catch(NumberFormatException r){
JOptionPane.showMessageDialog(null, "Please insert formula information");
}
}
else if(actionCommand.equals("Calc Compound Interest")){
try{
double principal = Double.parseDouble(principalText.getText());
double yearlyRate = Double.parseDouble(yearlyRateText.getText());
double termYears = Double.parseDouble(termYearText.getText());
double compoundInterest = financeFormula.compoundInterest(principal, yearlyRate, termYears);
String msg = "Compound Interest is: $" + dc.format(compoundInterest);
JOptionPane.showMessageDialog(null, msg);
}
catch(NumberFormatException r){
JOptionPane.showMessageDialog(null, "Please insert formula information");
}
}
}
}
private class ExitListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
public static void main(String[] args)
{
new newFinanceFullClass();
}
}
Again, use a CardLayout to help you swap your JPanels. You would create a JPanel and set its layout to CardLayout, and then you'd add the JPanels (the "cards") that you wish to swap into this holder JPanel using String constants, Strings that you will pass into the CardLayout's show(...) method to allow it to swap your components.
For instance, say you had an enum to hold your financial formula Strings, something like:
public enum FinanceFormula {
NONE("NONE"),
PRESENT_VALUE("Present value"),
SIMPLE_INTEREST("Simple interest"),
DOUBLING_TIME("Doubling time"),
COMPOUND_INTEREST("Compound interest"),
DECAF("Decaf");
private String name;
private FinanceFormula(String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return getName();
};
}
Then the CardLayout and its JPanel could be set up like so:
private CardLayout cardLayout = new CardLayout();
private JPanel cardHolderPanel = new JPanel(cardLayout);
and the JComboBox like below. This works because I have overridden the enum's to String method so that a proper name will display:
private JComboBox<FinanceFormula> comboBox = new JComboBox<>(FinanceFormula.values());
You would then add all the formula JPanels into the cardHolderPanel using String constants obtained from the enum:
// fill the cardHolderPanel with "cards", JPanels with formula:
cardHolderPanel.add(createNonePanel(), FinanceFormula.NONE.getName());
cardHolderPanel.add(createPresentValuePanel(), FinanceFormula.PRESENT_VALUE.getName());
cardHolderPanel.add(createSimpleInterestPanel(), FinanceFormula.SIMPLE_INTEREST.getName());
cardHolderPanel.add(createDoublingTimePanel(), FinanceFormula.DOUBLING_TIME.getName());
cardHolderPanel.add(createCompoundInterestPanel(), FinanceFormula.COMPOUND_INTEREST.getName());
cardHolderPanel.add(createDecafPanel(), FinanceFormula.DECAF.getName());
Then when you want to swap JPanels, simply pass in the appropriate String into the CardLayout's show method, and you're good:
private void combBoxActionPerformed(ActionEvent e) {
FinanceFormula selectedFormula = (FinanceFormula) comboBox.getSelectedItem();
cardLayout.show(cardHolderPanel, selectedFormula.getName());
}
The following program doesn't create any fancy formula JPanels, but it doesn't have to, since it is an MCVE built to demonstrate swapping JPanels only:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class NewFinance2 extends JPanel {
private CardLayout cardLayout = new CardLayout();
private JPanel cardHolderPanel = new JPanel(cardLayout);
private JComboBox<FinanceFormula> comboBox = new JComboBox<>(FinanceFormula.values());
public NewFinance2() {
// fill the cardHolderPanel with "cards", JPanels with formula:
cardHolderPanel.add(createNonePanel(), FinanceFormula.NONE.getName());
cardHolderPanel.add(createPresentValuePanel(), FinanceFormula.PRESENT_VALUE.getName());
cardHolderPanel.add(createSimpleInterestPanel(), FinanceFormula.SIMPLE_INTEREST.getName());
cardHolderPanel.add(createDoublingTimePanel(), FinanceFormula.DOUBLING_TIME.getName());
cardHolderPanel.add(createCompoundInterestPanel(), FinanceFormula.COMPOUND_INTEREST.getName());
cardHolderPanel.add(createDecafPanel(), FinanceFormula.DECAF.getName());
comboBox.addActionListener(e -> combBoxActionPerformed(e));
JPanel northPanel = new JPanel();
northPanel.add(comboBox);
setLayout(new BorderLayout());
add(cardHolderPanel, BorderLayout.CENTER);
add(northPanel, BorderLayout.NORTH);
}
private void combBoxActionPerformed(ActionEvent e) {
FinanceFormula selectedFormula = (FinanceFormula) comboBox.getSelectedItem();
cardLayout.show(cardHolderPanel, selectedFormula.getName());
}
// A bunch of dummy methods that don't create much
// Your real methods would create more complex JPanels
private JPanel createDecafPanel() {
return createPanel(FinanceFormula.DECAF);
}
private JPanel createCompoundInterestPanel() {
return createPanel(FinanceFormula.COMPOUND_INTEREST);
}
private JPanel createDoublingTimePanel() {
return createPanel(FinanceFormula.DOUBLING_TIME);
}
private JPanel createSimpleInterestPanel() {
return createPanel(FinanceFormula.SIMPLE_INTEREST);
}
private JPanel createPresentValuePanel() {
return createPanel(FinanceFormula.PRESENT_VALUE);
}
private JPanel createNonePanel() {
return createPanel(FinanceFormula.NONE);
}
// temporary method just for demonstration purposes
private JPanel createPanel(FinanceFormula financeFormula) {
JLabel label = new JLabel(financeFormula.getName());
label.setFont(label.getFont().deriveFont(Font.BOLD, 24f));
JPanel panel = new JPanel(new GridBagLayout());
panel.add(label);
panel.setPreferredSize(new Dimension(400, 300));
float split = 0.7f;
float h = (float) (split + Math.random() * (1f - split));
float s = (float) (split + Math.random() * (1f - split));
float b = (float) (split + Math.random() * (1f - split));
Color color = Color.getHSBColor(h, s, b);
panel.setBackground(color);
return panel;
}
private static void createAndShowGui() {
NewFinance2 mainPanel = new NewFinance2();
JFrame frame = new JFrame("Finance");
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());
}
}

Java Multidemensional Array Loop that inputs data with Button Action

Questions I am pulling my hair out over.
How do I get the array to add data to current index, then increment to the next index to add changed JTextField data for the next button press. currently I'm overwriting the same index.
I have tried to figure out actionlisteners for the button "Submit" that uses a counter with nesting of the loop. played with ideas from question 23331198 and 3010840 and 17829577 many others as a reference but didn't really get it to far. Most searches pull up info on managing buttons with arrays and creating button arrays so I assume I'm not using the correct wording to search with. I have read a few places that an MD array is not the best option to use.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class GUIandLogicTest extends JFrame
{
// Variable Decloration
private static JFrame mainFrame;
private static JPanel mainPanel;
private static JTextField fieldOne;
private static JTextField fieldTwo;
private static JTextArea textArea;
private static JLabel textFieldOneLabel;
private static JLabel textFieldTwoLabel;
double[][] tutArray = new double[10][2];
// int i =0 ;
// Set GUI method
private void gui()
{
// constructs GUI
mainFrame = new JFrame();
mainFrame.setSize(800, 800);
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
textFieldOneLabel = new JLabel("number 1");
mainPanel.add(textFieldOneLabel);
fieldOne = new JTextField(10);
mainPanel.add(fieldOne);
textFieldTwoLabel = new JLabel("number 2");
mainPanel.add(textFieldTwoLabel);
fieldTwo = new JTextField(10);
mainPanel.add(fieldTwo);
textArea = new JTextArea(50, 50);
mainPanel.add(textArea);
JButton Exit = new JButton("Quit");// Quits program
mainPanel.add(Exit);
Exit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
JButton submit = new JButton("Enter");
// Reads jfields and set varibles to be submitted to array
mainPanel.add(submit);
submit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
double txtField1 = Double
.parseDouble(fieldOne.getText().trim());
double txtField2 = Double
.parseDouble(fieldTwo.getText().trim());
if (txtField1 < 0)
{
}
if (txtField2 < 0)
{
}
int arrayIndex = 0;
tutArray[arrayIndex][0] = txtField1;
tutArray[arrayIndex][1] = txtField2;
arrayIndex++;
for (int i = 0; i < tutArray.length; i++)
{
textArea.append("Number1: " + tutArray[i][0] + " Number2: "
+ tutArray[i][1]);
textArea.append("\n");
textArea.append(String.valueOf(arrayIndex++));
textArea.append("\n");
// textArea.append(String.valueOf(arrayIndex++));
}
}
});
JButton report = new JButton();
// will be used to pull data out of array with formatting and math
mainFrame.setVisible(true);
mainFrame.add(mainPanel);
}
public static void main(String[] arg)
{
GUIandLogicTest GUIandLogic = new GUIandLogicTest();
GUIandLogic.start();
}
public void start()
{
gui();
}
}
This is what I was looking for thanks for the help!
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class GUIandLogicTest extends JFrame
{
// Variable Decloration
private static JFrame mainFrame;
private static JPanel mainPanel;
private static JTextField fieldOne;
private static JTextField fieldTwo;
private static JTextArea textArea;
private static JLabel textFieldOneLabel;
private static JLabel textFieldTwoLabel;
double[][] tutArray = new double[10][2];
int arrayIndex = 0;
// int i =0 ;
// Set GUI method
private void gui()
{
// constructs GUI
mainFrame = new JFrame();
mainFrame.setSize(800, 800);
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
textFieldOneLabel = new JLabel("number 1");
mainPanel.add(textFieldOneLabel);
fieldOne = new JTextField(10);
mainPanel.add(fieldOne);
textFieldTwoLabel = new JLabel("number 2");
mainPanel.add(textFieldTwoLabel);
fieldTwo = new JTextField(10);
mainPanel.add(fieldTwo);
textArea = new JTextArea(50, 50);
mainPanel.add(textArea);
JButton Exit = new JButton("Quit");// Quits program
mainPanel.add(Exit);
Exit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
JButton submit = new JButton("Enter");
// Reads jfields and set varibles to be submitted to array
mainPanel.add(submit);
submit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
double txtField1 = Double
.parseDouble(fieldOne.getText().trim());
double txtField2 = Double
.parseDouble(fieldTwo.getText().trim());
textArea.setText("");
if (txtField1 < 0)
{
}
if (txtField2 < 0)
{
}
tutArray[arrayIndex][0] = txtField1;
tutArray[arrayIndex][1] = txtField2;
arrayIndex++;
for (int i = 0; i < arrayIndex; i++)
{
textArea.append("Number1: " + tutArray[i][0] + " Number2: "
+ tutArray[i][1]);
// textArea.append("\n");
//textArea.append(String.valueOf(arrayIndex++));
textArea.append("\n");
// textArea.append(String.valueOf(arrayIndex++));
}
}
});
JButton report = new JButton();
// will be used to pull data out of array with formatting and math
mainFrame.setVisible(true);
mainFrame.add(mainPanel);
}
public static void main(String[] arg)
{
GUIandLogicTest GUIandLogic = new GUIandLogicTest();
GUIandLogic.start();
}
public void start()
{
gui();
}
}
You can add the index as a field in your main object:
protected int index;
in your actionPerformed you increase index:
index++;
NOTE:
But why do you extend from JFrame AND use the field mainFrame?
you can use
this.setSize(800,800);
this.add(mainPanel);
Please declare (because of extends JFrame):
private static final long serialVersionUID = 1L;
Please start the name of an object with a lower case letter:
JButton exit = new JButton("Quit");

moving data between classes with get and set

Ok, I am confused (and new to Java) about getters and setters. The code that I am working on will have multiple classes in a single container. The classes are UserInput, Totals, Greeting, and Checkboxes. The problem that I am having is that the UserInput panel accepts input from the user, and the data should be sent from the JTextFields to the complimentary fields in the Totals panel. I have been trying to use an action listener for the enter press, but to no avail.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.*;
import javax.swing.border.TitledBorder;
/**
*
* User input panel
* first panel
* has JTextFields for input of date for the hw/h, hours, and gallons
**/
public class UserInput extends JFrame
{
//variables/attributes
public double kwh;
public double hours;
public double gallons;
public double kFinal;
public double hFinal;
public double gFinal;
String i; //to hold the string from the textbox
//JFrame componants
private final JTextField kwhFieldU;
private final JTextField hoursFieldU;
private final JTextField gallonsFieldU;
private final JLabel kwhLabel;
private final JLabel hoursLabel;
private final JLabel gallonsLabel;
private final JPanel panel;
TextFieldHandler handler = new TextFieldHandler();
/**
*constructor
*/
public UserInput()
{
super("User Input");
// create the Grid
setLayout (new GridLayout (3,2));
//create the fields
kwhFieldU = new JTextField("Enter Kw/H", 15);
hoursFieldU = new JTextField("Enter Hours", 15);
gallonsFieldU = new JTextField("Enter Gallons", 15);
//create the labels
kwhLabel = new JLabel ("Kw/H");
hoursLabel = new JLabel ("Hours");
gallonsLabel = new JLabel ("Gallons");
//create the panel
panel = new JPanel();
kwhFieldU.addActionListener (handler);
hoursFieldU.addActionListener (handler);
gallonsFieldU.addActionListener (handler);
//Add a border
TitledBorder titled;
titled = BorderFactory.createTitledBorder("User Input");
//Add the tiles into the grid
add(kwhFieldU);
add(kwhLabel);
add(hoursFieldU);
add(hoursLabel);
add(gallonsFieldU);
add(gallonsLabel);
//Add panel to context frame
add(panel);
//display the window
setVisible(true);
}
//The get method to retrieve the user inputs
Scanner keyboard = new Scanner(System.in);
//get and set methods to store and retrieve date within the variables
//for kwh, hours, and gallons
/**
*
* #return
*/
/**
*
* #param k
*/
public void setKwh(double k)
{
kwh = k;
}
public double getKwh()
{
return kwh;
}
//get and set methods for hours
/**
*
* #param h
*/
public void setHours (double h)
{
hours = h;
}
public double getHours ()
{
return hours;
}
//get and set methods for gallons
/**
*
* #param g
*/
public void setGallons(double g)
{
gallons = g;
}
/**
*
* #return
*/
public double getGallons()
{
return gallons;
}
//Now add action listeners??? we will try it add the inner class to
//retrieve the variable data
/**
*
*/
private class TextFieldHandler implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == kwhFieldU)
{
//relates string i with the action command
i = e.getActionCommand();
//turns string i into a double in variable kFinal
double kFinal = Double.parseDouble (i);
//relates kFinal with kwh
kwh = kFinal;
}
if (e.getSource() == hoursFieldU)
{
i = e.getActionCommand();
double hFinal = Double.parseDouble (i);
hours = hFinal;
}
if (e.getSource() == gallonsFieldU)
{
i = e.getActionCommand();
double gFinal = Double.parseDouble (i);
gallons = gFinal;
}
}
}
}
package applianceutilitycalculator;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
/**
*
* #author Gerber
*/
public class Totals extends JFrame
{
//constants for the grid layout mgr for the Total panel
private JPanel Panel;
private JLabel kwhLabel;
private JLabel hoursLabel;
private JLabel gallonsLabel;
private JLabel totalLabel;
public JTextField kwhFieldT;
public JTextField hoursFieldT;
public JTextField gallonsFieldT;
private JTextField totalFieldT;
public Totals()
{
super();
// create the Grid
setLayout (new GridLayout (4,2));
//Create the fields
kwhFieldT = new JTextField(15);
hoursFieldT = new JTextField(15);
gallonsFieldT = new JTextField(15);
totalFieldT = new JTextField(15);
//create the labels
kwhLabel = new JLabel ("Kw/H");
hoursLabel = new JLabel ("Hours");
gallonsLabel = new JLabel ("Gallons");
totalLabel = new JLabel ("Totals");
//Add a border
TitledBorder titled;
titled = BorderFactory.createTitledBorder("Totals");
//add panels to grid
add(kwhFieldT);
add(kwhLabel);
add(hoursFieldT);
add(hoursLabel);
add(gallonsFieldT);
add(gallonsLabel);
add(totalFieldT);
add(totalLabel);
//Add panel to context frame
add(Panel);
//display the window
setVisible(true);
}
//add actionperformed to get the return value to fill the text fields
//need to convert it from double into string ???
/**
*
* #param evt
*/
public void actionPerformed(ActionEvent evt)
{
kwhFieldT = kwh.getText();
hoursFieldT = hours.getText();
gallonsFieldT = gallons.getText();
}
}

Java GUI won't display a prompt I want it to

So my program is designed to take in 2 values, make a calculation, and give this calculations value. I want to display it as a prompt in the GUI in the actionPerformed section after the button is clicked. It looks like it should show up but I can't seem to find why it isn't? It's "prompt2" that isn't showing up. Thanks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Windchill extends JFrame implements ActionListener{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private String degree;
private String wind;
private int degreeInt;
private int windInt;
private double windChillInt;
private JButton windButton;
private JLabel prompt;
private JLabel prompt1;
private JLabel prompt2;
private JTextField inputLine;
private JTextField inputLine1;
public Windchill(){
setTitle("Windchill");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
inputLine = new JTextField();
inputLine.setColumns(3);
inputLine.addActionListener(this);
contentPane.add(inputLine);
prompt = new JLabel();
prompt.setText("Enter the degrees in Farienheight ");
prompt.setSize(150,25);
contentPane.add(prompt);
inputLine1 = new JTextField();
inputLine1.setColumns(3);
inputLine1.addActionListener(this);
contentPane.add(inputLine1);
prompt1 = new JLabel();
prompt1.setText("Enter the wind speed in MPH");
prompt1.setSize(150,25);
contentPane.add(prompt1);
windButton = new JButton("Calculate windchill");
contentPane.add(windButton);
windButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event){
if (event.getSource() instanceof JButton){
JButton clickedButton = (JButton) event.getSource();
if (clickedButton == windButton){
degree = inputLine.getText();
degreeInt = Integer.parseInt(degree);
wind = inputLine1.getText();
windInt = Integer.parseInt(wind);
windChillInt = 0.08 * (degreeInt - 91.4)*(3.71* (Math.sqrt(windInt)) + 5.81 - 0.25 *windInt) + 91.4;
prompt2 = new JLabel();
prompt2.setText("The windchill is " + windChillInt);
prompt2.setSize(150,25);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(prompt2);
}
}
}
public static void main(String[] args) {
Windchill frame;
frame = new Windchill();
frame.setVisible(true);
}
}
prompt2 isn't showing up as Swing containers need to be validated for any newly added components can be visible. Also it's good practice to repaint. You could do:
contentPane.revalidate();
contentPane.repaint();
Side Notes:
It is unnecessary to set the layout again for the your ActionListener
contentPane.add(prompt2) can be simplified to add(prompt2)
Alternatively, you could just add the prompt2 JLabel to the contentPane on startup with empty String content and call setText to update.

I'm trying to create a calculator using JFrame and having some difficulties

Basically it's getting the thing to show up so I can test it and made sure I'm on the right track. This is the code for my main "calculator" file:
package simplecalculator;
import javax.swing.JFrame;
import javax.swing.UIManager;
public class Calculator {
public static void main(String[] args) {
JFrame calculatorFrame = new Listener();
calculatorFrame.setSize(1000, 0x3e8);
calculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
calculatorFrame.setVisible(true);
}
}
And I have a separate Listener file for the classes:
package simplecalculator;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Listener extends JFrame {
private JLabel enterFirstNumber;
private JLabel enterSecondNumber;
private JLabel resultLabel;
private JTextField getFirstNumber;
private JTextField getSecondNumber;
private JButton addition;
private JButton subtraction;
private JButton multiplication;
private JButton division;
private JPanel panelOne;
private JPanel panelTwo;
private JPanel panelThree;
private static final int frameWidth = 1000;
private static final int frameHeight = 1000;
int firstNumber;
int secondNumber;
double finalNumber;
public void Calc(){
setSize(frameWidth, frameHeight);
enterFirstNumber = new JLabel("Enter First Number: ");
getFirstNumber = new JTextField("0", 12);
enterSecondNumber = new JLabel("Enter Second Number: ");
getSecondNumber = new JTextField("0", 12);
}
public void buttons()
{
addition = new JButton("+");
addition.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
firstNumber = Integer.parseInt(getFirstNumber.getText());
secondNumber = Integer.parseInt(getSecondNumber.getText());
finalNumber = firstNumber + secondNumber;
resultLabel.setText("" + finalNumber);
}
});
subtraction = new JButton("-");
subtraction.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
firstNumber = Integer.parseInt(getFirstNumber.getText());
secondNumber = Integer.parseInt(getSecondNumber.getText());
finalNumber = firstNumber - secondNumber;
resultLabel.setText("" + finalNumber);
}
});
multiplication = new JButton("*");
multiplication.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
firstNumber = Integer.parseInt(getFirstNumber.getText());
secondNumber = Integer.parseInt(getSecondNumber.getText());
finalNumber = firstNumber * secondNumber;
resultLabel.setText("" + finalNumber);
}
});
division = new JButton("/");
division.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
firstNumber = Integer.parseInt(getFirstNumber.getText());
secondNumber = Integer.parseInt(getSecondNumber.getText());
finalNumber = firstNumber / secondNumber;
resultLabel.setText("" + finalNumber);
}
});
}
private void panels(){
panelOne = new JPanel();
panelOne.setLayout(new GridLayout(2, 2));
panelOne.add(enterFirstNumber);
panelOne.add(getFirstNumber);
panelOne.add(enterSecondNumber);
panelOne.add(getSecondNumber);
panelTwo = new JPanel();
panelTwo.setLayout(new GridLayout(2, 2));
panelTwo.add(addition);
panelTwo.add(subtraction);
panelTwo.add(multiplication);
panelTwo.add(division);
panelThree = new JPanel();
panelThree.add(resultLabel);
}
}
Basically all I need to know is:
1) Am I on the right track?
2) And how can I get an actual calculator rather than just a blank applet?
Sorry if I sound like a noob; I'm a programmin student and I already spent about 12 hours trying to figure this one out.
You never add any component to the JFrame. So obviously, it doesn't contain anything. You should add a constructor to your JFrame subclass, and make it add some component(s) to the frame.
And you should also indent your code, to make it readable, and respect Java naming conventions.
There are lot of pitfalls when trying to build ever basic calculator: in GUI layout, when entering/formatting numbers and providing required precision etc.
You can use this example to skip most of them on start:
https://github.com/plokhotnyuk/calculator/tree/fee1b741aa74d659b8e30ad66d26d9ca6a2f6bc5
Main idea (to start from end-to-end tests) is borrowed from this amazing book:
http://www.growing-object-oriented-software.com/
Feel free to fork and hack!
Enjoy developing with TDD & executable specifications!!!

Categories

Resources