I'm trying to make an applet that converts binary to decimal and decimal to binary. I have already written applets that do each individual but now I want to make one which uses radio buttons to select the conversion the user wants to do and then have the convert button carry out that conversion. I am stuck at the moment and not quite sure where to go from here... It doesn't currently compile.
I also want to include an arrow that points either up or down depending on the radio button selected... I've tried to implement the Unicode for said arrow into a JLabel but they do not accept characters, how would one go about this?
Thank you very much any help is greatly appreciated.
Heres my current mess of code...
EDIT:
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
public class binaryAndDecimalConvert extends JApplet
{
private JPanel bPanel;
private JPanel dPanel;
private JPanel buttonPanel;
private JPanel radioPanel;
private JPanel arrowPanel;
private JLabel arrowUp;
private JLabel arrowDown;
private JTextField binaryTxt;
private JTextField decimalTxt;
private ButtonGroup radioButtonGroup;
private JRadioButton binaryConvButton;
private JRadioButton decimalConvButton;
public void init()
{
Font font = new Font("display font", Font.BOLD, 15);
//build the panels
buildBpanel();
buildArrowPanel();
buildDpanel();
buildButtonPanel();
buildRadioPanel();
//create Layout Manager.
setLayout(new GridLayout(5, 1));
// Add the panels to the content pan.
add(bPanel);
add(arrowPanel);
add(dPanel);
add(buttonPanel);
add(radioPanel);
}
private void buildDpanel()
{
dPanel = new JPanel();
dPanel.setBackground(Color.pink);
JLabel message2 = new JLabel("Decimal Number: ");
decimalTxt = new JTextField(15);
dPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
dPanel.add(message2);
dPanel.add(decimalTxt);
}
private void buildBpanel()
{
//create the panel
bPanel = new JPanel();
bPanel.setBackground(Color.pink);
//create a label to display a mssage
JLabel message1 = new JLabel("Binary Number: ");
//create a text field for the binary number
binaryTxt = new JTextField(15);
//create a layout manager for the panel
bPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
///add the label and text field to the panel
bPanel.add(message1);
bPanel.add(binaryTxt);
}
public void buildRadioPanel()
{
radioPanel = new JPanel();
radioPanel.setBackground(Color.pink);
binaryConvButton = new JRadioButton("Binary to Decimal");
decimalConvButton = new JRadioButton("Decimal to Binary");
radioButtonGroup = new ButtonGroup();
radioButtonGroup.add(binaryConvButton);
radioButtonGroup.add(decimalConvButton);
binaryConvButton.addActionListener(new RadioButtonListener());
decimalConvButton.addActionListener(new RadioButtonListener());
binaryConvButton.addActionListener(new RadioButtonListener());
decimalConvButton.addActionListener(new RadioButtonListener());
radioPanel.add(binaryConvButton);
radioPanel.add(decimalConvButton);
binaryConvButton.setEnabled(true);
}
public void buildArrowPanel()
{
arrowPanel = new JPanel();
arrowUp = new JLabel("\u2191");
arrowDown = new JLabel("\u2193");
arrowPanel.setBackground(Color.pink);
arrowPanel.add(arrowDown);
}
private class RadioButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == binaryConvButton)
{
arrowPanel.add(arrowUp);
}
else if(e.getSource() == decimalConvButton)
arrowPanel.add(arrowDown);
}
}
private void buildButtonPanel()
{
buttonPanel = new JPanel();
buttonPanel.setBackground(Color.pink);
JButton convButton = new JButton("Convert");
convButton.addActionListener(new ButtonListener());
buttonPanel.add(convButton);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//binary to decimal conversion
String decimalNum= "";
int decimal1 = 0;
String binaryNum = "";
int power = 1;
int dec;
if(e.getSource() == decimalConvButton)
{
binaryNum=binaryTxt.getText();
for(int i = 1; i <= binaryNum.length(); i++)
{
if(binaryNum.charAt(binaryNum.length()-i) == '1')
{
decimal1 = (decimal1 + power);
}
power = (power*2);
}
decimalNum = Integer.toString(decimal1);
decimalTxt.setText(decimalNum);
}
//decimal to binary
if(e.getSource() == binaryConvButton)
{
dec = Integer.parseInt(decimalTxt.getText());
while (dec != 0)
{
binaryNum = (dec % 2) + binaryNum;
dec /= 2;
}
binaryTxt.setText(binaryNum);
}
}
}
}
One problem you've got is that you are re-declaring a class field inside of a method and effectively "shadowing" the field making it invisible. That field is "binary"
Here's where you initially declare it:
public class BinaryAndDecimalConvert extends JApplet {
private JPanel bPanel;
//...
private JTextField binary;
Here's where you shadow it:
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String decimalNum = "";
int decimal1 = 0;
String binaryNum = "";
int power = 1;
String binary; // **** redeclared here ****
if (binaryToDec = true) {
binaryNum = binary.getText(); // so this won't work
Solution: don't give variables local to a method the same name as important class fields.
Next, you try to call setText() on a String variable, binaryNumber:
binaryNumber.setText(decimal1);
String doesn't have such a method, so get rid of this method call.
Related
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());
}
}
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());
}
}
I have assigned the JButton cl to clear,
however in my program, and using (e.getSource() == cl)... it does not setText("") for each text field
I am not sure wether it is because I used an array for the JTextField or what...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class EmployeesApplet extends JApplet implements ActionListener
{
public JButton sd = new JButton ("Salaried");
public JButton hr = new JButton ("Hourly");
public JButton cm = new JButton ("Commissioned");
public JButton cl = new JButton ("Clear");
private final int FIELDS = 8,
FIELD_WIDTH = 20;
private String[] strings = new String[FIELDS];
private TextFieldWithLabel[] tf = new TextFieldWithLabel[FIELDS];
private JTextArea ta = new JTextArea(5,25);
// Add arrays for readFields() method
public void init()
{
String[] s = {"First Name", "Last Name", "Employee ID", "(a) Salaried: Weekly Salary", "(b1) Hourly 1: Rate Per Hour",
"(b2) Hourly 2: Hours Worked" , "(c1) Commissioned: Rate", "(c2) Commissioned: Gross Sales" };
//----------------------
// Set up the Structure
//----------------------
Container c = getContentPane();
JPanel f = new JPanel(new FlowLayout());
JPanel b = new JPanel(new BorderLayout(2,0));
JPanel glb = new JPanel(new GridLayout(8,1,0,2));
JPanel gtf = new JPanel(new GridLayout(8,1,0,2));
JPanel flb = new JPanel(new FlowLayout());
// Add FlowLayout to the container
c.add(f);
// Add BorderLayout to the FlowLayout
f.add(b);
//---------------------------------------
//Add JPanels to the BorderLayout regions
//---------------------------------------
// Add JLables to GridLayout in West
b.add(glb, BorderLayout.WEST);
for (int i = 0; i < tf.length; i++)
{
tf[i] = new TextFieldWithLabel(s[i], FIELD_WIDTH);
glb.add(tf[i].getLabel());
}
// Add JTextFeilds to GridLayout in East
b.add(gtf, BorderLayout.EAST);
for (int i = 0; i < tf.length; i++)
{
tf[i] = new TextFieldWithLabel(s[i], FIELD_WIDTH);
tf[i].getTextField();
gtf.add(tf[i].getTextField());
}
// Add JButtons to FlowLayout in South
b.add(flb, BorderLayout.SOUTH);
flb.add(sd);
flb.add(hr);
flb.add(cm);
flb.add(cl);
sd.addActionListener(this);
hr.addActionListener(this);
cm.addActionListener(this);
cl.addActionListener(this);
// Add JTextArea and make it not editable
f.add(ta);
ta.setEditable(false);
}
//---------------------------------------
// Read all the JTextFields and
// save the contents in a parallel array
//---------------------------------------
private void readFields()
{
for (int i = 0; i < tf.length; i++) // or FIELDS
strings[i] = tf[i].getText();
}
//---------------------------------------------------------------------------
// Returns true if required JTextFields for selected employee are not empty
// Checks required JTextFields in top down order,
// displays error in stats are for first req that is empty and places focus
//----------------------------------------------------------------------------
private boolean fieldsExist(int i, int i2)
{
for (int index = 0; index < tf.length; index++)
{
}
showStatus("field is empty"); // Diplays error message in status area
tf[i].requestFocus(); // places focus in JTextField
return true;
}
//-----------------------------------------------------------------------------------------
// Returns true if all non-required JTextFields for the seleceted employee are empty
// Checks non-required JTextFields in top-down order ,
// displays error message in first non-req JTextField that is not empty and places focus
//-----------------------------------------------------------------------------------------
private boolean fieldsEmpty(int i, int i2)
{
showStatus("field should be empty"); // Diplays error message in status area
tf[i].requestFocus(); // Places focus in JTextField
return true;
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == cl)
{
for (int i = 0; i < tf.length; i++)
{
tf[i].setText("");
tf[1].requestFocus();
}
} // End clear if
}
}
and here is the TextFieldWithLabel class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
public class TextFieldWithLabel extends JTextField
{
private JTextField text_field;
private JLabel label;
private final static int WIDTH = 20;
public TextFieldWithLabel (String s, int w)
{
label = new JLabel(s);
text_field = new JTextField(w);
}
public JLabel getLabel() {return label;}
public JTextField getTextField() {return text_field;}
public String getText() {return text_field.getText();}
}
You want to set the text of the text_field field of your TextFieldWithLabel, not the text of TextFieldWithLabel.
tf[i].getTextField().setText("");
tf[1].getTextField().requestFocus();
Note that you could get rid of this text_field attribute, and use TextFieldWithLabel directly as the JTextField instead .
Better yet, have TextFieldWithLabel not extend JTextField, since it has no use, it is only a container class for two components.
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 ;)
Alright so my program is getting the user's input to figure out the prime numbers (up to the max which the user entered), and then display these results in a scrollable JFrame. I have done all of that (I believe so at least) but keep getting one error when I try and compile it. Also, if you see any other mistakes that I have missed feel free to let me know!
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PrimeNumbersJ extends JFrame
{
private static final int WIDTH=400;
private static final int HEIGHT=300;
//JFrame Components
private JLabel jlblMaxNumber;
private JTextArea jtaOutput;
private JTextField jtfMaxNumber;
private JButton jbtnCalculate, jbtnClear, jbtnExit;
private CalculateButtonHandler calculateHandler;
private ClearButtonHandler clearHandler;
private ExitButtonHandler exitHandler;
private JScrollPane scrollingResult;
private JPanel jpnlTop = new JPanel();
private JPanel jpnlCenter = new JPanel();
private JPanel jpnlBottom = new JPanel();
public PrimeNumbersJ()
{
// Set the title and Size:
setTitle("Prime Numbers with JFrame");
setSize(WIDTH, HEIGHT);
jpnlBottom.setLayout(new GridLayout(1, 3));
// Instantiate the JLabel components:
jlblMaxNumber = new JLabel("Enter the Largest Number to test: ", SwingConstants.LEFT);
// Instantiate the JTextFields:
jtfMaxNumber = new JTextField(10);
// Make the JTextArea scrollable:
jtaOutput = new JTextArea(10,1);
scrollingResult = new JScrollPane(jtaOutput);
// Instantiate and register the Calculate button for clicks events:
jbtnCalculate = new JButton("Calculate");
calculateHandler = new CalculateButtonHandler();
jbtnCalculate.addActionListener(calculateHandler);
// Instantiate and register the Clear button for clicks events:
jbtnClear = new JButton("Clear");
clearHandler = new ClearButtonHandler();
jbtnClear.addActionListener(clearHandler);
// Instantiate and register the Exit button for clicks events:
jbtnExit = new JButton("Exit");
exitHandler = new ExitButtonHandler();
jbtnExit.addActionListener(exitHandler);
// Assemble the JPanels:
jpnlTop.setLayout(new GridLayout(1, 2));
jpnlTop.add(jlblMaxNumber);
jpnlTop.add(jtfMaxNumber);
jpnlCenter.setLayout(new GridLayout(1, 1));
jpnlCenter.add(scrollingResult);
jpnlBottom.setLayout(new GridLayout(1, 3));
jpnlBottom.add(jbtnCalculate);
jpnlBottom.add(jbtnClear);
jpnlBottom.add(jbtnExit);
// Start to add the components to the JFrame:
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
pane.add(jpnlTop, BorderLayout.NORTH);
pane.add(jpnlCenter, BorderLayout.CENTER);
pane.add(jpnlBottom, BorderLayout.SOUTH);
// Show the JFrame and set code to respond to the user clicking on the X:
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
jpnlTop.setLayout(new GridLayout(1, 3));
jpnlTop.add(jlblMaxNumber);
jpnlTop.add(jtfMaxNumber);
jpnlCenter.setLayout(new GridLayout(1, 1));
jpnlCenter.add(scrollingResult);
jpnlBottom.add(jbtnCalculate);
jpnlBottom.add(jbtnClear);
jpnlBottom.add(jbtnExit);
// Show the JFrame and set code to respond to the user clicking on the X:
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}//End Constructor
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int iRemainder,iPrimeCheck;
int iNumbertoTest = 0;
boolean bValidInput = true;
String sPrime ="";
try
{
iNumbertoTest = Integer.parseInteger(jtfMaxNumber.getText());
}
catch (Exception aeRef)
{
JOptionPane.showMessageDialog(null,"Enter the Max Number to Test.", getTitle(), JOptionPane.WARNING_MESSAGE);
bValidInput = false;
}// end of catch
if ( bValidInput )
{
for(iNumberToTest = 1;iNumberToTest <= 100;iNumberToTest++) {
iRemainder = 0;
for(iPrimeCheck = 1;iPrimeCheck <= iNumberToTest;iPrimeCheck++){
if(iNumberToTest % iPrimeCheck == 0){
iRemainder++;
}
}
if(iRemainder == 2 || iNumberToTest == 1)
{
String sNumber = Integer.toString(iNumberToTest);
sPrime = sPrime + (sNumber + "\n");
}
}
// Populate the output by using the methods in the user defined class::
jtaOutput.append("The Prime Numbers Are: \n" + sPrime + "\n");
} // end if
} //end ActionPerformed
}//End CalculateButtonHandler
private class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}//end ExitButtonHandler
private class ClearButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
jtfMaxNumber.setText("");
jtaOutput.setText("");
}
} // end ClearButtonHandler
public static void main(String args[])
{
PrimeNumbersJ primNumJ = new PrimeNumbersJ();
}
}
Error
java:120: cannot find symbol
symbol : method parseInteger(java.lang.String)
location: class java.lang.Integer
iMaxNumber = Integer.parseInteger(jtfMaxNumber.getText());
^
Integer.parseInteger()
does not exist.
Are you looking for Integer.parseInt() ???
change Integer.parseInteger() to
Integer.parseInt()
also declare int iNumberToTest as class variable in CalculateButtonHandler class
The Integer class doesn't contain method called parseInteger. Use parseInt instead.