Label with radio button issue - java

I am having some issues with my code, I cant see whats wrong with the logic, but here it is. I want them to have the radio button to choose either or, and when one is selected(radio button) the text area isn't available and vise versa. Here is the segment of the code. When I go back and forth on the radio buttons, both become not selectable, and I am unsure why.
private void PriceTab()
{
pricePanel = new JPanel(new FlowLayout());
final JRadioButton poolPrice= new JRadioButton("Pool");
final JRadioButton tubPrice = new JRadioButton("Hot Tub");
poolPrice.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(poolPrice);
group.add(tubPrice);
pricePanel.add(poolPrice);
pricePanel.add(tubPrice);
final JLabel poolLabel = new JLabel("Enter the pool's volume: ");
final JTextField poolField = new JTextField(10);
pricePanel.add(poolLabel);
pricePanel.add(poolField);
final JTextField tubField = new JTextField(10);
final JLabel tubLabel = new JLabel ("Enter the tub's volume: ");
pricePanel.add(tubLabel);
pricePanel.add(tubField);
JButton calculatePrice = new JButton("Calculate Price");
calculatePrice.setMnemonic('C');
pricePanel.add(calculatePrice);
pricePanel.add(createExitButton());
pricePanel.add(new JLabel("The price is: "));
final JTextField priceField = new JTextField(10);
priceField.setEditable(false);
pricePanel.add(priceField);
final JTextArea messageArea = createMessageArea(1, 25,
"*Please only select one section");
pricePanel.add(messageArea);
calculatePrice.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double pool = Double.parseDouble (poolField.getText());
double tub = Double.parseDouble(tubField.getText());
double price;
if (poolPrice.isSelected()) {
price = pool * 100;
} else {
price = tub * 75;
}
priceField.setText(df.format(price));
}
});
ActionListener priceListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == poolPrice) {
tubLabel.setEnabled(false);
tubField.setEnabled(false);
messageArea.setVisible(false);
} else if (e.getSource() == tubPrice) {
poolLabel.setEnabled(false);
poolField.setEnabled(false);
messageArea.setVisible(false);
}
}
};
poolPrice.addActionListener(priceListener);
tubPrice.addActionListener(priceListener);
}

ActionListener priceListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == poolPrice) {
tubLabel.setEnabled(false);
tubField.setEnabled(false);
// Re-enable the previously disabled labels
poolLabel.setEnabled(true);
poolField.setEnabled(true);
messageArea.setVisible(false);
} else if (e.getSource() == tubPrice) {
poolLabel.setEnabled(false);
poolField.setEnabled(false);
// Re-enable disabled labels
tubLabel.setEnabled(true);
tubField.setEnabled(true);
messageArea.setVisible(false);
}
}
};
You need to re-enable the buttons you disabled.

Related

JAVA GUI won't calculate the price

I'm trying to make this application to calculate but it won't. Spend ages on it. I just want to calculate ones I press the button. I need it to display the correct price when clicking on the correct combo box. The prices have been set I think.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.DecimalFormat;
public class retailsalescalcu extends JFrame {
//create the objects
JLabel department;
JLabel number;
JLabel name;
JLabel price;
JLabel discount;
JLabel sale;
JComboBox<String> dept;
JTextField itemNum;
JTextField itemName;
JTextField itemPrice;
JTextField itemDisc;
JTextField salePrice;
JButton calculate;
JButton clear;
public retailsalescalcu() {
//set object variables
super("Retail Sales Calculator"); //set window bar title
setSize(300, 300); //set window size
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set window close
GridLayout grid = new GridLayout(7, 2);
setLayout(grid);
department = new JLabel("Department");
dept = new JComboBox<String>();
dept.addItem("Select");
dept.addItem("Men's Clothing");
dept.addItem("Women's Clothing");
dept.addItem("Shoes");
dept.addItem("Belts");
dept.addItem("Electronics");
dept.addItem("Hats");
//add ItemListener - JTextField & ComboBox
dept.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
String str = (String)dept.getSelectedItem();
itemNum.setText(str);
} //end public void
}); //end item listener
number = new JLabel("Item Number");
itemNum = new JTextField(10);
name = new JLabel("Item Name");
itemName = new JTextField(10);
price = new JLabel("Original Price");
itemPrice = new JTextField(10);
discount = new JLabel("Discount");
itemDisc = new JTextField(10);
sale = new JLabel("Sale Price");
salePrice = new JTextField(10);
salePrice.setEditable(false);
calculate = new JButton("Calculate");
clear = new JButton("Clear");
//add objects to JFrame
add(department);
add(dept);
add(number);
add(itemNum);
add(name);
add(itemName);
add(price);
add(itemPrice);
add(discount);
add(itemDisc);
add(sale);
add(salePrice);
add(calculate);
add(clear);
//add event listener to calculate sale price
calculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent retail) {
String input1;
String input2;
double origPrice;
double percOff;
double clearance;
input1 = itemPrice.getText();
input2 = itemDisc.getText();
origPrice = Double.parseDouble(input1);
percOff = Double.parseDouble(input2)/100;
clearance = origPrice - (origPrice * percOff);
DecimalFormat df = new DecimalFormat("$#,###.##");
df.format(clearance);
salePrice.setText(df.format(clearance));
salePrice.setText(df.toString()); //output to JTextField
}
});
//add event listener to reset fields
clear.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent event) { //JButton event if clicked
dept.setSelectedIndex(0); //Combo Box will be empty and can be reset
itemNum.setText(null); //Item Number will be empty and can be reset
itemName.setText(null); //Item Name will be empty and can be reset
itemPrice.setText(null); //Item Price will be empty and can be reset
itemDisc.setText(null); //Item Discount will be empty and can be reset
salePrice.setText(null); //Item SalePrice will be empty and can be reset
}
});
setVisible(true);
} //end public retailsalescalcu
public static void main(String[] args) {
new retailsalescalcu();
} //end public static void
} //end public class retailsalescalcu
After debugging you code i found that you should remove/comment line #100 from your code
From
DecimalFormat df = new DecimalFormat("$#,###.##");
df.format(clearance);
salePrice.setText(df.format(clearance));
salePrice.setText(df.toString()); //output to JTextField
System.err.println(df.toString());
}
});
to
DecimalFormat df = new DecimalFormat("$#,###.##");
df.format(clearance);
salePrice.setText(df.format(clearance));
//salePrice.setText(df.toString()); //output to JTextField
System.err.println(df.toString());
}
});
EDIT:
One problem is here:
//salePrice.setText(df.toString());
Comment that out and you will see your price after clicking Calculate. You are already setting salesPrice here:
salePrice.setText(df.format(clearance));
The toString() is not going to give you what you want.

Java button doesn't work

I'm trying to debug my program for homework, but I can't even do that because I don't know why my buttons aren't working.
Any help is appreciated, thanks! (I know that my findnext is screwy for now, but I didn't know what else to do so I'm just debugging it for now)
public class Window extends JFrame implements ActionListener {
private JButton findnext;
private JButton replace;
private JButton delete;
private JButton upper;
private JTextField from,to;
private JTextArea textArea;
final static Color found = Color.PINK;
final Highlighter hilit;
final Highlighter.HighlightPainter painter;
public Window() {
setTitle("Project 8");
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
setSize((d.width/4)*3,d.height);
textArea = new JTextArea ("The apple ate the apple.",8,40);
textArea.setLineWrap(true);
Container contentPane = getContentPane();
addWindowListener(new Close());
contentPane.add(textArea);
JPanel panel = new JPanel();
JButton findnext = new JButton("FindNext");
panel.add(findnext);
from = new JTextField(8);
panel.add(from);
findnext.addActionListener(this);
JButton replace = new JButton("Replace");
panel.add(replace);
to = new JTextField(8);
panel.add(to);
findnext.addActionListener(this);
JButton delete = new JButton("Delete");
panel.add(delete);
findnext.addActionListener(this);
JButton upper = new JButton("Upper");
panel.add(upper);
findnext.addActionListener(this);
contentPane.add(panel, "South");
hilit = new DefaultHighlighter();
painter = new DefaultHighlighter.DefaultHighlightPainter(found);
textArea.setHighlighter(hilit);
}
public void actionPerformed(ActionEvent evt) {
String f = from.getText();
String t = to.getText();
int n = textArea.getText().indexOf(f);
Object source = evt.getSource();
if (source == findnext) {
hilit.removeAllHighlights();
String text = textArea.getText();
int index = text.indexOf(f,0);
if (index>0) {
try {
hilit.addHighlight(index, index+f.length(), DefaultHighlighter.DefaultPainter);
}
catch (BadLocationException e) {
;
}
}else if (source == replace) {
if (n>=0 && f.length() > 0) {
textArea.replaceRange(to.getText(),n,n+f.length());
;
}else if (source == delete) {
textArea.setText(" ");
}else if (source == upper) {
f.toUpperCase() ;
}
}
}
}
}
You have a shadowing problem. You declare...
private JButton findnext;
private JButton replace;
private JButton delete;
private JButton upper;
But in your constructor you do...
JButton findnext = new JButton("FindNext");
//...
JButton replace = new JButton("Replace");
//...
JButton delete = new JButton("Delete");
//...
JButton upper = new JButton("Upper");
Which is re-declaring those variables.
This means that when you try and do...
if (source == findnext) {
It's always false
You're also adding the ActionListener (this) to the findnext button four times...I think you mean to be adding it to each of the other buttons
Beware, there is already a class called Window in AWT, which could cause confusion for people. It's also discouraged to extend directly from a top level container like JFrame and instead should start with a JPanel and the add it to an instance of JFrame (or what ever container you like)
try this:
in ur constructor update this lines:
JButton findnext = new JButton("FindNext");
//
JButton replace = new JButton("Replace");
//
JButton delete = new JButton("Delete");
//
JButton upper = new JButton("Upper");
use this one:
findnext = new JButton("FindNext");
//
replace = new JButton("Replace");
//
delete = new JButton("Delete");
//
upper = new JButton("Upper");

Java GUI Adding objects to database

So I made a GUI which in this case if you want to add a Car to the database, you click "Add"
then a JFrame pops out with the following code:
public void newCar()
{
JFrame window = new JFrame("New Car");
JPanel newCarButtons = new JPanel();
newCarButtons.setLayout(new FlowLayout());
saveCar=new JButton("Save");
saveCar.addActionListener(buttonListener);
newCarButtons.add(saveCar);
cancelCar=new JButton("Cancel");
cancelCar.addActionListener(buttonListener);
newCarButtons.add(cancelCar);
JPanel newCarText = new JPanel();
GroupLayout group = new GroupLayout(newCarText);
newCarText.setLayout(group);
group.setAutoCreateGaps(true);
group.setAutoCreateContainerGaps(true);
JLabel make = new JLabel("Brand:");
JTextField maket = new JTextField(10);
newCarText.add(make);
newCarText.add(maket);
JLabel model = new JLabel("Model:");
JTextField modelt = new JTextField(10);
newCarText.add(model);
newCarText.add(modelt);
JLabel license = new JLabel("License Plate Numbers:");
JTextField licenset = new JTextField(10);
newCarText.add(license);
newCarText.add(licenset);
JLabel color = new JLabel("Color:");
JTextField colort = new JTextField(10);
newCarText.add(color);
newCarText.add(colort);
JLabel year = new JLabel("Year:");
final JTextField yeart = new JTextField(10);
yeart.addKeyListener(new KeyAdapter()
{
#Override
public void keyTyped(KeyEvent e)
{
super.keyTyped(e);
e.getKeyCode();
if (!((int) e.getKeyChar() >= 48 && (int) e.getKeyChar() <= 57))
{
e.consume();
}
}
});
newCarText.add(year);
newCarText.add(yeart);
JLabel horse = new JLabel("Horse Power: ");
JTextField horset = new JTextField(10);
newCarText.add(horse);
newCarText.add(horset);
JLabel isAvailable = new JLabel("Car Status:");
JLabel isAvailablet = new JLabel("Available");
newCarText.add(isAvailable);
newCarText.add(isAvailablet);
JLabel time = new JLabel("Time Until Service: ");
JTextField timet = new JTextField(10);
newCarText.add(time);
newCarText.add(timet);
JLabel consumption = new JLabel("Consumption per 100km: ");
JTextField consumptiont = new JTextField(10);
newCarText.add(consumption);
newCarText.add(consumptiont);
JLabel seats = new JLabel("Number of Seats: ");
JTextField seatst = new JTextField(10);
seatst.addKeyListener(new KeyAdapter()
{
#Override
public void keyTyped(KeyEvent e)
{
super.keyTyped(e);
e.getKeyCode();
if (!((int) e.getKeyChar() >= 48 && (int) e.getKeyChar() <= 57))
{
e.consume();
}
}
});
newCarText.add(seats);
newCarText.add(seatst);
JLabel doors = new JLabel("Number of Doors: ");
JTextField doorst = new JTextField(10);
doorst.addKeyListener(new KeyAdapter()
{
#Override
public void keyTyped(KeyEvent e)
{
super.keyTyped(e);
e.getKeyCode();
if (!((int) e.getKeyChar() >= 48 && (int) e.getKeyChar() <= 57))
{
e.consume();
}
}
});
newCarText.add(doors);
newCarText.add(doorst);
JLabel transmission = new JLabel("Transmission ");
JComboBox transmissiont = new JComboBox<String>();
transmissiont.addItem("Auto");
transmissiont.addItem("Manual");
transmissiont.addActionListener(buttonListener);
newCarText.add(transmission);
newCarText.add(transmissiont);
JLabel climate = new JLabel("Climate Control: ");
JComboBox climatet = new JComboBox<String>();
climatet.addItem("Yes");
climatet.addItem("No");
newCarText.add(climate);
newCarText.add(climatet);
GroupLayout.SequentialGroup hGroup = group.createSequentialGroup();
hGroup.addGroup(group.createParallelGroup().addComponent(make)
.addComponent(model).addComponent(license).addComponent(color)
.addComponent(time).addComponent(consumption)
.addComponent(year).addComponent(horse).addComponent(isAvailable)
.addComponent(seats).addComponent(doors).addComponent(transmission)
.addComponent(climate));
hGroup.addGroup(group.createParallelGroup().addComponent(maket)
.addComponent(modelt).addComponent(licenset).addComponent(colort)
.addComponent(timet).addComponent(consumptiont)
.addComponent(yeart).addComponent(isAvailablet)
.addComponent(horset).addComponent(seatst).addComponent(doorst)
.addComponent(transmissiont).addComponent(climatet));
group.setHorizontalGroup(hGroup);
GroupLayout.SequentialGroup vGroup = group.createSequentialGroup();
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(make).addComponent(maket));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(model).addComponent(modelt));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(license).addComponent(licenset));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(color).addComponent(colort));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(year).addComponent(yeart));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(horse).addComponent(horset));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(time).addComponent(timet));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(consumption).addComponent(consumptiont));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(isAvailable).addComponent(isAvailablet));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(seats).addComponent(seatst));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(doors).addComponent(doorst));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(transmission).addComponent(transmissiont));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(climate).addComponent(climatet));
group.setVerticalGroup(vGroup);
JPanel newCar = new JPanel();
newCar.setLayout(new BorderLayout());
newCar.add(newCarText, BorderLayout.NORTH);
newCar.add(newCarButtons, BorderLayout.SOUTH);
newCar.setBorder(new TitledBorder(BorderFactory
.createLineBorder(Color.black), "[New Car]", 2, 0));
Car car1= new Car(maket.getText(), modelt.getText(), licenset.getText(), colort.getText(), Integer.parseInt("yeart.getText()"), null, horset.getText(), timet.getText(), consumptiont.getText(), Integer.parseInt("seatst.getText()"), Integer.parseInt("doorst.getText()"), null, null, 0);
window.add(newCar);
window.setLocationRelativeTo(null);
window.setSize(400, 450);
window.setVisible(true);
}
Notice that at the bottom there is a Car object. This is where i need your help. The adapter, when adding cars, takes a Car object as an argument, so the idea is to fill out all the text fields and based on the text you input , you create a new Car object. But if I do this ,this way it will just create a empty Car object since when you open the window you don't have anything in the textfields. So how do i make that when you click "Add" it sends out a filled Car object based on the content in the text fields?
Button Listener:
private class MyButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == addCars)
{
newCar();
}
if (e.getSource() == saveCar)
{
adapter.addCar(car);
}
}
}
Why don't you simply pass your car object as argument to newCar method and initialize proper fields there just as you are doing when you are persisting car instance?
if (e.getSource() == addCars)
{
newCar(car);
}
remember to change newCar method signature.
public void newCar(Car newCar)
{
//DO WHATEVER YOU WANT WITH THAT DATA AND INITIALIZE PROPER FIELDS
JFrame window = new JFrame("New Car");
(.....)
This should go inside the listener
Car car1= new Car(maket.getText(), modelt.getText(), licenset.getText(),
colort.getText(), Integer.parseInt("yeart.getText()"), null,
horset.getText(), timet.getText(), consumptiont.getText(),
Integer.parseInt("seatst.getText()"),
Integer.parseInt("doorst.getText()"),
null, null, 0);
You want to get the text when the button is pressed. Not in your constructor
private class MyButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == addCars)
{
newCar(); // I don't know what you're trying to do here
}
if (e.getSource() == saveCar)
{
Car car1= new Car(maket.getText(), modelt.getText(), licenset.getText(),
colort.getText(), Integer.parseInt("yeart.getText()"), null,
horset.getText(), timet.getText(), consumptiont.getText(),
Integer.parseInt("seatst.getText()"),
Integer.parseInt("doorst.getText()"),
null, null, 0);
// add car1 to database
}
}
}
Edit: Declare all your textfields as class members, then you can use them in yout listener class
public class GUI{
JTextFeild maket = new JTextField();
JTextFeild licenset = new JTextField();
JTextFeild colort = new JTextField();
JTextFeild yeart = new JTextField();
JTextFeild horset = new JTextField();
JTextFeild timet = new JTextField();
JTextFeild consumptiont = new JTextField();
JTextFeild maket = new JTextField();
public void newCar(){
... // remove your textfields from here.
}
public static void main(String[] args){
...
}
private class MyButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == addCars)
{
newCar(); // I don't know what you're trying to do here
}
if (e.getSource() == saveCar)
{
Car car1= new Car(maket.getText(), modelt.getText(), licenset.getText(),
colort.getText(), Integer.parseInt("yeart.getText()"), null,
horset.getText(), timet.getText(), consumptiont.getText(),
Integer.parseInt("seatst.getText()"),
Integer.parseInt("doorst.getText()"),
null, null, 0);
// add car1 to database
}
}
}
}

How to make the txPanel visible only after the 'enter pin ok' button has been clicked?

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?

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