Using JButtons to clear JTextFields - java

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.

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());
}
}

Get values out from JTextField and convert to int

eqn.setABC() takes in three integers, but CoeffA, CoeffB, and CoeffC are JTextFields.
How can I take the input from the JTextFields, convert it to ints, and feed it to eqn.setABC()?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FactorQuadraticUI extends JFrame implements ActionListener {
public JTextField coeffA;
public JTextField coeffB;
public JTextField coeffC;
public JTextField factors; //contains answer in form (px+q)(rx+s)
public JButton findFactors;
public QuadraticEqn eqn;
static final long serialVersionUID = 12345L;
public FactorQuadraticUI(QuadraticEqn e) {
super("Quadratic Equation Factor Finder");
eqn = e;
Container c = getContentPane();
c.setLayout(new FlowLayout());
JPanel eqnArea = new JPanel(new FlowLayout());
coeffA = new JTextField(2);
eqnArea.add(coeffA);
eqnArea.add(new JLabel("x^2 +"));
coeffB = new JTextField(2);
eqnArea.add(coeffB);
eqnArea.add(new JLabel("x +"));
coeffC = new JTextField(2);
eqnArea.add(coeffC);
//////////JTextField f1 = new JTextField("-5");
//control button: find factors
findFactors = new JButton("factor!");
findFactors.addActionListener(this);
eqnArea.add(findFactors);
c.add(eqnArea);
//output area
factors = new JTextField(27);
factors.setEditable(false);
c.add(factors);
this.setBounds(100, 100, 350, 100);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
//"factor" button pressed
//how to get the values out
// and make them ints
eqn.setABC(coeffA, coeffB, coeffC);
factors.setText(eqn.toString() + " = " + eqn.getQuadraticFactors() );
factors.setText("testing...");
}
}
You can extract integers from JTextField using:
Integer.parseInt(jtextField.getText());
This command has two parts:
First part:
JTextField.getText() // This gets text from text field. Ofcourse replace "JTextField" with your textfield's name.
Second part:
Integer.parseInt(..) // This gets/parses the integer values in a string. We are inputting the string here from above step.

Components don't get updated in my second frame

Ok so I have two JFrames. The first one is my main program. The second one is accessed by selecting an option on the menu of the first one. This second frame allows the user to enter values for different grades. For example, they are able to set the range of the grade "A" from 90 - 100 or from 85 - 100. Furthermore, they can add new grades like "A+" or "B-", and set ranges for them too.
If the user wants to add a grade, he uses the "Add Row" option on the menu titled "Actions". The frame prompts the user to enter the grade he wants to add (A+, or B-), he enters it and it should create a new row, with that grade, in the right place.
So there is where my problem begins. The headings and the grades are stored in an ArrayList of JLabels, and I wrote an algorithm to accurately predict the index of the new grade entered by the user ("B+" would be after "A-" and before "B"). So the entered grade is on the right position in my labels ArrayList. BUT for some reason, the new label doesn't add itself to my panel, and so cannot be seen by the user.
Some other information:
1. The panel uses grid bag layout - columns = 3 and rows = number of grades.
2. Each grade has two text fields, where the user enters the range value (I haven't added any functionality to the text fields, they're just there so I don't forget about them)
Here is the code:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
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 Adjustments implements ActionListener {
private JMenuBar menubar; // for adding more grades
private ArrayList<JTextField> textFields;
private ArrayList<JLabel> labels;
private JPanel panel;
private JFrame frame;
private ArrayList<GridBagConstraints> gbcs;
private JButton button;
#Override
public void actionPerformed(ActionEvent e) {
frame = new JFrame();
frame.setSize(Frame.LENGTH, Frame.HEIGHT);
frame.setDefaultCloseOperation(1);
frame.setTitle("Adjustments");
createComponents();
frame.setVisible(true);
}
private void createComponents() {
panel = new JPanel();
panel.setLayout(new GridBagLayout());
createLabels();
createTextFields();
createMenuBar();
createLayout();
frame.setJMenuBar(menubar);
}
private void createLayout() {
// This creates the layout. First makes the constraints, then adds everything to the panel
gbcs = new ArrayList<GridBagConstraints>();
for (int i = 0; i < labels.size() - 2; i++) {
for (int j = 0; j < 3; j++) {
gbcs.add(new GridBagConstraints());
gbcs.get((i * 3) + j).gridx = 100 + (100 * j);
gbcs.get((i * 3) + j).gridy = 100 + (100 * i);
}
}
// This is for the three headings on the top - "Grade", "From" and "To"
for (int i = 0; i < 3; i++) {
panel.add(labels.get(i), gbcs.get(i));
}
int l = 3, tf = 0; // l is the labels count, tf is for text fields
for (int i = 3; i < gbcs.size(); i++) {
if (i % 3 == 0) {
panel.add(labels.get(l), gbcs.get(i));
l++;
} else {
panel.add(textFields.get(tf), gbcs.get(i));
tf++;
}
}
frame.add(panel);
}
private void createLabels() {
// all the labels are made
labels = new ArrayList<JLabel>();
labels.add(new JLabel("Grade"));
labels.add(new JLabel("From"));
labels.add(new JLabel("To"));
labels.add(new JLabel("A"));
labels.add(new JLabel("B"));
// labels.add(new JLabel("B-"));
labels.add(new JLabel("C"));
labels.add(new JLabel("D"));
}
private void createTextFields() {
// there are two text fields on each row, starting from the 2nd
textFields = new ArrayList<JTextField>();
for (int i = 0; i < 8; i++) {
textFields.add(new JTextField(5));
}
}
private void createMenuBar() {
menubar = new JMenuBar();
// create and add the menu/menu items to the menubar
JMenu actions = new JMenu("Action");
JMenuItem addrow = new JMenuItem("Add Row");
actions.add(addrow);
class Listener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String newGrade = JOptionPane.showInputDialog(frame, "What grade is this?");
if (newGrade.length() == 2) { // e.g.: ("B+")
String s = newGrade.substring(0, 1);
int index = 0; // index is the location of grade in the labels ArrayList
for (int i = 3; i < labels.size(); i++) {
if (s.equals(labels.get(i).getText())) {
index = i;
break;
}
}
String s2 = newGrade.substring(1);
if (s2.equals("-")) index++;
labels.add(index, new JLabel(newGrade));
textFields.add(new JTextField(5));
textFields.add(new JTextField(5));
}
panel.removeAll(); // removes everything from the panel to be readied again
createLayout(); // creates the layout everything
}
}
addrow.addActionListener(new Listener());
menubar.add(actions);
}
}
Why won't the new grades display on my frame?
Thanks for your help!
You've got some errors in your code.. but i have a solution for you.
Short answer: You forgot panel.revalidate(); & panel.repaint(); after recreating layout new.
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
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 gui implements ActionListener {
private JMenuBar menubar; // for adding more grades
private ArrayList<JTextField> textFields;
private ArrayList<JLabel> labels;
private JPanel panel;
private JFrame frame;
private ArrayList<GridBagConstraints> gbcs;
private JButton button;
#Override
public void actionPerformed(ActionEvent e) {
frame = new JFrame();
frame.setSize(Frame.WIDTH, Frame.HEIGHT);
frame.setDefaultCloseOperation(1);
frame.setTitle("Adjustments");
createComponents();
frame.setVisible(true);
frame.pack();
}
private void createComponents() {
panel = new JPanel();
panel.setLayout(new GridBagLayout());
createLabels();
createTextFields();
createMenuBar();
createLayout();
frame.add(panel);
frame.setJMenuBar(menubar);
}
private void createLayout() {
// This creates the layout. First makes the constraints, then adds
// everything to the panel
gbcs = new ArrayList<GridBagConstraints>();
for (int i = 0; i < labels.size()-2; i++) {
for (int j = 0; j < 3; j++) {
gbcs.add(new GridBagConstraints());
gbcs.get((i * 3) + j).gridx = 100 + (100 * j);
gbcs.get((i * 3) + j).gridy = 100 + (100 * i);
}
}
// This is for the three headings on the top - "Grade", "From" and "To"
for (int i = 0; i < 3; i++) {
panel.add(labels.get(i), gbcs.get(i));
}
int l = 3, tf = 0; // l is the labels count, tf is for text fields
for (int i = 3; i < gbcs.size(); i++) {
if (i % 3 == 0) {
panel.add(labels.get(l), gbcs.get(i));
l++;
} else {
panel.add(textFields.get(tf), gbcs.get(i));
tf++;
}
}
panel.revalidate();
panel.repaint();
}
private void createLabels() {
// all the labels are made
labels = new ArrayList<JLabel>();
labels.add(new JLabel("Grade"));
labels.add(new JLabel("From"));
labels.add(new JLabel("To"));
labels.add(new JLabel("A"));
labels.add(new JLabel("B"));
// labels.add(new JLabel("B-"));
labels.add(new JLabel("C"));
labels.add(new JLabel("D"));
}
private void createTextFields() {
// there are two text fields on each row, starting from the 2nd
textFields = new ArrayList<JTextField>();
for (int i = 0; i < 8; i++) {
textFields.add(new JTextField(5));
}
}
private void createMenuBar() {
menubar = new JMenuBar();
// create and add the menu/menu items to the menubar
JMenu actions = new JMenu("Action");
JMenuItem addrow = new JMenuItem("Add Row");
actions.add(addrow);
class Listener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String newGrade = JOptionPane.showInputDialog(frame,
"What grade is this?");
if (newGrade.length() == 2) { // e.g.: ("B+")
String s = newGrade.substring(0, 1);
int index = 0; // index is the location of grade in the
// labels ArrayList
for (int i = 3; i < labels.size(); i++) {
if (s.equals(labels.get(i).getText())) {
index = i;
break;
}
}
String s2 = newGrade.substring(1);
if (s2.equals("-"))
index++;
labels.add(index, new JLabel(newGrade));
textFields.add(new JTextField(5));
textFields.add(new JTextField(5));
}
panel.removeAll(); // removes everything from the panel to be
// readied again
createLayout(); // creates the layout everything
}
}
addrow.addActionListener(new Listener());
menubar.add(actions);
}
}

Getting compiler error for unknown reason

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.

Binary to Decimal Applet with radio buttons

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.

Categories

Resources