例程中的一部分,运行错误 :Cannot make a static reference to the non-static method

alca_bigV 2017-08-03 07:55:52
如上.
MyComm类中,简单定义 了一个列举所有串口的方法.
package my_swt_prj;
import java.io.*;
import java.util.*;
/*commport pkg*/
import javax.comm.CommPort;/*支持串口,并口 的管理*/
import javax.comm.CommPortIdentifier;/*串口的设置和管理*/
import javax.comm.SerialPort;/*串口的读 写*/
//public class MyComm implements Runnable, SerialPortEventListener {
public class MyComm{


public void listPortChoices(){

CommPortIdentifier portId;
Enumeration en = CommPortIdentifier.getPortIdentifiers();
// iterate through the ports.
while (en.hasMoreElements()) {
portId = (CommPortIdentifier) en.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
System.out.println(portId.getName());
}
}
//portChoice.select(parameters.getPortName());/*select's menu,focus at portname's */
}
}

在Myframe中,声明 一个对象.
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Properties;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import java.awt.Color;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
//inport comm pkg
import java.io.*;
import java.util.*;


public class MyJFrame extends JFrame {

private JPanel contentPane;

MyComm com1=new MyComm();


然后在下面的鼠标事件中调用 .
btnNewButton_4.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// btnNewButton.setText("Batton D was clicked");
textArea.append("button D was clicked by systom out\n");

//MyComm.
MyComm.listPortChoices();
}
});
不点鼠标,其他正常,点了button4,出现上面的报错,,,不能在static的方法里引用非static的方法或参数?
把方法改成.
public class MyComm{
public CommPortIdentifier portId;

public void listPortChoices(){


Enumeration en = CommPortIdentifier.getPortIdentifiers();
// iterate through the ports.
while (en.hasMoreElements()) {
portId = (CommPortIdentifier) en.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
System.out.println(portId.getName());
}
}
//portChoice.select(parameters.getPortName());/*select's menu,focus at portname's */
}
}

不行,指点该 哪里修改?
...全文
250 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
alca_bigV 2017-08-05
  • 打赏
  • 举报
回复
引用 2 楼 q54244125 的回复:
建议了解下java基础方面的。 静态变量,不能在非静态方法中使用。
清楚了,全部改成static的...3q
天涯若风 2017-08-04
  • 打赏
  • 举报
回复
建议了解下java基础方面的。 静态变量,不能在非静态方法中使用。
解开者 2017-08-04
  • 打赏
  • 举报
回复
不能在静态上下文中使用非静态关联 可以把上下文改为静态的,或者把被调用方法改成非静态的
alca_bigV 2017-08-04
  • 打赏
  • 举报
回复
引用 2 楼 q54244125 的回复:
建议了解下java基础方面的。 静态变量,不能在非静态方法中使用。
大神能指出 我哪个变量引用错误了吗?例子我几乎没改动,只是把类名改成我自己的..我能看到的变量,也都 改了试过......简单的十行不到的程序 ,出错,郁闷 哎.
alca_bigV 2017-08-04
  • 打赏
  • 举报
回复
引用 1 楼 windowsoahil 的回复:
不能在静态上下文中使用非静态关联 可以把上下文改为静态的,或者把被调用方法改成非静态的
大神看下,我把listPortChoices改成public了以后,效果一样...

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧