这个程序只是为了自学Java。在编写代码时,我遇到了以下问题:在我的主类中实现的按钮使用侦听器时,我遇到错误(红色下划线)。
由于我是学习Java的新手,如果解决方案很明显,请原谅。我已经尝试过将main和actionPerfomed
方法都抽象,但这会导致更多的问题。在使用actionPerformed
方法之前,我还尝试了@Override
。
代码如下:
// Java program to create a blank text
// field of definite number of columns.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Main extends JFrame implements ActionListener {
// JTextField
static JTextField t;
// JFrame
static JFrame f;
// JButton
static JButton b;
// label to diaplay text
static JLabel l;
// default constructor
Main()
{
}
// main class
public static void main(String[] args)
{
// create a new frame to stor text field and button
f = new JFrame("textfield");
// create a label to display text
l = new JLabel("nothing entered");
// create a new button
b = new JButton("submit");
// create a object of the text class
Main te = new Main();
// addActionListener to button
b.addActionListener(te);
// create a object of JTextField with 16 columns
t = new JTextField(16);
// create a panel to add buttons and textfield
JPanel p = new JPanel();
// add buttons and textfield to panel
p.add(t);
p.add(b);
p.add(l);
l.setOpaque(true);
// add panel to frame
f.add(p);
// set the size of frame
f.setSize(300, 300);
p.setBackground(Color.cyan);
f.show();
}
// if the button is pressed
public void actionPerformed(java.awt.event.ActionEvent e, JPanel p)
{
String s = e.getActionCommand();
if (s.equals("submit")) {
// set the text of the label to the text of the field
if(t.getText().equals("hue")) {
p.setBackground(changeColor());
}
l.setText(t.getText());
// set the text of field to blank
t.setText(" ");
}
}
public Color changeColor() {
int r = (int)(Math.random())*256;
int g = (int)(Math.random())*256;
int b = (int)(Math.random())*256;
Color color = new Color(r,g,b);
return color;
}
}
发布于 2019-05-19 18:52:36
当一个类实现一个接口时,它必须使用接口中给出的相同参数来实现所需的函数。正如您在https://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html上看到的那样,ActionListener只实现了一个函数
void actionPerformed(ActionEvent e);
所以你必须在你的类中实现这个函数。但是您实现了一个不同的函数,该函数具有相同的名称但没有相同的参数:
void actionPerformed(java.awt.event.ActionEvent e, JPanel p)
https://stackoverflow.com/questions/56207003
复制相似问题