"Unexpected type" error - java

I'm having a problem compiling my Java program:
\Desktop\Java Programming\JFrameWithPanel.java:79: unexpected type
required: variable
found : value
if(serviceTerms.isSelected() = false)
^
1 error
What is causing this error?
public class JFrameWithPanel extends JFrame implements ActionListener, ItemListener
{
int packageIndex;
double price;
double[] prices = {49.99, 39.99, 34.99, 99.99};
DecimalFormat money = new DecimalFormat("$0.00");
JLabel priceLabel = new JLabel("Total Price: "+price);
JButton button = new JButton("Check Price");
JComboBox packageChoice = new JComboBox();
JPanel pane = new JPanel();
TextField text = new TextField(5);
JButton accept = new JButton("Accept");
JButton decline = new JButton("Decline");
JCheckBox serviceTerms = new JCheckBox("I Agree to the Terms of Service.", false);
JTextArea termsOfService = new JTextArea("This is a text area", 5, 10);
public JFrameWithPanel()
{
super("JFrame with Panel");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pane.add(packageChoice);
setContentPane(pane);
setSize(250,250);
setVisible(true);
packageChoice.addItem("A+ Certification");
packageChoice.addItem("Network+ Certification ");
packageChoice.addItem("Security+ Certifictation");
packageChoice.addItem("CIT Full Test Package");
pane.add(button);
button.addActionListener(this);
pane.add(text);
text.setEditable(false);
text.setBackground(Color.WHITE);
text.addActionListener(this);
pane.add(termsOfService);
termsOfService.setEditable(false);
termsOfService.setBackground(Color.lightGray);
pane.add(serviceTerms);
serviceTerms.addItemListener(this);
pane.add(accept);
accept.addActionListener(this);
pane.add(decline);
decline.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
packageIndex = packageChoice.getSelectedIndex();
price = prices[packageIndex];
text.setText("$"+price);
Object source = e.getSource();
if(source == accept)
{
if(serviceTerms.isSelected() = false) // line 79
{
JOptionPane.showMessageDialog(null,"Please accept the terms of service.");
}
else
{
JOptionPane.showMessageDialog(null,"Thanks.");
}
}
}

You have an (illegal) assignment instead of a comparison. Surely you mean:
if (serviceTerms.isSelected() == false)
Of course the preferential, and more readable, way to write this condition is:
if (!serviceTerms.isSelected())

The problem is that you are using the assignment operator =. What you should be using is the equality operator == like the following:
if(serviceTerms.isSelected() == false) // line 79
{
JOptionPane.showMessageDialog(null,"Please accept the terms of service.");
}
Or, to totally bypass this mistake, you should skip comparing to false and use the ! (not) operator like so.
if(!serviceTerms.isSelected()) // line 79
{
JOptionPane.showMessageDialog(null,"Please accept the terms of service.");
}
I feel this way reads better.
If not, service terms is selected
That reads more like a sentence than:
If service terms is selected equals false

Related

Java TextField Date auto fill

Alright I got something like this:
public void menu() {
final Form menu = new Form("Menu");
menu.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
Button confirm = new Button("Confirm");
Container creditCardContainer = new Container(new GridLayout(1, 3));
final TextField num1 = new TextField(3);
final TextField num2 = new TextField(3);
final TextField num3 = new TextField(3);
num1.setConstraint(TextArea.NUMERIC);
num2.setConstraint(TextArea.NUMERIC);
num3.setConstraint(TextArea.NUMERIC);
creditCardContainer.addComponent(num1);
creditCardContainer.addComponent(num2);
creditCardContainer.addComponent(num3);
Validator v = new Validator();
v.addConstraint(num1, new LengthConstraint(2));
v.addConstraint(num2, new LengthConstraint(2));
v.addConstraint(num3, new LengthConstraint(4));
automoveToNext(num1, num2);
automoveToNext(num2, num3);
menu.add(creditCardContainer);
menu.add(confirm);
v.addSubmitButtons(confirm);
menu.show();
confirm.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
String getdate = num1.getText() + "/" + num2.getText() + "/" + num3.getText();
System.out.println(getdate);
new StateMachine("/theme");
}
});
}
}
private void automoveToNext(final TextField current, final TextField next) {
current.addDataChangedListener(new DataChangedListener() {
public void dataChanged(int type, int index) {
if(current.getText().length() == 3) {
Display.getInstance().stopEditing(current);
String val = current.getText();
current.setText(val.substring(0, 2));
next.setText(val.substring(2));
Display.getInstance().editString(next, 3, current.getConstraint(), next.getText());
}
}
});
}
Notice that addDataChangeListener is deprecated so I had to change it to addDataChangedListener instead.
I think there is something wrong in my code, because when I run it in the Codename One Simulator, it still allow me to type letters, even with the code below:
num1.setConstraint(TextArea.NUMERIC);
num2.setConstraint(TextArea.NUMERIC);
num3.setConstraint(TextArea.NUMERIC);
Also when I finish typing the date, my confirm button doesn't get highlighted as it should be. Please someone help me to fix it.
Obs: My date is intended to be dd/MM/yyyy
We don't support direct field masking as native text field input doesn't handle that very well. You have 2 options I can think of:
Use Date Picker which launches a great device native UI to pick the date. Notice it's not great in the simulator but on Android/iOS it would look good.
Use 3 text fields and automatically move to the next as you type like we did for this credit card input sample: http://www.codenameone.com/blog/validation-regex-masking.html
Using
try {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = format.parse("");
}catch (ParseException e) {
System.out.println("Wrong format.");
}
to check if the date is valid format.

Loading images and data from a text file and appending to it (Java)

I've created a platform game where each type of game object is assigned to specific rgb values so I can create levels by drawing them out in paint and loading the image. Right now I have the first two levels already loaded and I am able to get the path of the 3rd level through a textfield input and load a custom 3rd level. Each level needs a path to the png image of the level, and the number of coins needed to progress to the next level. I want to have every level load up from one text file where each line maybe has the level number, the image path, and the # of coins. I'm making it to be customizable so that the user can add or change levels simply by adding these parameters through 3 textfields in my customize menu. This way also my designer can help create levels and by reading from the text file I imagine there will be a lot less code in the long run when there are 20+ levels. Any ideas on how I can load from and append to this file? Here's what I'm working with right now:
public static BufferedImageLoader loader = new BufferedImageLoader();
public Handler(Camera cam){
this.cam = cam;
level1 = loader.loadImage("/level1.png");
level2 = loader.loadImage("/level2.png");
}
public void changeLevel(){
clearLevel();
cam.setX(0);
Player.coinCount = 0;
if(Game.LEVEL == 1){
Player.maxCoins = 4;
LoadImageLevel(level1);
}
if(Game.LEVEL == 2){
LoadImageLevel(level2);
Player.maxCoins = 11;
}
if(Game.LEVEL == 3){
System.out.println(Data.levelPath);
try{
level3 = loader.loadImage(Data.levelPath);
LoadImageLevel(level3);
} catch (Exception e) {
e.printStackTrace();
System.out.println("error loading custom level");
}
}
}
public Menu(Game game, Handler handler){
this.handler = handler;
pathField = new JTextField(10);
levelField = new JTextField(10);
coinField = new JTextField(10);
if(Game.gameState == STATE.Menu){
int selection = JOptionPane.showConfirmDialog(
null, getPanel(), "Input Form : "
, JOptionPane.OK_CANCEL_OPTION
, JOptionPane.PLAIN_MESSAGE);
if(selection == JOptionPane.OK_OPTION) {
Data.levelPath = pathField.getText();
Data.level = levelField.getText();
Data.coinAmount = Double.valueOf(coinField.getText());
System.out.println(Data.levelPath + Data.level + Data.coinAmount);
}
}
private JPanel getPanel(){
JPanel basePanel = new JPanel();
basePanel.setOpaque(true);
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(3, 2, 5, 5));
centerPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
centerPanel.setOpaque(true);
JLabel mLabel1 = new JLabel("Enter path: (e.g., /level1.png) ");
JLabel mLabel2 = new JLabel("Enter which level to load the image in: ");
JLabel mLabel3 = new JLabel("Enter the amount of coins you must collect");
centerPanel.add(mLabel1);
centerPanel.add(pathField);
centerPanel.add(mLabel2);
centerPanel.add(levelField);
centerPanel.add(mLabel3);
centerPanel.add(coinField);
basePanel.add(centerPanel);
return basePanel;
}
Any ideas or suggestions are appreciated!
It's actually just....
Given a value of the input.getText() as 1#path#20, It have level number, the image path, and the number of coins separated by # token.
public static String [] separateFields(String input, String separator){
String[] separatedValues = input.split("#");
return separatedValues;
}
Call the function, define the arguments.
// input is textfield.getText() , and the value of input is 1#path#20
String [] result= separateFields(input, "#");
Then you get
int level = Integer.parseInt(result[0]); // level
String aPath = result[1]; // path
int numCoins = Integer.parseInt(result[2]); // number of coins

A Java Swing Component Keeps Getting Disabled?

I am back with another problem :(
Let me show you guys the code:
JCheckBox pPec = new JCheckBox("Potion Effect");
pPec.setBounds(new Rectangle(50, 270, 140, 30));
pPec.setFont(fDisp);
List<String> pPeLl = new ArrayList<String>();
for (DPE dpe : DPE.values()){
pPeLl.add(dpe.toString());
}
String[] pPeL = pPeLl.toString().replace("[", "").replace("]", "").split(", ");
JComboBox<String> pPeE = new JComboBox<String>(pPeL);
pPeE.setBounds(new Rectangle(175, 270, 150, 30));
List<String> pPeNLl = new ArrayList<String>();
for (int i = 1; i <= 255; i++){
pPeNLl.add(Integer.toString(i));
}
String[] pPeNL = pPeNLl.toString().replace("[", "").replace("]", "").split(", ");
JComboBox<String> pPeN = new JComboBox<String>(pPeNL);
pPeN.setBounds(new Rectangle(175, 300, 73, 30));
JTextField pPeT = new JTextField();
((AbstractDocument)pPeT.getDocument()).setDocumentFilter(new NumberFilter());
pPeT.setBounds(new Rectangle(175+73+4, 300, 73, 30));
if (file.exists()){
for (String s : DFileLoader.getMethod(pathToSaveAs)){
if (s.startsWith("playerPotionEffect%%##")){
pPec.setSelected(true);
potionEffect = true;
break;
}else{
pPeN.setEnabled(false);
pPeT.setEnabled(false);
pPeE.setEnabled(false);
potionEffect = false;
}
}
if (DFileLoader.getMethod(pathToSaveAs).size() <= 0){
pPeN.setEnabled(false);
pPeT.setEnabled(false);
pPeE.setEnabled(false);
potionEffect = false;
}
}else{
pPeN.setEnabled(false);
pPeT.setEnabled(false);
pPeE.setEnabled(false);
potionEffect = false;
}
pPec.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (pPec.isSelected()){
pPeE.setEnabled(true);
pPeN.setEnabled(true);
pPeT.setEnabled(true);
}else if (!pPec.isSelected()){
pPeE.setEnabled(false);
pPeN.setEnabled(false);
pPeT.setEnabled(false);
}
if (pPec.isSelected()) potionEffect = true;
else potionEffect = false;
}
});
pane.add(pPec);
if (file.exists()){
for (String s : DFileLoader.getMethod(pathToSaveAs)){
if (s.startsWith("playerPotionEffect%%##")){
String[] d = s.split("%%##");
String text;
if (d.length <= 1) text = "";
else text = d[3];
pPeE.setSelectedItem(d[1]);
pPeN.setSelectedItem(d[2]);
pPeT.setText(text);
}
}
}
pane.add(pPeN);
pane.add(pPeT);
pane.add(pPeE);
The DFileLoader.getMethod(String) returns a String List
What I am trying to do is that it loads the information from a file, and if the file starts with "playerPotionEffect%%##" (as shown after file.exists()), it sets the checkbox as selected. If not, it doesn't select it and it disables the other components shown in this piece of code. The checkbox selection works fine, it's just when I load the file, the 2 JComboBoxes and the JTextField are disabled, even though I want them to be enabled.
Can anyone help me? It might be really obvious where the problem is, and that I just haven't noticed. I have tried moving code around, but it still doesn't work.
the "pane" is a Container for the JFrame's content pane.
Also, I have it set to as you click on the checkbox, it enables and disables the other components. This works, and if I turned the checkbox off and on again, the components would be enabled. However, I just want it so that it is enabled on load when the box is checked.
Lol I suck!
To fix this, I have to enable the components in the loop as well before the break. Not all the strings start with playerPotionEffect
xD

How can I add values from textfield when i press the button with not having all of the values

im working on a java program using GUI, and i ran into a problem whenever i try to add the values from the text fields and one is missing it doesn't work and i get an error but if all of them are available i get the right answer, how can i add without having all the values?
JButton btnCheckOut = new JButton("CHECK OUT");
btnCheckOut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double apples, strawberries, watermelon, tomatoe, carrot, beef, lamb, payment;
apples = Double.parseDouble(textField.getText());
strawberries = Double.parseDouble(textField_1.getText());
watermelon = Double.parseDouble(textField_2.getText());
tomatoe = Double.parseDouble(textField_3.getText());
carrot = Double.parseDouble(textField_4.getText());
beef = Double.parseDouble(textField_5.getText());
lamb = Double.parseDouble(textField_6.getText());
payment = (apples*8)+(strawberries*10)+(watermelon*14)+
(tomatoe*5)+(carrot*6)+(beef*25)+(lamb*20);
DecimalFormat df = new DecimalFormat("###.##");
textField_7.setText(String.valueOf(df.format(payment)));
}
});
Create e.g. getDoubleValue, which you apply to all your items when read. Simple as:
apples = getDoubleValue( textField.getText() );
...
...
then
public double getDoubleValue( String txt ) {
double d = 0d;
try {
if( txt != null && !txt.isEmpty() ) {
d = Double.parseDouble( txt );
}
} catch(Exception ex) {}
return d;
}
(This will also take care for "dirty input", if the textfield does not contain a number it will set it to zero during parse).
When you make your textFields, initialize the text there to 0. Like
JTextField textField_1 = new JTextField("0");
Or, you could add
if(textField.getText() == ""){
textField.setText("0");
}
For each text field before trying to parse to double.
Create an IF statement that sets the variables to zero if its respective TextField is empty, before you do the math operation.
if(textfield.getText().isEmpty())
{
apples = 0;
}

Image as a variable in JLabel, to be used in if-else

I'm a newbie so please be patient
What I want
I have a JPanel on which I have a JButton, a JLabel and a JTextArea. Upon pressing JButton, an image has to be printed inside the JLabel (and some text in JTextArea). This certain image (and text) is determined by if-else statements. Conditions of if-else are based on an integer variable R.
Basically its a survey like question-answer thing I'm trying to make. I use the R to record answers from user. When a user clicks a choice, the value of R gets updated.
Its working fine for the text, but not the image.
For text, I use a String variable yourphone. If the value of R in the end is eg 120, then yourphone gets updated to a string eg. Xperia Z.
I want a similar variable I can use for image, so that the picture of Xperia Z is displayed when the user clicks JButton.
Total value of R is used in if-else statements.
Structure
I initiate variables like this
int R=0;
String yourphone;
ImageIcon imageresult;
My JPanel which is meant to display result
final JPanel result = new JPanel();
result.setBackground(Color.BLACK);
getContentPane().add(result, "name_17130054294139");
result.setLayout(null);
final JTextArea txtrphoneresult = new JTextArea();
txtrphoneresult.setBackground(Color.BLACK);
txtrphoneresult.setForeground(Color.YELLOW);
txtrphoneresult.setFont(new Font("Tahoma", Font.PLAIN, 14));
txtrphoneresult.setBounds(448, 515, 469, 121);
result.add(txtrphoneresult);
JLabel resultlabel = new JLabel(imageresult);
resultlabel.setBounds(292, 122, 782, 346);
result.add(resultlabel);
JButton btnShowResult = new JButton("Show Result");
btnShowResult.setFont(new Font("Tahoma", Font.PLAIN, 10));
btnShowResult.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(R==1726)
{
yourphone = "Samsung Galaxy S4\r\nHTC One\r\nSony Xperia Z";
ImageIcon imageresult = new ImageIcon("galaxy_one_XperiaZ.jpg");
}
else if(R==5002)
{
yourphone = "Sony Xperia Z1\r\nSamsung Galaxy Note 3";
ImageIcon imageresult = new ImageIcon("Note3_sonyZ1.jpg");
}
else
{
yourphone = "No Results";
}
txtrphoneresult.setText(yourphone);
}
});
btnShowResult.setBounds(618, 48, 130, 32);
result.add(btnShowResult);
Problem
The image is not displayed at all.
If there is any other possible way to achieve this, please guide.
At first you create your imageresult inside if-else and it's not visible for all method. And you doesn't add your image to JLabel.
Make resultlabel as clas member or final variable.
Change your code in next way:
public void actionPerformed(ActionEvent e) {
ImageIcon imageresult = null;
if(R==1726)
{
yourphone = "Samsung Galaxy S4\r\nHTC One\r\nSony Xperia Z";
imageresult = new ImageIcon("galaxy_one_XperiaZ.jpg");
}
else if(R==5002)
{
yourphone = "Sony Xperia Z1\r\nSamsung Galaxy Note 3";
imageresult = new ImageIcon("Note3_sonyZ1.jpg");
}
else
{
yourphone = "No Results";
}
resultlabel.setIcon(imageresult)
txtrphoneresult.setText(yourphone);
}
Declare ImageIcon imageresult before the if statement and call
resultlabel.setIcon(imageresult)
after txtrphoneresult.setText(yourphone);
BTW: Don't use null layout/setBounds(). Read about layouts and choose proper one.
where do you set icon for your label.
you mising this line
resultlabel.setIcon(imageresult);
Make resultLabel final and change action performed:
public void actionPerformed(ActionEvent e)
{
ImageIcon imageresult = null;
if(R == 1726)
{
yourphone = "Samsung Galaxy S4\r\nHTC One\r\nSony Xperia Z";
imageresult = new ImageIcon("galaxy_one_XperiaZ.jpg");
}
else if(R == 5002)
{
yourphone = "Sony Xperia Z1\r\nSamsung Galaxy Note 3";
imageresult = new ImageIcon("Note3_sonyZ1.jpg");
}
else
{
yourphone = "No Results";
}
txtrphoneresult.setText(yourphone);
resultlabel.setIcon(imageresult);
}
The image is not displayed because you are not "giving" it to you JLabel. You can do it by using the setIcon() method.
You also have a problem with variable declaration. Unlike PHP and some other programming languages, in Java a variable only exists within the brackets (and sub-brackets) {} it has been declared in (despite there are some exceptions). For example :
public void myMethod() {
float b = 5f;
if (true) {
int a = 6;
if (true) {
// a exists, you can do whatever you like with it
// b exists, you can do whatever you like with it
}
// a exists you can do whatever you like with it
// b exists, you can do whatever you like with it
} // a is "destroyed"
// a doesn't exists
// b still exists
} // b is "destroyed"
// Neither a or b exists
You are in the exact same case with the declaration of your variable imageresult.

Categories