Modifying a JTextField after reading String from another JTextField - java

Having some problems updating a JTextField in a different class after reading a String from another JTextField. Here's the method in question:
public JTextField buyVowel(playerPlate player)
{
String get = input.getText();
String[] vowels = new String[]{"a","e","i","o","u"};
for(int i =0; i<vowels.length; i++)
{
if(get.equals(vowels[i]))
{
player.pMoney =- 250;
player.playerMoney.setText("$"+player.pMoney);
}
}
return player.playerMoney;
}
playerPlate is a separate class.
I'm using this method to determine what player the program should be modifying:
public playerPlate getCurrentPlayer()
{
if(currentPlayer == 1)
{
return player1;
}
else if(currentPlayer == 2)
{
return player2;
}
else
{
return player3;
}
}
player(s) 1, 2, and 3 are instances of playerPlate.
I want it to be modifying instance variables in this class:
package wheelOfFortune;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class playerPlate extends JPanel
implements ActionListener
{
public String pName;
public int pMoney = 500;
public int currentPlayer;
public JTextField playerMoney;
public playerPlate(String player, Color color, int currentPlayer)
{
setBorder(BorderFactory.createLineBorder(Color.BLACK,2));
setBackground(color);
pName = player;
JTextField playerNames = new JTextField(pName);
playerNames.setBorder(BorderFactory.createLineBorder(Color.BLACK,2));
playerNames.setEditable(false);
playerNames.setFont(new Font("Impact", Font.PLAIN, 24));
playerNames.setHorizontalAlignment(JTextField.CENTER);
playerNames.setBackground(Color.WHITE);
JTextField playerMoney = new JTextField("$"+pMoney);
playerMoney.setBorder(BorderFactory.createLineBorder(Color.BLACK,2));
playerMoney.setEditable(false);
playerMoney.setFont(new Font("Impact", Font.BOLD, 32));
playerMoney.setHorizontalAlignment(JTextField.CENTER);
playerMoney.setBackground(Color.WHITE);
Box b1 = Box.createVerticalBox();
b1.add(playerNames);
b1.add(Box.createVerticalStrut(5));
Box b2 = Box.createHorizontalBox();
b2.add(Box.createHorizontalStrut(60));
Box b3 = Box.createVerticalBox();
b3.add(playerMoney);
b3.add(Box.createVerticalStrut(8));
b2.add(b3);
b1.add(b2);
b1.add(Box.createVerticalStrut(5));
add(b1);
}
public void actionPerformed(ActionEvent e)
{
}
}
Here is the actionPerformed method within the main class:
public void actionPerformed(ActionEvent e)
{
JButton b = (JButton)e.getSource();
if(b==spin)
{
spinWheel(wheelStuff);
repaint();
}
if(b==next)
{
updatePlayer();
repaint();
}
if(b==reset)
{
letterBoard.reset();
updateCat();
repaint();
}
if(b==buyVowel)
{
buyVowel(getCurrentPlayer());
repaint();
}
}
The gist of what I want to happen, is when the user types a vowel into JTextField input, and clicks JButton buyVowel it subtracts $250 from their total money (pMoney). And displays the change on the GUI. After tinkering with this for a couple hours, I honestly have no idea why this isn't working. I keep receiving nullPointerExceptions when trying to use it. Thanks for your help.
Note: everything except for class playerPlate is in the same class. playerPlate is in a separate class.

You're shadowing the variable playerMoney in the constructor of playerPlate. The method buyVowel relies on playerPlate being instantiated when invoking setText, otherwise a NullPointerException will be thrown. Replace
JTextField playerMoney = new JTextField("$"+pMoney);
with
playerMoney = new JTextField("$"+pMoney);
Aside: Java naming conventions indicate that class names start with uppcase letters so use class names such as PlayerPlate.

Related

How to run a method from another class when button is pressed?

I'm creating a TicTacToe program for a Java project. I'm using swing with a 3x3 panel as the GUI and integrating buttons into each box for the user to click. The problem is, I do not know how to run the WinCondition method (meaning when a user gets 3 in a row). I am not able to call it to the actionPerformed method in the button class, and I don't know where else it would be viable to call.
I have two classes, one is a button class and another is the actual game which creates the panel for the user.
I've tried thinking about where else I could implement it, but I cannot because I do not know another way to execute code when a button is pressed other than the actionPerformed method.
public class TicTacGame extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
JPanel p = new JPanel();
XOButton[] buttons = new XOButton[9];
public TicTacGame() {
super("TicTacToe");
setSize(400,400);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
p.setLayout(new GridLayout(3,3));
for(int i = 0; i < 9; i++) {
buttons[i] = new XOButton();
p.add(buttons[i]);
}
add(p);
setVisible(true);
}
public int winCondition() {
//I have left out the win condition method so this box doesn't get unnecessarily long
}
public static void main(String[] args) {
TicTacGame ttg = new TicTacGame();
}
}
public class XOButton extends JButton implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
ImageIcon X;
ImageIcon O;
//0 is nothing, 1 is X, 2 is O
int value = 0;
public static int turn = 1;
public XOButton() {
X = new ImageIcon(this.getClass().getResource("X.png"));
O = new ImageIcon(this.getClass().getResource("O.png"));
addActionListener(this);
}
public int getValue() {
return this.value;
}
public void actionPerformed(ActionEvent e) {
if(turn >= 5) {
int win = ttg.winCondition();
}
if(turn % 2 == 0) {
value += 2;
turn++;
}
else {
value++;
turn++;
}
value %= 3;
switch(value) {
case 0:
setIcon(null);
break;
case 1:
setIcon(X);
removeActionListener(this);
break;
case 2:
setIcon(O);
removeActionListener(this);
break;
}
}
}
What I expect is that whenever a button is clicked, the winCondition() method is executed to check if a user won or not.
there's a plenty ways to do that one of them
DON'T
create the win method static, so that you can access from any other class. for more info read comments below
1)you can pass a reference from TicTacGame class into XOButton class in the constructor.. so that you've the access to any other function in TicTacGame class
2)you can use interfaces....etc

ActionListener class keeps repeating when swing Timer is started

I am trying to develop a very basic "Simon says" simulator using Java GUI. I have a method that generates and returns an int[] array; for each element in the array, the Timer computer should start, call the doClick() method for the specified JButton, and wait for 1/2 a second. Each JButton is connected to an ActionListener() that changes the color of the specific button to white, activates another Timer timer, and changes the button back to its original color.
Every time I call computer.start(); within the for-loop it runs the code within ComputerListener(), but it repeats endlessly. I have added print statements so that I can see what is going on via the output on Netbeans. I have looked at similar issues on the forum, but nothing has provided a viable solution.
My question: why is my ComputerListener class repeating when computer.start(); is called within the for-loop?
package simon;
// #jagged_prospect
import java.util.Random;
import java.util.Arrays;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.ButtonUI;
import javax.swing.plaf.basic.BasicButtonUI;
public class SIMONPanel extends JPanel{
private static final int PANEL_W=300,PANEL_H=300;
private static final int PREF_W=500,PREF_H=500;
private static final String[] CARD_LABELS={"main","info","game"};
private final JPanel gameCard,infoCard,splashCard;
private final JButton rButton,yButton,gButton,bButton;
private final int lives=3;
private CardLayout cardlayout=new CardLayout();
private JPanel cards=new JPanel(cardlayout);
private Action[] actions={new ShowMainAction(),new ShowInfoAction(),
new ShowGameAction()};
private Object source;
private Timer timer,computer;
public SIMONPanel(){
setBackground(Color.BLACK);
setLayout(new BorderLayout());
gameCard=new JPanel();
infoCard=new JPanel();
splashCard=new JPanel();
// game card panel
gameCard.setLayout(new BorderLayout());
gameCard.setPreferredSize(new Dimension(PANEL_W,PANEL_H));
JPanel gameButtonPanel=new JPanel();
gameButtonPanel.setLayout(new GridLayout(2,2));
JButton startButton=new JButton("Start");
startButton.addActionListener(new StartListener());
rButton=new JButton("red");
rButton.addActionListener(new ColorButtonListener());
rButton.setSize(50,50);
rButton.setUI((ButtonUI)BasicButtonUI.createUI(rButton));
rButton.setBackground(Color.RED);
rButton.setForeground(Color.WHITE);
yButton=new JButton("yellow");
yButton.addActionListener(new ColorButtonListener());
yButton.setSize(50,50);
yButton.setUI((ButtonUI)BasicButtonUI.createUI(yButton));
yButton.setBackground(Color.YELLOW);
gButton=new JButton("green");
gButton.addActionListener(new ColorButtonListener());
gButton.setSize(50,50);
gButton.setUI((ButtonUI)BasicButtonUI.createUI(gButton));
gButton.setBackground(Color.GREEN);
bButton=new JButton("blue");
bButton.addActionListener(new ColorButtonListener());
bButton.setSize(50,50);
bButton.setUI((ButtonUI)BasicButtonUI.createUI(bButton));
bButton.setBackground(Color.BLUE);
bButton.setForeground(Color.WHITE);
gameButtonPanel.add(gButton);
gameButtonPanel.add(rButton);
gameButtonPanel.add(yButton);
gameButtonPanel.add(bButton);
gameCard.add(gameButtonPanel,BorderLayout.CENTER);
gameCard.add(startButton,BorderLayout.SOUTH);
// splash card panel
splashCard.setLayout(new BorderLayout());
splashCard.setPreferredSize(new Dimension(PANEL_W,PANEL_H));
splashCard.setBackground(Color.BLACK);
JLabel titleLabel=new JLabel("S I M O N",SwingConstants.CENTER);
titleLabel.setFont(new Font("Niagara Solid",Font.BOLD,84));
titleLabel.setForeground(Color.WHITE);
splashCard.add(titleLabel,BorderLayout.CENTER);
// info card panel
// nothing here yet
JPanel buttonPanel=new JPanel(new GridLayout(1,0,5,0));
for(Action action : actions){
buttonPanel.add(new JButton(action));
buttonPanel.setBackground(Color.BLACK);
}
cards.add(splashCard,CARD_LABELS[0]);
cards.add(infoCard,CARD_LABELS[1]);
cards.add(gameCard,CARD_LABELS[2]);
add(cards,BorderLayout.CENTER);
add(buttonPanel,BorderLayout.SOUTH);
}
// sets uniform panel size
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
// shows the Main Menu card
private class ShowMainAction extends AbstractAction {
public ShowMainAction() {
super("Main");
}
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.show(cards,CARD_LABELS[0]);
}
}
// shows the Info card
private class ShowInfoAction extends AbstractAction {
public ShowInfoAction() {
super("Info");
}
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.show(cards,CARD_LABELS[1]);
}
}
// show the Game card
private class ShowGameAction extends AbstractAction {
public ShowGameAction() {
super("Game");
}
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.show(cards,CARD_LABELS[2]);
}
}
private class TimerListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent event){
if(source==gButton){
gButton.setBackground(Color.GREEN);
}
else if(source==rButton){
rButton.setBackground(Color.RED);
rButton.setForeground(Color.WHITE);
}
else if(source==yButton){
yButton.setBackground(Color.YELLOW);
}
else if(source==bButton){
bButton.setBackground(Color.BLUE);
bButton.setForeground(Color.WHITE);
}
}
}
private class ColorButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent event){
source=event.getSource();
int delay=300;
timer=new Timer(delay,new TimerListener());
if(source==gButton){
gButton.setBackground(Color.WHITE);
timer.setRepeats(false);
timer.start();
}
else if(source==rButton){
rButton.setBackground(Color.WHITE);
rButton.setForeground(Color.BLACK);
timer.setRepeats(false);
timer.start();
}
else if(source==yButton){
yButton.setBackground(Color.WHITE);
timer.setRepeats(false);
timer.start();
}
else if(source==bButton){
bButton.setBackground(Color.WHITE);
bButton.setForeground(Color.BLACK);
timer.setRepeats(false);
timer.start();
}
}
}
private class StartListener implements ActionListener{
public void actionPerformed(ActionEvent event){
// calls generateSequence() to make pattern for player to replicate
// for debugging in output
System.out.println(Arrays.toString(generateSequence()));
}
}
public int[] generateSequence(){
Random ran=new Random();
ComputerListener cpu=new ComputerListener();
computer=new javax.swing.Timer(500,cpu);
int seqLen=4;
int[] gameSequence=new int[seqLen];
for(int x=0;x<seqLen;x++){
int assign=ran.nextInt(4)+1;
gameSequence[x]=assign;
}
for(int y=0;y<seqLen;y++){ // print and wait 1/2 second, repeat 3 times
computer.start();
}
//computer.stop(); // should stop ComputerListener()???
return gameSequence;
}
private class ComputerListener implements ActionListener{
public void actionPerformed(ActionEvent event){
// for debugging in output
System.out.println("it worked");
}
}
}
You're calling the computer Swing Timer's start button multiple times in a for loop, and that is not what you want to do, and in fact, the whole purpose of the timer is to help you get rid of the for loop. Instead the Timer repeats an action, and changes a state, and keeps going until its done. Consider using an int array or better an ArrayList to hold the colors that the timer should iterate through, and within that ActionListener, do the action and advance a pointer to the next position in the array or List, using that pointer to decide what action to do next. Then when the pointer is completely through the collection, stop the Timer.
For an example of exactly what I'm describing, please check out my Timer's ActionListener for an incomplete Simon game here: Method keeps window from closing
The Timer's ActionListener, annotated, is below:
private class TimerListener implements ActionListener {
private SimonPanel simonPanel; // the Simon JPanel
private int colorListIndex = 0; // index into the ArrayList of MyColor objects
private int sliceCount = 0;
private List<MyColor> myColorList; // the MyColor ArrayList -- the random colors to press
private int maxCount;
public TimerListener(SimonPanel simonPanel, List<MyColor> myColorList) {
// pass in the key fields into the program via constructor parameter
this.simonPanel = simonPanel;
this.myColorList = myColorList; // again the ArrayList that holds random MyColor objects
maxCount = myColorList.size(); // size of my list
}
#Override
public void actionPerformed(ActionEvent evt) {
// if index at the end of the list -- get out and clean up
if (colorListIndex == maxCount) {
// clear the display of "pressed" colors
for (MyColor myColor : MyColor.values()) {
simonPanel.setMyColorPressed(myColor, false);
}
// stop this timer
((Timer) evt.getSource()).stop();
return;
}
// the listener is a little complex since it must turn on colors and turn them off
// which is why I use a sliceCount int counter variable here
if (sliceCount == 0) {
// turn on the next color in the list (using the index)
MyColor myColor = myColorList.get(colorListIndex);
simonPanel.setMyColorPressed(myColor, true);
sliceCount++;
} else if (sliceCount < TIME_SLICES - 1) {
sliceCount++;
return;
} else if (sliceCount == TIME_SLICES - 1) {
sliceCount = 0;
MyColor myColor = myColorList.get(colorListIndex);
simonPanel.setMyColorPressed(myColor, false); // turn off the color
colorListIndex++; // and increment the index
return;
}
}
}

Java: Add Place Holder on JTextField

Is there a way or method in which we can add placeholder in j text field. I want to add placeholder "Enter Your Number" in field but how can I do this. I check all methods but didn't working.
Code:
public class Loop extends JFrame{
private JTextField t1;
public L(){
getContentPane().setLayout(null);
t1=new JTextField();
t1.setBounds(27,50,47,28);
getContentPane().add(t1);
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Main:
public class Main {
public static void main(String[] args) {
L object = new L();
}
}
Check out Text Prompt for a flexible solution.
You can control when prompt is displayed (always, focus gained or focus lost). You can also customize the style of the text.
Here is an example of which you can you inspire
package TinyOS;
import java.awt.*;
import javax.swing.*;
import javax.swing.text.Document;
#SuppressWarnings("serial")
public class PlaceholderTextField extends JTextField {
public static void main(final String[] args) {
final PlaceholderTextField tf = new PlaceholderTextField ("");
tf.setColumns(20);
tf.setPlaceholder("Here is a placeHolder!");
final Font f = tf.getFont();
tf.setFont(new Font(f.getName(), f.getStyle(), 30));
JOptionPane.showMessageDialog(null, tf);
}
private String placeholder;
public PlaceholderTextField () {
}
public PlaceholderTextField (
final Document pDoc,
final String pText,
final int pColumns)
{
super(pDoc, pText, pColumns);
}
public PlaceholderTextField (final int pColumns) {
super(pColumns);
}
}
I hope that can help you
This code should work, it listen on first click and removes the text
public class Loop extends JFrame{
private JTextField t1;
private boolean clicked = false;
public L(){
getContentPane().setLayout(null);
t1=new JTextField();
t1.setText("Enter Your Number");
t1.addMouseListener(new MouseAdapter(){
#Override
public void mousePressed(MouseEvent e){
if(!clicked){
clicked=true;
t1.setText("");
}
}
}
t1.setBounds(27,50,47,28);
getContentPane().add(t1);
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Maybe better solution exists
Note - not tested
EDIT (how the boolean clicked works)
when you call method mousePressed(MouseEvent) at the first time, the clicked variable is false, by declaration:
private boolean clicked = false;
So the if body is executed (because !clicked = !false = true)
in the if body, the clicked variable is set to true, so if condition will be then false: (because !clicked = !true = false)
This solves the problem of running code just once.

How do I use the outcome of my actionPerformed method to effect the main method - java

I have a class called Screen containing the actionPerformed method.
I want a different outcome for the different menu items: random, aggressive and human.
This outcome effects the main method, however I am unsure how to link the two...
public class Screen extends JFrame
implements ActionListener {
ActionListener listener;
JMenuItem random = new JMenuItem("Random");
JMenuItem aggressive = new JMenuItem("Aggressive");
JMenuItem human = new JMenuItem("Human");
public Screen(Board board){
//menuBar items
menu.add(random);
random.addActionListener(this);
menu.add(aggressive);
aggressive.addActionListener(this);
menu.add(human);
human.addActionListener(this);
....
//sets up board of buttons and adds actionListener to each.
....
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == random){
}
if(e.getSource() == aggressive){
}
if(e.getSource() == human){
}
//code for the board buttons - nothing to do with the menu.
//But thought it might help
if (numClicks == 0){
JButton piece = (JButton) e.getSource();
String xy = piece.getName();
String x = xy.substring(0,1);
String y = xy.substring(2,3);
FromXInt = Integer.parseInt(x);
FromYInt = Integer.parseInt(y);
System.out.println("From" + " " +FromXInt + "," + FromYInt);
}
else{
JButton piece = (JButton) e.getSource();
String xy = piece.getName();
String x = xy.substring(0,1);
String y = xy.substring(2,3);
ToXInt = Integer.parseInt(x);
ToYInt = Integer.parseInt(y);
System.out.println("To" + " " + ToXInt + "," + ToYInt);
}
numClicks++;
if (numClicks >= 2){
numClicks = 0;
}
return;
}
}
My class which contains the main method:
public class Chess{
public static void main(String [ ] args){
Screen s = new Screen(board);
// my attempt but doesn't work
if (s.actionPerformed(e) == random){
.....
note: I am new to Java and still trying to get my head round the linking of multiple classes.
--------------------The ActionPerformed method also contains events if buttons are clicked but I haven't added that code in because it over complicates things.--
This approach uses a public enum and sets the style variable according to the users menu choice:
package chess;
//...
public class Screen extends JFrame
implements ActionListener {
private JMenuItem random = new JMenuItem("Random");
private JMenuItem aggressive = new JMenuItem("Aggressive");
private JMenuItem human = new JMenuItem("Human");
public enum PlayStyle {Random, Aggressive, Human};
private PlayStyle style;
public Screen(Board board) {
//menuBar items
menu.add(random);
random.addActionListener(this);
menu.add(aggressive);
aggressive.addActionListener(this);
menu.add(human);
human.addActionListener(this);
//....
//sets up board of buttons and adds actionListener to each.
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == random) {
style=PlayStyle.Random;
}
if (e.getSource() == aggressive) {
style=PlayStyle.Aggressive;
}
if (e.getSource() == human) {
style=PlayStyle.Human;
}
//code for the board buttons - nothing to do with the menu.
//....
}
public PlayStyle getStyle(){
return style;
}
}
This is the class that contains the main method:
package chess;
import chess.Screen.PlayStyle;
public class Chess{
public static void main(String [ ] args){
Screen s = new Screen(board);
// this attempt will work
if (s.getStyle()==PlayStyle.Random) {
...
} else if (s.getStyle()==PlayStyle.Aggressive){
...
You are calling a method and it seems that you want to use something that comes back from that method but the method itself returns nothing, i.e. "void". I changed your Screen class so that the method returns something now.
public class Screen extends JFrame
implements ActionListener {
public Source actionPerformed(ActionEvent e) {
....
if(e.getSource() == random){
}
if(e.getSource() == aggressive){
}
if(e.getSource() == human){
}
return e.getSource()
}
The main method will now be able to receive a result from the call and use it.

Item Listeners Error

I'm having an issue with Item Listeners.It's the first time I'm using it, so far all I've used is the Item Event. I was wondering if you could clear up what the difference between those two, as well point me out what I'm doing wrong.
My issue is on line 46 the line starting with: Object source = toppingList.getSource(); and the error I get is 'Cannot find symbol'.
I'm thinking I'm using the wrong item before the getSource();, I thought that the toppingList was the correct item, I can't see which other item I could put in it's place.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Pizza extends JFrame{
FlowLayout flow = new FlowLayout();
JComboBox pizzaBox = new JComboBox();
JLabel toppingList = new JLabel("Topping List");
JLabel aLabel = new JLabel("Paulos's American Pie");
JTextField totPrice = new JTextField(10);
int[] pizzaPrice = {7,10,10,8,8,8,8};
int totalPrice = 0;
String output;
int pizzaNum;
public Pizza()
{
super("Pizza List");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(flow);
pizzaBox.addItemListener((ItemListener) this);
add(toppingList);
pizzaBox.addItem("cheese");
pizzaBox.addItem("sausage");
pizzaBox.addItem("pepperoni");
pizzaBox.addItem("onion");
pizzaBox.addItem("green pepper");
pizzaBox.addItem("green olive");
pizzaBox.addItem("black olive");
add(pizzaBox);
add(aLabel);
add(totPrice);
}
public static void main(String[] arguments)
{
JFrame frame = new DebugFourteen3();
frame.setSize(200, 150);
frame.setVisible(true);
}
public void itemStateChanged(ItemEvent[] list)
{
Object source = toppingList.getSource();
if(source == pizzaBox)
{
int pizzaNum = pizzaBox.getSelectedIndex();
totalPrice = pizzaPrice[pizzaNum];
output = "Pizza Price $" + totalPrice;
totPrice.setText(output);
}
}
}
Gui elements do not have any getSource, it is a method of the event - telling you which gui element generated the event. But you know what the source of the event is, since in your constructor you wrote:
pizzaBox.addItemListener((ItemListener) this);
and you did not add this to any other gui element. So you cannot get events from any other gui element. So do not test for it.
But there are other issues:
Your PizzaBox should implement ItemListener:
public class Pizza extends JFrame implement ItemListener
and then just write
pizzaBox.addItemListener(this);
If you want to listen to multiple elements, add separate anonymous listener for each (and Pizza does not implement ItemListener)
// in your constructor:
pizzaBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
pizzaNum = pizzaBox.getSelectedIndex(); // in your code you have int pizzaNum but at the same time, pizzaNum is a class variable, probably an error
// and so on
}
}
});
or you can move the code to a separate method
public class Pizza extends JFrame {
public Pizza() {
:
pizzaBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
pizzaBox_itemStateChanged(e);
}
});
:
}
private void pizzaBox_itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
pizzaNum = pizzaBox.getSelectedIndex();
// and so on
}
}
:
}
You need to implement ItemListener with class. For details go through this tutorial
public class Pizza extends JFrame implements ItemListener{
.....
public Pizza(){
pizzaBox.addItemListener(this);// Here this is enough
....
}
// itemStateChanged should write as follows
public void itemStateChanged(ItemEvent e) {
//It will be enable if checkbox is selected
if (e.getStateChange() == ItemEvent.SELECTED) {
int pizzaNum = pizzaBox.getSelectedIndex();
totalPrice = pizzaPrice[pizzaNum];
output = "Pizza Price $" + totalPrice;
totPrice.setText(output);
}
}
}

Categories