我只是使用事件处理程序在Java中编写基本的GUI
程序。所有代码都正常工作,除了
string s = String.format("field 1 is %s", event.getActionCommand())
错误是
String类型的方法格式(String,object)不适用于参数format(String,String)`'。
所以event.getActionCommand())
肯定会返回一个字符串。但格式方法不接受。
我在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);
}
}
答案 0 :(得分:0)
您尚未在文本框中添加操作命令
溶液:
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);