当前位置: 技术问答>java相关
菜鸟遇到菜问题,请教一下啦 :)
来源: 互联网 发布时间:2015-01-22
本文导语: import javax.swing.*; import java.awt.*; import java.awt.event.*; public class GUI { public static void main(String args[]) { JFrame f=new JFrame("Hello,JFram"); Container c=f.getContentPane(); //获得 f 的内容窗格,以容器变量 c 来引...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI
{
public static void main(String args[])
{
JFrame f=new JFrame("Hello,JFram");
Container c=f.getContentPane(); //获得 f 的内容窗格,以容器变量 c 来引用
c.setLayout(new BorderLayout());
JTextField msg=new JTextField("This is a TextField");
JButton but_ok=new JButton("OK");
JButton but_cancel=new JButton("Cancel");
c.add(but_ok,BorderLayout.NORTH);
c.add(but_cancel,BorderLayout.SOUTH);
c.add(msg,BorderLayout.CENTER);
f.pack();
f.setSize(200,100);
f.setResizable(false);
f.show();
but_cancel.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});//Event of Button Cancel
but_ok.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
msg.setText("Hello,Java"); ///// 这里出错 代码见后////////
}
});
//以下处理关闭事件
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
==============
GUI.java:40: Attempt to use a non-final variable msg from a different method. From enclosing blocks, only final local variables are available.
msg.setText("Hello,Java");
^
1 error
Exit code: 1
There were errors
import java.awt.*;
import java.awt.event.*;
public class GUI
{
public static void main(String args[])
{
JFrame f=new JFrame("Hello,JFram");
Container c=f.getContentPane(); //获得 f 的内容窗格,以容器变量 c 来引用
c.setLayout(new BorderLayout());
JTextField msg=new JTextField("This is a TextField");
JButton but_ok=new JButton("OK");
JButton but_cancel=new JButton("Cancel");
c.add(but_ok,BorderLayout.NORTH);
c.add(but_cancel,BorderLayout.SOUTH);
c.add(msg,BorderLayout.CENTER);
f.pack();
f.setSize(200,100);
f.setResizable(false);
f.show();
but_cancel.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});//Event of Button Cancel
but_ok.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
msg.setText("Hello,Java"); ///// 这里出错 代码见后////////
}
});
//以下处理关闭事件
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
==============
GUI.java:40: Attempt to use a non-final variable msg from a different method. From enclosing blocks, only final local variables are available.
msg.setText("Hello,Java");
^
1 error
Exit code: 1
There were errors
|
只要将JTextField msg=new JTextField("This is a TextField");一句改为:
final JTextField msg=new JTextField("This is a TextField");即可。
final JTextField msg=new JTextField("This is a TextField");即可。
|
关于变量作用域的问题。
关键 JTextField msg;
要放在调用方法可访问的地方。
msg = ...;
赋值语句的位置不是太重要。