尝试运行程序时出现错误,因为找不到我的方法。 这是第一个错误代码:
Error: cannot find symbol
symbol: method getSelectedItem()
location: variable event of type java.awt.event.ActionEvent
这是第二个错误代码:
Error: cannot find symbol
symbol: method setBackground(java.awt.Color)
location: variable x of type java.lang.Object
以下是程序代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class PanelColor extends JFrame implements ActionListener{
// Declare all instance data (primitives and objects used)
private int WIDTH = 501;
private int HEIGHT = 501;
JPanel panelN;
JPanel panelS;
JPanel panelE;
JPanel panelW;
JPanel panelC;
Container con;
JComboBox box;
Dimension dPN;
Dimension dPS;
Dimension dPE;
Dimension dPW;
Dimension dPC;
//constructor
public PanelColor(){
super("Panel Color");
con = getContentPane();
con.setLayout(new BorderLayout());
setSize(WIDTH, HEIGHT);
panelN = new JPanel();
panelS = new JPanel();
panelE = new JPanel();
panelW = new JPanel();
panelC = new JPanel();
dPC = new Dimension(25,25);
dPS = new Dimension(200,200);
dPE = new Dimension(400,200);
dPW = new Dimension(400,200);
dPN = new Dimension(200,200);
panelC.setBackground(Color.RED);
panelN.setBackground(Color.YELLOW);
panelE.setBackground(Color.BLUE);
panelW.setBackground(Color.GREEN);
panelS.setBackground(Color.MAGENTA);
panelC.setPreferredSize(dPC);
panelN.setPreferredSize(dPN);
panelE.setPreferredSize(dPE);
panelW.setPreferredSize(dPW);
panelS.setPreferredSize(dPS);
box = new JComboBox();
box.addItem("Panel North");
box.addItem("Panel South");
box.addItem("Panel East");
box.addItem("Panel West");
box.addItem("Panel Center");
box.addActionListener(this);
con.add(panelC, BorderLayout.CENTER);
con.add(panelE, BorderLayout.EAST);
con.add(panelW, BorderLayout.WEST);
con.add(panelN, BorderLayout.NORTH);
con.add(panelS, BorderLayout.SOUTH);
con.add(box, BorderLayout.CENTER);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event){
Object source = event.getSource();
Random r = new Random();
int red = r.nextInt(255) + 1;
int green = r.nextInt(255) + 1;
int blue = r.nextInt(255) + 1;
Color c = new Color(red, green, blue);
String text = event.getSelectedItem();
Object x = event.getSelectedItem();
if(source == text){
x.setBackground(c);
}
}
public static void main(String[] args){
PanelColor object = new PanelColor();
}
}
我知道有很多关于找不到符号错误的帖子,但通过我所看到的所有帖子,他们都没有帮我解决这个问题。 我想知道为什么它会给我这些错误?以及如何修复它以便我知道以供将来参考。错误所在的区域列在本段下方。我希望如果他们遇到类似问题,也可以帮助其他人。
这些是有错误的区域:
String text = event.getSelectedItem();
Object x = event.getSelectedItem();
if(source == text){
x.setBackground(c);
}
答案 0 :(得分:3)
getSelectedItem
是JComboBox
而不是ActionEvent
JComboBox comboBox = (JComboBox) event.getSource();
...
String text = comboBox.getSelectedItem().toString();
答案 1 :(得分:1)
问题在于getSelectedItem();
类
ActionEvent
您需要将其更改为:
String text = (String) box.getSelectedItem();