Get values out from JTextField and convert to int - java

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.

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

What would be the best way of making this piece of code smaller?

I was wondering if we are adding the same components to java (in the main class)over and over again and writing separate code for each of them, would it be possible to make the code smaller? e.g. if we are adding buttons and labels many times, which each do different job, would it it possible to have them in less code or does it have to be like that e.g.
JLabel label = new JLabel("Text1");
label.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label);
JTextField field = new JTextField();
panel.add(field);
JLabel label1 = new JLabel("Text2");
label1.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label1);
JTextField field1 = new JTextField();
panel.add(field1);
field1.setEnabled(false);
JLabel label2 = new JLabel("Text3");
label2.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label2);
JTextField field2 = new JTextField();
panel.add(field2);
field2.setEnabled(false);
In my code I have to add the same components over and over again like 10 times but each one is doing a different job, would it be possible to have them in less code?
Also I want to be able to store the values of each textbox in a different variable, e.g. store the value of field1 to int number;.
Create a method that you can reuse:
private void method createLabel(JPanel panel, String text) {
JLabel label = new JLabel(text);
label.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label);
JTextField field = new JTextField();
panel.add(field);
}
If you need extra things like setEnabled() or whatever, just pass parameters in order to do it or not depending on requirements. If you need the Labels back just change void to JLabel and return it. Then you call it like this
createLabel(panel, "text1");
createLabel(panel, "text2");
...
1.Create ArrayList
2.Create method for adding JLabel to arraylist
3.Make it take a String name parameter
4.Profit???
"would it be possible to make the code smaller? "
Yes. One way, as #iberbue suggested is to use a method. You can have a method that return a JPanel and pass arguments to it
Have a look at this example I was working on for a different question. But it serves the same purpose. Look at the method createPanel that return a JPanel. Then I just use JPanel panel = createPanel(...);
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Test2 {
Map<String, JTextField> fields;
Map<String, JLabel> labels;
public Test2() {
fields = new HashMap<>();
labels = new HashMap<>();
JPanel mainPanel = new JPanel(new GridLayout(10, 1));
for (int i = 1; i <= 10; i++) {
JPanel panel = createPanel("Text Field " + i);
mainPanel.add(panel);
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new Test2();
}
});
}
private JPanel createPanel(String fieldName) {
JPanel panel = new JPanel();
JTextField field = new JTextField(15);
field.addActionListener(new FieldListener());
fields.put(fieldName, field);
JLabel label = new JLabel(fieldName);
label.addMouseListener(new MouseHandler());
labels.put(fieldName, label);
JButton button = new JButton(fieldName);
button.addActionListener(new ButtonListener());
panel.add(label);
panel.add(field);
panel.add(button);
return panel;
}
public class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
String fieldName = button.getText();
JTextField field = fields.get(fieldName);
System.out.println(field.getText());
}
}
public class FieldListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JTextField field = (JTextField)e.getSource();
System.out.println(field.getText());
}
}
public class MouseHandler extends MouseAdapter {
#Override
public void mouseClicked(MouseEvent e) {
JLabel label = (JLabel)e.getSource();
System.out.println(label.getText());
}
}
}
You can write a method, something like this.
private void add(JPanel panel, int i, boolean enabled){
JLabel label = new JLabel("Text" + i);
label.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label);
JTextField field = new JTextField();
panel.add(field);
field.setEnabled(enabled);
}
And then you call it 3 times as needed.
You've noticed that most code is repeated. This is a good first step.
Then, notice what parts change (semantically) between iterations (that is, ignore the different variable names and other unimportant info): new JLabel(theLabelThatChanges)and .setEnabled(thisFieldEnabled).
Then, put all these in a loop:
for(int i = 0; i < 10; i++)
{
JLabel label2 = new JLabel(theLabelThatChanges);
label2.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label2);
JTextField field2 = new JTextField();
panel.add(field2);
field1.setEnabled(thisFieldEnabled);
}
Make sure have a collection of values for the thing that changes:
String[] labels = new String[] { "Text1", "Text2", "Text3" };
boolean[] enabledBoxes = new boolean { true, false, true };
Be sure to grab a value in each iteration:
String theLabelThatChanges = labels[i];
boolean thisFieldEnabled = enabledBoxes[i];
Final code:
String[] labels = new String[] { "Text1", "Text2", "Text3" };
boolean[] enabledBoxes = new boolean { true, false, true };
for(int i = 0; i < 3; i++)
{
String theLabelThatChanges = labels[i];
boolean thisFieldEnabled = enabledBoxes[i];
JLabel label2 = new JLabel(theLabelThatChanges);
label2.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label2);
JTextField field2 = new JTextField();
panel.add(field2);
field1.setEnabled(thisFieldEnabled);
}
As others have commented, you could then take the part that creates all this stuff and make it a separate procedure that takes the label and the enabled status as parameters:
private void addControls(String theLabelThatChanges, boolean thisFieldEnabled)
{
JLabel label2 = new JLabel(theLabelThatChanges);
label2.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label2);
JTextField field2 = new JTextField();
panel.add(field2);
field1.setEnabled(thisFieldEnabled);
}
Then call it from the loop:
for(int i = 0; i < 3; i++)
{
addControls(labels[i], enabledBoxes[i]);
}
Complexer answer.
If you want to be OO.
Make class CustomJButton extends JButton
Set Everything you need in the contructor
You will be able to do this if you're not going to use the Button vars anymore
new CustomJButton("NAME");
You will be able to do this if you're going to use the Button vars
CustomJButton j = new CustomJButton("NAME");
I thought there already should be some fluent swing GUI API, but I did not find any on the spur. JavaFX GUI on Java 8 is nice.
Though Java 8 allows terse event listeners with Java 7 one can do a fluent API too.
JPanel panel = new FrameBuilder().panel()
.children()
.label("Text1")
.setHorizontalAlignment(SwingConstants.CENTER)
.textField()
.setId("field1")
.label("Text2")
.setHorizontalAlignment(SwingConstants.CENTER)
.textField()
.setId("field2")
.setEnabled(false)
.endChildren()
.create();
Where FrameBuilder.panel gives a PanelBuilder whose create returns the JPanel. Or so.

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.

Java IOStream Arrays JFrame

I have to create a CD inventory program for my first Java class. The book is poorly written and extremely verbose. I have created 4 frames to handle each requirement of the assignment. But the book doesn't explain how to write arrays to a .dat file. If I could get an idea of how to add data to an array from my TextFields then write to a .dat file I could stumble through the rest. Here is what I have so far. How do I take my JTextFields from my Add CD listener and write to a .dat file so I can view it later.
import java.util.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.lang.SecurityException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
class CDinventoryItem extends JFrame implements Comparable <CDinventoryItem> {
private String sPtitle;
private String genreCD;
private int iPitemNumber;
private int iPnumberofUnits;
private double dPunitPrice;
private double dEvalue;
private JFrame frame2= new JFrame();
private JFrame frame3= new JFrame();
private JFrame frame4= new JFrame();
private JPanel panel1 = new JPanel();
private JPanel panel2 = new JPanel();
private JPanel panel3 = new JPanel();
private JPanel panel4 = new JPanel();
private JPanel panel5 = new JPanel();
private JPanel panel6 = new JPanel();
private JLabel[] label = new JLabel[20];
private JTextField titleField;
private JTextField itemNField;
private JTextField numofunitsField;
private JTextField priceField;
private JButton next;
private JButton prev;
private JButton addCD = new JButton ("Add CD");
private JButton save = new JButton ("Save");
private JButton delete;
private JButton modify;
private JButton search = new JButton ("Search for CD");
private JButton mainmenu;
private JButton displayCD = new JButton ("Display Inventory");
private CDinventoryItem [] inven;
private DataOutputStream outFile;
private DataInputStream inputFile;
public CDinventoryItem (String title, int itemNumber, int numberofUnits,
double unitPrice, String genre){
sPtitle = title;
iPitemNumber = itemNumber;
iPnumberofUnits = numberofUnits;
dPunitPrice = unitPrice;
genreCD = genre;
for(int i = 0; i < label.length; i++) {
label[i] = new JLabel();
}
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel1.add(label[0]);
Icon bug = new ImageIcon( getClass().getResource( "mylogo.JPG" ) );
label[0].setIcon( bug );
label[0].setPreferredSize(new Dimension(400, 150));
panel1.add(label[1]);
label[1].setText("Press button to choose option:");
label[1].setPreferredSize(new Dimension(400, 50));
panel1.add(panel2);
panel2.setPreferredSize(new Dimension(400, 50));
ButtonListerner inputNewCD = new ButtonListerner();
panel2.add(addCD);
addCD.addActionListener(inputNewCD);
ButtonListerner searchCD = new ButtonListerner();
panel2.add(search);
search.addActionListener(searchCD);
ButtonListerner display = new ButtonListerner();
panel2.add(displayCD);
displayCD.addActionListener(display);
setContentPane(panel1);
}
private class ButtonListerner implements ActionListener
{
public void actionPerformed ( ActionEvent event) {
if (event.getActionCommand().equals("Add CD"))
{
frame2.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame2.setLocation(525,100);
frame2.setSize(425, 425);
frame2.setVisible( true );
frame2.add(panel3);
panel3.add(label[0]);
panel3.add(label[2]);
label[2].setText("Enter title of CD:");
label[2].setPreferredSize(new Dimension(100, 25));
JTextField titleText = new JTextField(20);
panel3.add (titleText);
sPtitle.equals(titleText);
label[2].setPreferredSize(new Dimension(175, 25));
panel3.add(label[3]);
label[3].setText("Enter number of CDs:");
JTextField numCDText = new JTextField(5);
panel3.add(numCDText);
label[3].setPreferredSize(new Dimension(275, 25));
panel3.add(label[4]);
label[4].setText("Enter price of CD:");
JTextField priceCDText = new JTextField(6);
panel3.add(priceCDText);
label[4].setPreferredSize(new Dimension(274, 25));
panel3.add(label[5]);
label[5].setText("Pick genre:");
String stringBox[] = {"Drama","Action","Comedy"};
JComboBox comboBox = new JComboBox(stringBox);
comboBox.setEditable(false);
panel3.add(comboBox);
panel3.add(save);
}
if (event.getActionCommand().equals("Search for CD")){
frame3.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame3.setLocation(100,525);
frame3.setSize(425, 425);
frame3.setVisible( true );
frame3.add(panel4);
panel4.add(label[0]);
panel4.add(label[6]);
label[6].setText("Enter name of CD you want to search for:");
JTextField searchName = new JTextField(20);
panel4.add(searchName);
panel4.add(label[7]);
label[7].setText("Or search by genre:");
JCheckBox checkB1 = new JCheckBox("Drama");
JCheckBox checkB2 = new JCheckBox("Action");
JCheckBox checkB3 = new JCheckBox("Comedy");
panel4.add(checkB1);
panel4.add(checkB2);
panel4.add(checkB3);
}
if (event.getActionCommand().equals("Display Inventory")){
frame4.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame4.setLocation(525,525);
frame4.setSize(425, 425);
frame4.setVisible( true );
frame4.add(panel5);
panel5.add(label[0]);
panel5.add(label[8]);
label[8].setText("List of CDs:");
}
if (event.getActionCommand().equals("Save")){
String dataFile = "inventory.dat";
try{
outFile = new DataOutputStream(new BufferedOutputStream(
new FileOutputStream(dataFile)));
}
catch(FileNotFoundException fileNotFoundException ){
}
}
}}
public int compareTo(CDinventoryItem otherItem) {
return this.sPtitle.compareTo(otherItem.getTitle());
}
#Override
public String getTitle() {
return sPtitle;
}
}
public class CDinventoryprogram {
public static void main(String[] args) {
JOptionPane.showMessageDialog( null, "Welcome to my CD inventory program!!"
, "Inventory", JOptionPane.INFORMATION_MESSAGE);
CDinventoryItem initem = new CDinventoryItem ("", 0, 0, 0.0,"" );
initem.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
initem.setLocation(100,100);
initem.setSize(425, 425);
initem.setVisible( true );
}
Sorry to be a nit-picker, but this:
class CDinventoryItem extends JFrame implements Comparable <CDinventoryItem>
has a "God" class anti-pattern design smell to it. You are asking it to be a CDinventoryItem, to hold a collection of CDinventoryItems, to display this collection of items in a GUI and to be the root container of that GUI, and now to output that information to disk. In other words you are asking this poor class to do too much.
Before even thinking about creating a GUI to display this information or writing code to output anything to a file, you need to seriously refactor it.
I recommend in the least you consider doing this:
1) Create a class CDInventoryItem that's Comparable, and has fields to hold this information -- String title, int itemNumber, int numberofUnits, double unitPrice, String genre -- and that's it.
2) Create another class for manipulating a collection of the above with an add method, a remove method, a listAll() method, a sort method, a search method, an int to refer to the current CDInventoryItem in the collection and a getter method to obtain it the current item, a method to get the next() and the previous() items, and to advance or decrement this int index,...
3) A class for IO support for reading and writing CDInventoryItems to and from a file, perhaps using Serialization (then CDInventoryItem should be serializable).
4) And then and only then should you start the GUI portion of your program. The GUI should use the classes above as its underlying logic.
If you do this, your coding will go along much more smoothly. If not, you may have a ton of horrendous debugging ahead of you.
In the method ButtonListerner.actionPerformed(), when the Add CD button is pressed (checked by event.getActionCommand().equals("Add CD")), you are creating a local text field:
JTextField titleText = new JTextField(20);
panel3.add (titleText);
sPtitle.equals(titleText);
label[2].setPreferredSize(new Dimension(175, 25));
panel3.add(label[3]);
label[3].setText("Enter number of CDs:");
JTextField numCDText = new JTextField(5);
panel3.add(numCDText);
label[3].setPreferredSize(new Dimension(275, 25));
...
The first thing you need to do is use the one in the outer class (so you can get the values later):
titleField = new JTextField(20);
panel3.add (titleField);
sPtitle.equals(titleField);
label[2].setPreferredSize(new Dimension(175, 25));
panel3.add(label[3]);
label[3].setText("Enter number of CDs:");
itemNField = new JTextField(5);
panel3.add(itemNField);
label[3].setPreferredSize(new Dimension(275, 25));
...
After this, when Save button is clicked, now your fields will hold the user input, so you can now get those values:
String title = titleField.getText();
...
Now to write to a file, you need to use an OutputStream. There are many OutputStream subclasses, each one has it's own use. BufferedWriter is for writing text, DataOutputStream is for writing binary data, you should not use both together like you are doing now. Assuming you want to write binary data, you can do this:
try {
outFile = new DataOutputStream(new FileOutputStream(dataFile));
outFile.writeUTF(titleField.getText());
// convert string to int
int itemN = Integer.parseInt(itemNField.getText());
outFile.writeInt(itemN);
outFile.flush();
outFile.close();
}
catch(IOException error) {
error.printStackTrace();
}
Note: To keep things simple, I didn't added proper error handling (the outFile.close() should be in a finally statement).

Categories

Resources