从Java动作侦听器获取变量值?
作者:互联网
对这个新问题,很抱歉,我正在尝试使用JAVA和Swing为简单的应用程序创建GUI,但是我一直试图从外部获取在动作侦听器中生成的变量值.
public geRes()
{
setTitle("geRes");
setBounds(100, 100, 272, 308);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JButton btnNewButton = new JButton("igen");
btnNewButton.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.showOpenDialog(fc.getParent());
fc.getName();
}
});
btnNewButton.setToolTipText("Selec");
getContentPane().add(btnNewButton);
JButton btnCivos = new JButton("smbinar");
btnCivos.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
File dir = new File(); // I want to use fc.getName() as argument there
我想从另一个按钮内的第二个方法访问fc.getName().有什么建议么?提前致谢!
解决方法:
将JFileChooser设置为全局变量,以便可以从其他方法调用它.
在方法外初始化
JFileChooser fc;
您可以将其放在这里:
public geRes()
{
JFileChooser fc;
setTitle("geRes");
...
然后当您使用JFileChooser时,它将看起来像这样
fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
...
然后,您可以从其他方法立即调用JFileChooser.
JButton btnCivos = new JButton("smbinar");
btnCivos.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
//you can now get the value of fc.getName()
标签:variables,swing,parameter-passing,java 来源: https://codeday.me/bug/20191028/1952727.html