![](/img/trans.png)
[英]Java - num1 = event.getActionCommand() Doesn't work (Can't set the String as an Int)
[英]error: String.format is not accepting event.getActionCommand() [as object]
我只是在使用事件处理程序用Java编写基本的GUI
程序。 所有代码工作正常,除了在
string s = String.format("field 1 is %s", event.getActionCommand())
错误是
类型为String的方法format(String,object)不适用于参数format(String,String)`。
因此肯定event.getActionCommand())
返回一个字符串。 但是format方法不接受。
我使用互联网上著名的教程之一在eclipse(kepler)中编写此代码。 他的代码有效,但不是我的。 我是Java的初学者。 请帮助我找到这个愚蠢的错误。
这是我的代码。
package tushar_GUI;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
public class tush extends JFrame{
private JTextField textbox1;
private JTextField textbox2;
private JTextField textbox3 ;
private JPasswordField textbox_pass1;
public tush(){
super("TITLE");
setLayout(new FlowLayout());
textbox1 = new JTextField(10);
add(textbox1);
textbox2 = new JTextField("Enter Your Text Here", 30);
add(textbox2);
textbox3 = new JTextField("This is UNEDITABLE textbox", 30);
textbox3.setEditable(false);
add(textbox3);
textbox_pass1 = new JPasswordField("password");
add(textbox_pass1);
thehandler handler = new thehandler();
textbox1.addActionListener(handler);
textbox2.addActionListener(handler);
textbox3.addActionListener(handler);
textbox_pass1.addActionListener(handler);
}
private class thehandler implements ActionListener{
public void actionPerformed(ActionEvent event){
String string = "";
if(event.getSource() == textbox1)
string = String.format("field 1 is %s", event.getActionCommand());
else if(event.getSource() == textbox2)
string = String.format("field 2 is %s", event.getActionCommand());
else if(event.getSource() == textbox3)
string = String.format("field 3 is %s", event.getActionCommand());
else if(event.getSource() == textbox_pass1)
string = String.format("password field is %s", event.getActionCommand());
JOptionPane.showMessageDialog(null, string);
}
}
}
这是我的主要班级
package tushar_GUI;
import javax.swing.JFrame;
public class gui1 {
public static void main (String[] args){
tush tushObject = new tush();
tushObject.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tushObject.setSize(500, 500);
tushObject.setVisible(true);
}
}
您尚未在文本框中添加操作命令
解:
textbox1 = new JTextField(10);
textbox1.setActionCommand("textbox1 ");
add(textbox1);
textbox2 = new JTextField("Enter Your Text Here", 30);
textbox2.setActionCommand("textbox2 ");
add(textbox2);
textbox3 = new JTextField("This is UNEDITABLE textbox", 30);
textbox3.setActionCommand("textbox3 ");
textbox3.setEditable(false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.