簡體   English   中英

錯誤:String.format不接受event.getActionCommand()[作為對象]

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM