This is a java program with two buttons used to change an integer value and display it.
However in IntelliJIDEA the two lines with
increase.addActionListener(incListener());
decrease.addActionListener(decListener());
keep displaying errors ‘Method call expected’.
I am not sure what to do to fix this.
Any help will be greatly appreciated
Thanks
Note: the full code is attached below.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main extends JDialog {
public JPanel contentPane;
public JButton decrease;
public JButton increase;
public JLabel label;
public int number;
public Main() {
setContentPane(contentPane);
setModal(true);
increase = new JButton();
decrease = new JButton();
increase.addActionListener(incListener());
decrease.addActionListener(decListener());
number = 50;
label = new JLabel();
}
public class incListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
number++;
label.setText("" + number);
}
}
public class decListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
number--;
label.setText("" + number);
}
}
public static void main(String[] args) {
Main dialog = new Main();
dialog.pack();
dialog.setVisible(true);
System.exit(0);
}
}
asked May 7, 2013 at 11:45
1
incListener and declListener are classes, not methods.
Try
increase.addActionListener(new incListener());
btw, rename your classes names to make them start with an uppercase
answered May 7, 2013 at 11:47
Arnaud DenoyelleArnaud Denoyelle
30k16 gold badges92 silver badges149 bronze badges
It’s simple: use new incListener()
instead of incListener()
. The later is trying to call a method named incListener
, the former creates an object from the class incListener
, which is what we want.
answered May 7, 2013 at 11:48
PurkkaKoodariPurkkaKoodari
6,7136 gold badges37 silver badges58 bronze badges
incListener and decListener are a classes but not a methods, so you must call new to use them, try this:
increase.addActionListener(new incListener());
decrease.addActionListener(new decListener());
sorry for my bad english
answered May 7, 2013 at 11:53
substitute the lines with
increase.addActionListener( new incListener());
decrease.addActionListener( new decListener());
answered May 7, 2013 at 11:47
SimulantSimulant
19.2k8 gold badges63 silver badges98 bronze badges
Make these changes:
public Main() {
contentPane = new JPanel();
setContentPane(contentPane);
setModal(true);
increase = new JButton("inc");
decrease = new JButton("dec");
contentPane.add(increase);
contentPane.add(decrease);
increase.addActionListener(new incListener());
decrease.addActionListener(new decListener());
number = 50;
label = new JLabel(number+"");
contentPane.add(label);
}
answered May 7, 2013 at 11:55
hamidhamid
2,0334 gold badges22 silver badges42 bronze badges
It’s sad but I had to Google this same error… I was staring at a method that returned a class. I left off the new
operator.
return <class>(<parameters>)
vs
return new <class>(<parameters>)
answered May 20, 2019 at 17:56
CoryCory
1952 silver badges8 bronze badges
Whenever a string object is created using new operator a new object is created which is what your program is looking for.
The following link is useful in learning about the difference between a string and a new string.
What is the difference between «text» and new String(«text»)?
answered Jul 9, 2018 at 20:03
See more:
Hi..
I’m beginner Programmer,
when I want to make simple program, I got some Error.
string strDiurai = null; string Tbl1 = null; string [] arrBelasan = {"SEPULUH ", "SEBELAS ", "DUA BELAS ", "TIGA BELAS ", "EMPAT BELAS ", "LIMA BELAS ", "ENAM BELAS ", "TUJUH BELAS ", "DELAPAN BELAS ", "SEMBILAN BELAS " }; Tbl1 = arrBelasan(Convert.ToInt32(strDiurai)); <-- Error
The error say «method, delegate or event is expected».
what Should I do?
Sorry my english not good.
Here you need to use square braces for accessing array element instead of parentheses
Tbl1 = arrBelasan[Convert.ToInt32(strDiurai)];
Updated 18-Jun-13 19:46pm
Thanks you very much..
you are the Master C#
how to call class?
private void btnterbilang_Click(object sender, EventArgs e) { LHasil.Text = Terbilang(double.Parse(txtinput.Text)); <--ERROR }
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
This is a java program with two buttons used to change an integer value and display it.
However in IntelliJIDEA the two lines with
increase.addActionListener(incListener());
decrease.addActionListener(decListener());
keep displaying errors ‘Method call expected’.
I am not sure what to do to fix this.
Any help will be greatly appreciated
Thanks
Note: the full code is attached below.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main extends JDialog {
public JPanel contentPane;
public JButton decrease;
public JButton increase;
public JLabel label;
public int number;
public Main() {
setContentPane(contentPane);
setModal(true);
increase = new JButton();
decrease = new JButton();
increase.addActionListener(incListener());
decrease.addActionListener(decListener());
number = 50;
label = new JLabel();
}
public class incListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
number++;
label.setText("" + number);
}
}
public class decListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
number--;
label.setText("" + number);
}
}
public static void main(String[] args) {
Main dialog = new Main();
dialog.pack();
dialog.setVisible(true);
System.exit(0);
}
}
asked May 7, 2013 at 11:45
1
incListener and declListener are classes, not methods.
Try
increase.addActionListener(new incListener());
btw, rename your classes names to make them start with an uppercase
answered May 7, 2013 at 11:47
Arnaud DenoyelleArnaud Denoyelle
30k16 gold badges92 silver badges149 bronze badges
It’s simple: use new incListener()
instead of incListener()
. The later is trying to call a method named incListener
, the former creates an object from the class incListener
, which is what we want.
answered May 7, 2013 at 11:48
PurkkaKoodariPurkkaKoodari
6,7136 gold badges37 silver badges58 bronze badges
incListener and decListener are a classes but not a methods, so you must call new to use them, try this:
increase.addActionListener(new incListener());
decrease.addActionListener(new decListener());
sorry for my bad english
answered May 7, 2013 at 11:53
substitute the lines with
increase.addActionListener( new incListener());
decrease.addActionListener( new decListener());
answered May 7, 2013 at 11:47
SimulantSimulant
19.2k8 gold badges63 silver badges98 bronze badges
Make these changes:
public Main() {
contentPane = new JPanel();
setContentPane(contentPane);
setModal(true);
increase = new JButton("inc");
decrease = new JButton("dec");
contentPane.add(increase);
contentPane.add(decrease);
increase.addActionListener(new incListener());
decrease.addActionListener(new decListener());
number = 50;
label = new JLabel(number+"");
contentPane.add(label);
}
answered May 7, 2013 at 11:55
hamidhamid
2,0334 gold badges22 silver badges42 bronze badges
It’s sad but I had to Google this same error… I was staring at a method that returned a class. I left off the new
operator.
return <class>(<parameters>)
vs
return new <class>(<parameters>)
answered May 20, 2019 at 17:56
CoryCory
1952 silver badges8 bronze badges
Whenever a string object is created using new operator a new object is created which is what your program is looking for.
The following link is useful in learning about the difference between a string and a new string.
What is the difference between «text» and new String(«text»)?
answered Jul 9, 2018 at 20:03
Client clientAlias = null;
Note noteAlias = null;
Comment commentAlias = null;
query.JoinAlias(() => noteAlias.Client, () => clientAlias)
.JoinAlias(() => noteAlias.Comments, () => commentAlias);
query.Where(() => clientAlias.Id == clientId);
query.OrderBy(() => clientAlias.Id).Desc();
This line is in error. Any guesses why?
query.OrderBy(() => clientAlias.Id).Desc();
The error says
Method Delegate or Event is Expected
asked Jun 13, 2012 at 11:42
joncodojoncodo
2,3086 gold badges38 silver badges74 bronze badges
I was not using
using NHibernate;
using NHibernate.Criterion;
Funny that resharper did not suggest that.
answered Jun 13, 2012 at 13:07
joncodojoncodo
2,3086 gold badges38 silver badges74 bronze badges
2
This is a java program with two buttons used to change an integer value and display it.
However in IntelliJIDEA the two lines with
increase.addActionListener(incListener());
decrease.addActionListener(decListener());
keep displaying errors ‘Method call expected’.
I am not sure what to do to fix this.
Any help will be greatly appreciated
Thanks
Note: the full code is attached below.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main extends JDialog {
public JPanel contentPane;
public JButton decrease;
public JButton increase;
public JLabel label;
public int number;
public Main() {
setContentPane(contentPane);
setModal(true);
increase = new JButton();
decrease = new JButton();
increase.addActionListener(incListener());
decrease.addActionListener(decListener());
number = 50;
label = new JLabel();
}
public class incListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
number++;
label.setText("" + number);
}
}
public class decListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
number--;
label.setText("" + number);
}
}
public static void main(String[] args) {
Main dialog = new Main();
dialog.pack();
dialog.setVisible(true);
System.exit(0);
}
}
asked May 7, 2013 at 11:45
1
incListener and declListener are classes, not methods.
Try
increase.addActionListener(new incListener());
btw, rename your classes names to make them start with an uppercase
answered May 7, 2013 at 11:47
Arnaud DenoyelleArnaud Denoyelle
29.7k15 gold badges90 silver badges146 bronze badges
It’s simple: use new incListener()
instead of incListener()
. The later is trying to call a method named incListener
, the former creates an object from the class incListener
, which is what we want.
answered May 7, 2013 at 11:48
PurkkaKoodariPurkkaKoodari
6,6936 gold badges37 silver badges57 bronze badges
incListener and decListener are a classes but not a methods, so you must call new to use them, try this:
increase.addActionListener(new incListener());
decrease.addActionListener(new decListener());
sorry for my bad english
answered May 7, 2013 at 11:53
substitute the lines with
increase.addActionListener( new incListener());
decrease.addActionListener( new decListener());
answered May 7, 2013 at 11:47
SimulantSimulant
19.1k8 gold badges62 silver badges98 bronze badges
Make these changes:
public Main() {
contentPane = new JPanel();
setContentPane(contentPane);
setModal(true);
increase = new JButton("inc");
decrease = new JButton("dec");
contentPane.add(increase);
contentPane.add(decrease);
increase.addActionListener(new incListener());
decrease.addActionListener(new decListener());
number = 50;
label = new JLabel(number+"");
contentPane.add(label);
}
answered May 7, 2013 at 11:55
hamidhamid
2,0154 gold badges22 silver badges42 bronze badges
It’s sad but I had to Google this same error… I was staring at a method that returned a class. I left off the new
operator.
return <class>(<parameters>)
vs
return new <class>(<parameters>)
answered May 20, 2019 at 17:56
CoryCory
1962 silver badges8 bronze badges
Whenever a string object is created using new operator a new object is created which is what your program is looking for.
The following link is useful in learning about the difference between a string and a new string.
What is the difference between «text» and new String(«text»)?
answered Jul 9, 2018 at 20:03
Issue
I am completely new to Android Studio and just learned Object-oriented programming. My project requires me to build something on open-source code. I added a new menu item to a menu and want to start another activity once the user clicks the menu item with id: plot. I followed a recipe on the internet but got an error with it. It said ‘method call expected’ which means Terminal Fragment may be a method. I got confused, as I thought it is a class(an activity). Could anyone give me instructions to start an activity (turn to the next page with a different activity) in this case? What will be the simplest way to do this? Much Appreciated.
I added this in onOptionsItemSelected(MenuItem item).
if (id == R.id.plot){
Intent intent = new Intent(TerminalFragment.this, MainActivity2.class);
startActivity(intent);
}
TerminalFragment.java (entire code)
package de.kai_morich.simple_bluetooth_le_terminal;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class TerminalFragment extends Fragment implements ServiceConnection, SerialListener {
private MenuItem menuItem;
private enum Connected { False, Pending, True }
private String deviceAddress;
private SerialService service;
private TextView receiveText;
private TextView sendText;
private TextUtil.HexWatcher hexWatcher;
private Connected connected = Connected.False;
private boolean initialStart = true;
private boolean hexEnabled = false;
private boolean pendingNewline = false;
private String newline = TextUtil.newline_crlf;
/*
* Lifecycle
*/
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
//Register with activity
// You must inform the system that your app bar fragment is participating in the population of the options menu.
// tells the system that your fragment would like to receive menu-related callbacks.
setRetainInstance(true);
deviceAddress = getArguments().getString("device");
}
@Override
public void onDestroy() {
if (connected != Connected.False)
disconnect();
getActivity().stopService(new Intent(getActivity(), SerialService.class));
super.onDestroy();
}
@Override
public void onStart() {
super.onStart();
if(service != null)
service.attach(this);
else
getActivity().startService(new Intent(getActivity(), SerialService.class)); // prevents service destroy on unbind from recreated activity caused by orientation change
}
@Override
public void onStop() {
if(service != null && !getActivity().isChangingConfigurations())
service.detach();
super.onStop();
}
@SuppressWarnings("deprecation") // onAttach(context) was added with API 23. onAttach(activity) works for all API versions
@Override
public void onAttach(@NonNull Activity activity) {
super.onAttach(activity);
getActivity().bindService(new Intent(getActivity(), SerialService.class), this, Context.BIND_AUTO_CREATE);
}
@Override
public void onDetach() {
try { getActivity().unbindService(this); } catch(Exception ignored) {}
super.onDetach();
}
@Override
public void onResume() {
super.onResume();
if(initialStart && service != null) {
initialStart = false;
getActivity().runOnUiThread(this::connect);
}
}
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
service = ((SerialService.SerialBinder) binder).getService();
service.attach(this);
if(initialStart && isResumed()) {
initialStart = false;
getActivity().runOnUiThread(this::connect);
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
service = null;
}
/*
* UI
*/
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_terminal, container, false);
receiveText = view.findViewById(R.id.receive_text); // TextView performance decreases with number of spans
receiveText.setTextColor(getResources().getColor(R.color.colorRecieveText)); // set as default color to reduce number of spans
receiveText.setMovementMethod(ScrollingMovementMethod.getInstance());
sendText = view.findViewById(R.id.send_text);
hexWatcher = new TextUtil.HexWatcher(sendText);
hexWatcher.enable(hexEnabled);
sendText.addTextChangedListener(hexWatcher);
sendText.setHint(hexEnabled ? "HEX mode" : "");
View sendBtn = view.findViewById(R.id.send_btn);
sendBtn.setOnClickListener(v -> send(sendText.getText().toString()));
return view;
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_terminal, menu);
menu.findItem(R.id.hex).setChecked(hexEnabled);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.clear) {
receiveText.setText("");
return true;
} if (id == R.id.plot){
Intent intent = new Intent(TerminalFragment.this, MainActivity2.class);
startActivity(intent);
}else if (id == R.id.newline) {
String[] newlineNames = getResources().getStringArray(R.array.newline_names);
String[] newlineValues = getResources().getStringArray(R.array.newline_values);
int pos = java.util.Arrays.asList(newlineValues).indexOf(newline);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Newline");
builder.setSingleChoiceItems(newlineNames, pos, (dialog, item1) -> {
newline = newlineValues[item1];
dialog.dismiss();
});
builder.create().show();
return true;
} else if (id == R.id.hex) {
hexEnabled = !hexEnabled;
sendText.setText("");
hexWatcher.enable(hexEnabled);
sendText.setHint(hexEnabled ? "HEX mode" : "");
item.setChecked(hexEnabled);
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
/*
* Serial + UI
*/
private void connect() {
try {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
status("connecting...");
connected = Connected.Pending;
SerialSocket socket = new SerialSocket(getActivity().getApplicationContext(), device);
service.connect(socket);
} catch (Exception e) {
onSerialConnectError(e);
}
}
private void disconnect() {
connected = Connected.False;
service.disconnect();
}
private void send(String str) {
if(connected != Connected.True) {
Toast.makeText(getActivity(), "not connected", Toast.LENGTH_SHORT).show();
return;
}
try {
String msg;
byte[] data;
if(hexEnabled) {
StringBuilder sb = new StringBuilder();
TextUtil.toHexString(sb, TextUtil.fromHexString(str));
TextUtil.toHexString(sb, newline.getBytes());
msg = sb.toString();
data = TextUtil.fromHexString(msg);
} else {
msg = str;
data = (str + newline).getBytes();
}
SpannableStringBuilder spn = new SpannableStringBuilder(msg + 'n');
spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorSendText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
receiveText.append(spn);
service.write(data);
} catch (Exception e) {
onSerialIoError(e);
}
}
private void receive(byte[] data) {
if(hexEnabled) {
receiveText.append("Hello" + TextUtil.toHexString(data) + 'n');
} else {
String msg = new String(data);
if(newline.equals(TextUtil.newline_crlf) && msg.length() > 0) {
// don't show CR as ^M if directly before LF
msg = msg.replace(TextUtil.newline_crlf, TextUtil.newline_lf);
// special handling if CR and LF come in separate fragments
if (pendingNewline && msg.charAt(0) == 'n') {
Editable edt = receiveText.getEditableText();
if (edt != null && edt.length() > 1)
edt.replace(edt.length() - 2, edt.length(), "");
}
pendingNewline = msg.charAt(msg.length() - 1) == 'r';
}
receiveText.append(TextUtil.toCaretString(msg, newline.length() != 0)); //print out data
}
}
private void status(String str) {
SpannableStringBuilder spn = new SpannableStringBuilder(str + 'n');
spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorStatusText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
receiveText.append(spn);
}
/*
* SerialListener
*/
@Override
public void onSerialConnect() {
status("connected");
connected = Connected.True;
}
@Override
public void onSerialConnectError(Exception e) {
status("connection failed: " + e.getMessage());
disconnect();
}
@Override
public void onSerialRead(byte[] data) {
receive(data);
}
@Override
public void onSerialIoError(Exception e) {
status("connection lost: " + e.getMessage());
disconnect();
}
}
menu_terminal.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/plot"
android:title="PLOTDATA"
app:showAsAction="always" />
<item
android:id="@+id/clear"
android:icon="@drawable/ic_delete_white_24dp"
android:title="Clear"
app:showAsAction="always" />
<item
android:id="@+id/newline"
android:title="Newline"
app:showAsAction="never" />
<item
android:id="@+id/hex"
android:title="HEX Mode"
android:checkable="true"
app:showAsAction="never" />
</menu>
Solution
Here, TerminalFragment
is a fragment, not an activity. And so, instead of using TerminalFragment.this
in new Intent()
, you should use getActivity()
.
So, the final code would look something like this:
Intent intent = new Intent(getActivity(), MainActivity2.class);
startActivity(intent);
You can also check this: Intent from Fragment to Activity
Answered By – ganjaam
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0
This is a java program with two buttons used to change an integer value and display it.
However in IntelliJIDEA the two lines with
increase.addActionListener(incListener());
decrease.addActionListener(decListener());
keep displaying errors ‘Method call expected’.
I am not sure what to do to fix this.
Any help will be greatly appreciated
Thanks
Note: the full code is attached below.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main extends JDialog {
public JPanel contentPane;
public JButton decrease;
public JButton increase;
public JLabel label;
public int number;
public Main() {
setContentPane(contentPane);
setModal(true);
increase = new JButton();
decrease = new JButton();
increase.addActionListener(incListener());
decrease.addActionListener(decListener());
number = 50;
label = new JLabel();
}
public class incListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
number++;
label.setText("" + number);
}
}
public class decListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
number--;
label.setText("" + number);
}
}
public static void main(String[] args) {
Main dialog = new Main();
dialog.pack();
dialog.setVisible(true);
System.exit(0);
}
}
incListener and declListener are classes, not methods.
Try
increase.addActionListener(new incListener());
btw, rename your classes names to make them start with an uppercase
It’s simple: use new incListener()
instead of incListener()
. The later is trying to call a method named incListener
, the former creates an object from the class incListener
, which is what we want.
incListener and decListener are a classes but not a methods, so you must call new to use them, try this:
increase.addActionListener(new incListener());
decrease.addActionListener(new decListener());
sorry for my bad english