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.
Related
My code is messy so you might not be able to follow it, but I am trying to make a YouTube to MP3 converter.
It opens up a JPanel for the user to type in the YouTube URL. When I try to get the text from the JTextField, I had to make my method return a value so i can use the value in my other class, and I think that is causing my code not to work.
If someone could help me out, that would be great. I am really new to Java coding and I'm not sure why I chose such a complicated program, but I almost have it done. This is the last part then the cosmetics and cleaning up the code starts :)
My code:
public class Bank_Statement extends JFrame {
// width & height of window
private static final int WIDTH = 500;
private static final int HEIGHT = 500;
public static final Keys text = null;
final ActionListener convertButtonHandler = null;
static Scanner console = new Scanner(System.in);
static String M1;
public static String Bank_Statement1() {
//create/set labels
JButton skinny = new JButton("Convert");
skinny.addActionListener(new ButtonListener());
JPanel buttonPane = new JPanel();
buttonPane.add(skinny);
JButton skinny2 = new JButton("Paste");
JPanel buttonPane2 = new JPanel();
buttonPane2.add(skinny2);
JTextField text;
text = new JTextField(" ");
JPanel textPane = new JPanel();
textPane.add(text);
JTextField text2 = new JTextField("----------------------------------------WAIT LIST----------------------------------------");
JPanel textPane2 = new JPanel();
textPane2.add(text2);
JFrame frame = new JFrame("Youtube Converter");
frame.setSize(WIDTH, HEIGHT);
frame.add(textPane, BorderLayout.WEST);
frame.add(buttonPane2, BorderLayout.CENTER);
frame.add(buttonPane, BorderLayout.EAST);
frame.add(textPane2, BorderLayout.PAGE_END);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
return text.getText();
}
public static void main(String[] args) {
Bank_Statement recObject = new Bank_Statement();
}
}
class ButtonListener implements ActionListener {
ButtonListener() {}
public void actionPerformed(ActionEvent e) {
WebDriver driver = new HtmlUnitDriver();
driver.get("http://www.youtubeinmp3.com/");
String J = Bank_Statement.Bank_Statement1();
driver.findElement(By.id("video")).sendKeys(J + Keys.ENTER);
driver.findElement(By.id("download")).click();
String L= driver.getCurrentUrl();
System.out.println(L);
try {
Runtime.getRuntime().exec(new String[] {"cmd", "/c","start chrome " + L});
} catch (IOException e1) {
e1.printStackTrace();
}
driver.quit();
}
}
return text.getText();
Will be executed right after the Windows appears. It does not wait until the user enters some text.
Try the following:
public class Bank_Statement extends JFrame {
private JTextField text;
public static Bank_Statement bank_statement;
public Bank_Statement() {
//create/set labels
JButton skinny = new JButton("Convert");
skinny.addActionListener(new ButtonListener());
text = new JTextField(" ");
JPanel textPane = new JPanel();
textPane.add(text);
...
frame.setVisible(true);
}
public String getText(){
return text.getText();
}
public static void main(String[] args) {
bank_statement = new Bank_Statement();
}
}
class ButtonListener implements ActionListener {
ButtonListener() {}
public void actionPerformed(ActionEvent e) {
String J = Bank_Statement.bank_statement.getText();
System.out.println(J);
}
}
I removed a few lines in the middle to keep it compact. I hope it is clear, ask otherwise. The design is quite bad, but I didn't want to change to mutch of your code.
Well, first of all, I assume this is your constructor for the Bank_Statement class
public static String Bank_Statement1() {
//create/set labels
JButton skinny = new JButton("Convert");
skinny.addActionListener(new ButtonListener());
JPanel buttonPane = new JPanel();
buttonPane.add(skinny);
JButton skinny2 = new JButton("Paste");
JPanel buttonPane2 = new JPanel();
buttonPane2.add(skinny2);
JTextField text;
text = new JTextField(" ");
JPanel textPane = new JPanel();
textPane.add(text);
JTextField text2 = new JTextField("----------------------------------------WAIT LIST----------------------------------------");
JPanel textPane2 = new JPanel();
textPane2.add(text2);
JFrame frame = new JFrame("Youtube Converter");
frame.setSize(WIDTH, HEIGHT);
frame.add(textPane, BorderLayout.WEST);
frame.add(buttonPane2, BorderLayout.CENTER);
frame.add(buttonPane, BorderLayout.EAST);
frame.add(textPane2, BorderLayout.PAGE_END);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
return text.getText();
}
This is an incorrect use of a constructor.
In this case, your constructor should be declared as:
public static Bank_Statement(){
//constructor code goes here
}
then you can declare a getter method for your JTextField value like so:
public String getText(){
return text.getText();
}
then you should be able to call that method (getText) in any method once the object is instantiated. Like this:
public static void main(String[] args){
//just an example...you wouldn't really want to do this
Bank_Statement recObject = new Bank_Statement();
recObject.getText();
}
But overall this solution is not a "good" fix because there are many other ways to do it that are considered better. This will simply fix your error you are having. I would look into understanding classes and objects better before you continue. :)
what I am trying to do is compare two inputs from TextFields within a JFrame using an ActionListener. If the two inputs are equal and the user hits the button, a MessageDialog will pop up and say "equal". If they are not equal, a MessageDialog will pop up and say "not equal". I have the frame and ActionListener running, I just do not know how to take the inputs from the TextFields and compare them.
For example, if the user enters something like this,
Equal TextFields, this will pop up, Equal Message
Here is my Main Class:
public class LabFiveOne
{
public static void main(String[] args)
{
JFrame frame = new JFrame("String Equality Program");
JTextField tf1 = new JTextField(10);
tf1.setActionCommand(tf1.toString());
tfListener tfListen = new tfListener(tf1);
JTextField tf2 = new JTextField(10);
tf2.setActionCommand(tf2.toString());
JButton chEq = new JButton("Check Equality");
chEq.addActionListener(tfListen);
JPanel nPanel = new JPanel();
nPanel.add(tf1);
nPanel.add(tf2);
frame.add(nPanel, BorderLayout.NORTH);
JPanel sPanel = new JPanel();
sPanel.add(chEq);
frame.add(sPanel, BorderLayout.SOUTH);
nPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
And here is my ActionListener Class:
class tfListener implements ActionListener
{
private final JTextField tf3;
public tfListener(JTextField nameTF)
{
tf3 = nameTF;
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("abc"))
{
JOptionPane.showMessageDialog(null, "equal");
}
else
{
JOptionPane.showMessageDialog(null, "not equal");
}
}
}
EDIT: ok than try to change the constructor in your ActionListener Class to
public tfListener(JTextField tf1, JTextField tf2){
{
Hi :) just don't overthink and you should be fine. The simple way would be to implement the ActionListener directly to your Main Class like this:
public class LabFiveOne
{
public static void main(String[] args)
{
JFrame frame = new JFrame("String Equality Program");
final JTextField tf1 = new JTextField(10);
tf1.setActionCommand(tf1.toString());
tfListener tfListen = new tfListener(tf1);
final JTextField tf2 = new JTextField(10);
tf2.setActionCommand(tf2.toString());
JButton chEq = new JButton("Check Equality");
chEq.addActionListener(tfListen);
JPanel nPanel = new JPanel();
nPanel.add(tf1);
nPanel.add(tf2);
frame.add(nPanel, BorderLayout.NORTH);
JPanel sPanel = new JPanel();
sPanel.add(chEq);
frame.add(sPanel, BorderLayout.SOUTH);
nPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
{
class tfListener implements ActionListener
{
private final String tf1text;
private final String tf2text;
public tfListener(JTextField tf1, JTextField tf2)
{
tf1text = new String(tf1.getText());
tf1text = new String(tf2.getText());
}
#Override
public void actionPerformed(ActionEvent e)
{
if(tf1text.equal(tf2text))
{
JOptionPane.showMessageDialog(null, "equal");
}
else
{
JOptionPane.showMessageDialog(null, "not equal");
}
}
}
}
tf1.toString();
Shows you some information from the JTextField.
use another methods to get your input from the field. I mean it's the method:
tfi.getText();
Better look in a JTextField javadoc
To be honest with you, I don't think you need two classes; one for implementing the GUI and one for handling the ActionListener when you can have everything in one class like the class below
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
public class LabFiveOne implements ActionListener
{
private JFrame frame;
private JPanel nPanel, sPanel;
private JTextField tf1, tf2;
private JButton chEq;
public static void main(String[] args)
{
new LabFiveOne();
}
public LabFiveOne(){
frame = new JFrame("String Equality Program");
tf1 = new JTextField(10);
tf2 = new JTextField(10);
chEq = new JButton("Check Equality");
chEq.addActionListener(this);
nPanel = new JPanel();
nPanel.add(tf1);
nPanel.add(tf2);
frame.add(nPanel, BorderLayout.NORTH);
sPanel = new JPanel();
sPanel.add(chEq);
frame.add(sPanel, BorderLayout.SOUTH);
nPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String action = e.getActionCommand();
if(action.equals("Check Equality")){
String number1 = tf1.getText();
String number2 = tf2.getText();
int num1 = Integer.valueOf(number1);
int num2 = Integer.valueOf(number2);
if(num1 == num2){
JOptionPane.showMessageDialog(null, "Equal");
}
else{
JOptionPane.showMessageDialog(null, "Not Equal");
}
}
}
}
I have everything declared globally so that the ActionPerformed method will have access the values in the Textfields.
I have very simple code, just 2 buttons to display numbers from array in textArea.
public class FotyUI extends javax.swing.JFrame {
public FotyUI() {
initComponents();
}
int[] numbers = {0,1,2,3,4,5,6,7,8,9};
int position = 0;
private void nextActionPerformed(java.awt.event.ActionEvent evt) {
position ++;
tekst.setText(" " + numbers[position]);
}
private void previousActionPerformed(java.awt.event.ActionEvent evt) {
position--;
tekst.setText(" " + numbers[position]);
}
Now, this code runs great I have two buttons and textArea, but I would like to create an external JFrame2 with 2 buttons to control/display array from Frame 1
When I type:
public class FotyUI extends javax.swing.JFrame {
public FotyUI() {
initComponents();
}
int[] numbers = {0,1,2,3,4,5,6,7,8,9};
int position = 0;
JFrame temp = new JFrame();
JPanel panelik = new JPanel();
JButton nextS = new JButton("Next");
JButton prevS = new JButton("Previous");
panelik.add(nextS);
I have an error to create package panelik....
Can u help me ? How to create Frame 2 with 2 buttons and textArea to display/control content of array from Frame1
ok, I solve it !!!!!!!!
JFrame frame = new JFrame("Test");
frame.setVisible(true);
frame.setSize(500,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("hello agin1");
panel.add(button);
pole = new JTextField();
panel.add(pole);
button.addActionListener (new Action1());
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
position ++;
tekst.setText(" " + numbers[position]);
pole.setText(" " + numbers[position]);
}
}
public class ATMgui extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final int WIDTH = 500;
public static final int HEIGHT = 200;
private ATMbizlogic theBLU;// short for the Business Logic Unit
public JLabel totalBalanceLabel;
public JTextField withdrawTextField;
public JTextField depositTextField;
public JTextField pinTextField;
/**
* Creates a new instance of ATMgui
*/
public ATMgui() {
setTitle("ATM Transactions");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setBackground(Color.BLACK);
contentPane.setLayout(new BorderLayout());
// Do the panel for the rest stop
JLabel start = new JLabel("Welcome To Your Account", JLabel.CENTER);
Font curFont = start.getFont();
start.setFont(new Font(curFont.getFontName(), curFont.getStyle(), 25));
start.setForeground(Color.BLUE);
start.setOpaque(true);
start.setBackground(Color.BLACK);
pinTextField = new JTextField();
JLabel pinLabel = new JLabel("Enter your PIN below:", JLabel.CENTER);
pinLabel.setForeground(Color.RED);
pinLabel.setOpaque(true);
pinLabel.setBackground(Color.WHITE);
JButton pinButton = new JButton("Enter Pin OK");
pinButton.addActionListener(this);
pinButton.setBackground(Color.red);
JPanel pinPanel = new JPanel();
pinPanel.setLayout(new GridLayout(3, 1, 100, 0));
pinPanel.add(pinLabel);
pinPanel.add(pinTextField);
pinPanel.add(pinButton);
contentPane.add(pinPanel, BorderLayout.WEST);
JPanel headingPanel = new JPanel();
headingPanel.setLayout(new GridLayout());
headingPanel.add(start);
contentPane.add(headingPanel, BorderLayout.NORTH);
// Do the panel for the amount & type of transactions
withdrawTextField = new JTextField();
JLabel withdrawLabel = new JLabel("Withdraw (0.00)", JLabel.CENTER);
withdrawLabel.setForeground(Color.RED);
withdrawLabel.setOpaque(true);
withdrawLabel.setBackground(Color.WHITE);
depositTextField = new JTextField();
JLabel depositLabel = new JLabel("Deposit (0.00)", JLabel.CENTER);
depositLabel.setForeground(Color.RED);
depositLabel.setOpaque(true);
depositLabel.setBackground(Color.WHITE);
JButton txButton = new JButton("Transactions OK");
txButton.addActionListener(this);
txButton.setBackground(Color.red);
JPanel txPanel = new JPanel();
txPanel.setLayout(new GridLayout(5, 1, 30, 0));
txPanel.add(withdrawLabel);
txPanel.add(withdrawTextField);
txPanel.add(depositLabel);
txPanel.add(depositTextField);
txPanel.add(txButton);
contentPane.add(txPanel, BorderLayout.EAST);
txPanel.setVisible(true);
totalBalanceLabel = new JLabel("Your balance after transactions: ", JLabel.CENTER);
totalBalanceLabel.setForeground(Color.BLUE);
totalBalanceLabel.setOpaque(true);
totalBalanceLabel.setBackground(Color.BLACK);
contentPane.add(totalBalanceLabel, BorderLayout.SOUTH);
theBLU = new ATMbizlogic();
}
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
// Container contentPane = getContentPane();
if (actionCommand.equals("Transactions OK")) {
try {
double deposit = Double.parseDouble(depositTextField.getText().trim());
double withdraw = Double.parseDouble(withdrawTextField.getText().trim());
theBLU.computeBalance(withdraw, deposit);
totalBalanceLabel.setText("Your balance after transactions: " + theBLU.getBalance());
} catch (ATMexception ex) {
totalBalanceLabel.setText("Error: " + ex.getMessage());
} catch (Exception ex) {
totalBalanceLabel.setText("Error in deposit or withdraw amount: " + ex.getMessage());
}
} else if (actionCommand.equals("Enter Pin OK")) {
try {
double pin = Double.parseDouble(pinTextField.getText().trim());
theBLU.checkPin(pin);
totalBalanceLabel.setText("Your balance after transactions: " + theBLU.getBalance());
} catch (ATMexception ex) {
totalBalanceLabel.setText("Error: " + ex.getMessage());
} catch (Exception ex) {
totalBalanceLabel.setText("Error in pin: " + ex.getMessage());
}
} else {
System.out.println("Error in button interface.");
}
}
public static void main(String[] args) {
ATMgui gui = new ATMgui();
gui.setVisible(true);
}
}
I don't think this is the right way to implement ActionListeners for buttons.
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
// Container contentPane = getContentPane();
if (actionCommand.equals("Transactions OK"))
else ...
}
With the if-else stamements in the method actionPerformed, your program is forced to check what listener to invoke, every time whatever button is pressed, and, in this way, your code isn't easy to edit and reuse.
Also, the GUI Container is acting like a receiver of events, then you should avoid
pinButton.addActionListener(this);
Try to implement your own inner classes for each button, like this:
JButton pinButton = new JButton("Enter Pin OK");
pinButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae){
//enter here your action
txPanel.setVisible(true);
}
});
In this way, you don't need to implement the ActionListener interface for your class, because you're implementing a inner istance of the interface for your pinButton. Check this old question of SO.
Also, you should avoid to implement all your GUI elements in your class constructor, it's better to implement the GUI in a separate method, like createAndShowGui(), and call it in the constructor, to respect the Java Swing conventions and to run the Swing components in a different thread, called Event Dispatch Thread, different from the main thread of your application. Read this question.
Then include txPanel.setVisible(false); in createAndShowGui() method.
Remember that the Swing components are not thread-safe.
Since the code pasted by you is not working, I had made a small program for you, have a look, and see what changes can you do to incorporate that in your case :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PanelTest extends JFrame
{
private JPanel eastPanel;
public PanelTest()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
Container container = getContentPane();
eastPanel = new JPanel();
eastPanel.setBackground(Color.DARK_GRAY);
JPanel westPanel = new JPanel();
westPanel.setBackground(Color.YELLOW);
JPanel centerPanel = new JPanel();
centerPanel.setBackground(Color.BLUE);
container.add(eastPanel, BorderLayout.LINE_START);
container.add(centerPanel, BorderLayout.CENTER);
container.add(westPanel, BorderLayout.LINE_END);
eastPanel.setVisible(false);
JButton showButton = new JButton("Click Me to Display EAST JPanel");
showButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
eastPanel.setVisible(true);
}
});
JButton hideButton = new JButton("Click Me to Hide EAST JPanel");
hideButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
eastPanel.setVisible(false);
}
});
container.add(hideButton, BorderLayout.PAGE_START);
container.add(showButton, BorderLayout.PAGE_END);
setSize(300, 300);
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PanelTest();
}
});
}
}
And from future, never use NORTH, EAST, WEST and SOUTH for BorderLayout. They have been replaced with PAGE_START, LINE_START, LINE_END and PAGE_END respectively.
A BorderLayout object has five areas. These areas are specified by the BorderLayout constants:
PAGE_START
PAGE_END
LINE_START
LINE_END
CENTER
Version note:
Before JDK release 1.4, the preferred names for the various areas were different, ranging from points of the compass (for example, BorderLayout.NORTH for the top area) to wordier versions of the constants we use in our examples. The constants our examples use are preferred because they are standard and enable programs to adjust to languages that have different orientations.
I had modified the checkPin(...) method of the ATMLogin class to return a boolean instead of void, so that inside the actionPerformed(...) method of the ATMgui class, if this thing returns true, then only to set the required JPanel to visible, else nothing is to be done.
Do check the code and see what changes you can do to make it work for your end.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ATMgui extends JFrame implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
public static final int WIDTH = 500;
public static final int HEIGHT = 200;
private ATMbizlogic theBLU;// short for the Business Logic Unit
private JPanel txPanel;
public JLabel totalBalanceLabel;
public JTextField withdrawTextField;
public JTextField depositTextField;
public JTextField pinTextField;
/**
* Creates a new instance of ATMgui
*/
public ATMgui()
{
setTitle("ATM Transactions");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setBackground(Color.BLACK);
contentPane.setLayout(new BorderLayout());
// Do the panel for the rest stop
JLabel start = new JLabel("Welcome To Your Account", JLabel.CENTER);
Font curFont = start.getFont();
start.setFont(new Font(curFont.getFontName(), curFont.getStyle(), 25));
start.setForeground(Color.BLUE);
start.setOpaque(true);
start.setBackground(Color.BLACK);
pinTextField = new JTextField();
JLabel pinLabel = new JLabel("Enter your PIN below:", JLabel.CENTER);
pinLabel.setForeground(Color.RED);
pinLabel.setOpaque(true);
pinLabel.setBackground(Color.WHITE);
JButton pinButton = new JButton("Enter Pin OK");
pinButton.addActionListener(this);
pinButton.setBackground(Color.red);
JPanel pinPanel = new JPanel();
pinPanel.setLayout(new GridLayout(3, 1, 100, 0));
pinPanel.add(pinLabel);
pinPanel.add(pinTextField);
pinPanel.add(pinButton);
contentPane.add(pinPanel, BorderLayout.WEST);
JPanel headingPanel = new JPanel();
headingPanel.setLayout(new GridLayout());
headingPanel.add(start);
contentPane.add(headingPanel, BorderLayout.NORTH);
// Do the panel for the amount & type of transactions
withdrawTextField = new JTextField();
JLabel withdrawLabel = new JLabel("Withdraw (0.00)", JLabel.CENTER);
withdrawLabel.setForeground(Color.RED);
withdrawLabel.setOpaque(true);
withdrawLabel.setBackground(Color.WHITE);
depositTextField = new JTextField();
JLabel depositLabel = new JLabel("Deposit (0.00)", JLabel.CENTER);
depositLabel.setForeground(Color.RED);
depositLabel.setOpaque(true);
depositLabel.setBackground(Color.WHITE);
JButton txButton = new JButton("Transactions OK");
txButton.addActionListener(this);
txButton.setBackground(Color.red);
txPanel = new JPanel();
txPanel.setLayout(new GridLayout(5, 1, 30, 0));
txPanel.add(withdrawLabel);
txPanel.add(withdrawTextField);
txPanel.add(depositLabel);
txPanel.add(depositTextField);
txPanel.add(txButton);
contentPane.add(txPanel, BorderLayout.EAST);
txPanel.setVisible(false);
totalBalanceLabel = new JLabel("Your balance after transactions: ", JLabel.CENTER);
totalBalanceLabel.setForeground(Color.BLUE);
totalBalanceLabel.setOpaque(true);
totalBalanceLabel.setBackground(Color.BLACK);
contentPane.add(totalBalanceLabel, BorderLayout.SOUTH);
theBLU = new ATMbizlogic();
}
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
// Container contentPane = getContentPane();
if (actionCommand.equals("Transactions OK"))
{
try
{
double deposit = Double.parseDouble(depositTextField.getText().trim());
double withdraw = Double.parseDouble(withdrawTextField.getText().trim());
theBLU.computeBalance(withdraw, deposit);
totalBalanceLabel.setText("Your balance after transactions: " + theBLU.getBalance());
}
/*catch (ATMexception ex)
{
totalBalanceLabel.setText("Error: " + ex.getMessage());
}*/
catch (Exception ex)
{
totalBalanceLabel.setText("Error in deposit or withdraw amount: " + ex.getMessage());
}
}
else if (actionCommand.equals("Enter Pin OK"))
{
try
{
double pin = Double.parseDouble(pinTextField.getText().trim());
if(theBLU.checkPin(pin))
txPanel.setVisible(true);
totalBalanceLabel.setText("Your balance after transactions: " + theBLU.getBalance());
}
/*catch (ATMexception ex)
{
totalBalanceLabel.setText("Error: " + ex.getMessage());
}*/
catch (Exception ex)
{
totalBalanceLabel.setText("Error in pin: " + ex.getMessage());
ex.printStackTrace();
}
}
else
{
System.out.println("Error in button interface.");
}
}
public static void main(String[] args)
{
ATMgui gui = new ATMgui();
gui.setVisible(true);
}
}
class ATMbizlogic
{
private double totalBalance;
private boolean rightPinEntered;
/**
* Creates a new instance of ATMbizlogic
*/
public ATMbizlogic()
{
totalBalance = 0.0;
rightPinEntered = true;
}
public void computeBalance(double withdraw, double deposit)
//throws ATMexception
{
if(withdraw <=0)
{
System.out.println("Negative withdraw not allowed");
//throw new ATMexception("Negative withdraw not allowed");
}
if(deposit <=0)
{
System.out.println("Negative deposit not allowed");
//throw new ATMexception("Negative deposit not allowed");
}
double balance = deposit - withdraw;
totalBalance = totalBalance + balance;
}
public boolean checkPin(double pin)
//throws ATMexception
{
if(pin <=0)
{
System.out.println("Negative pin not allowed");
rightPinEntered = false;
//throw new ATMexception("Negative pin not allowed");
}
/*else if(rightPinEntered == false)
{
System.out.println("Can not take another pin");
rightPinEntered = false;
//throw new ATMexception("Can not take another pin");
}*/
else if(pin<1111 || pin>9999)
{
System.out.println("Enter a valid pin");
rightPinEntered = false;
//throw new ATMexception("Enter a valid pin");
}
else
{
rightPinEntered = true;
}
return rightPinEntered;
}
public double getBalance()
{
return totalBalance;
}
}
In the call to constructor ATMgui(), put
txPanel.setVisible(false);
and in the actionCommand.equals("Enter Pin OK") part, you can set it to true.
Is that what you want?
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.