我处于初步阶段,无论我尝试什么,似乎都无法让程序运行。我认为这个问题与我如何称呼关键字“this”有关,但我不能确定。
现在我让程序简单地打印出 JComboBox 中突出显示的内容,以保持简单,因为稍后可以使用“if”语句简单地完成比较方面。任何帮助表示赞赏。这是我的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main extends JPanel implements ActionListener {
JFrame frame;
JPanel panel;
JLabel label1;
JLabel label2;
public Main() {
super(new BorderLayout());
String[] colorStrings = { "", "Black", "White", "Red", "Blue", "Yellow",
"Green", "Orange", "Purple"};
JComboBox color1 = new JComboBox(colorStrings);
color1.setSelectedIndex(7);
color1.addActionListener(this);
JComboBox color2 = new JComboBox(colorStrings);
color2.setSelectedIndex(7);
color2.addActionListener(this);
add(label1, BorderLayout.PAGE_START);
add(color1, BorderLayout.PAGE_START);
add(label2, BorderLayout.PAGE_END);
add(color2, BorderLayout.PAGE_END);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
public void actionPerformed(ActionEvent e) {
JComboBox listen1 = (JComboBox)e.getSource();
String otherColor1 = (String)listen1.getSelectedItem();
System.out.println(otherColor1);
JComboBox listen2 = (JComboBox)e.getSource();
String otherColor2 = (String)listen2.getSelectedItem();
System.out.println(otherColor2);
}
private static void createAndShowGUI(JComboBox color1, JComboBox color2) {
JFrame frame = new JFrame("Does it match?");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new Main();
newContentPane.add(color1, color2);
newContentPane.setOpaque(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
出现的错误是:
运行:线程“AWT-EventQueue-0”中的异常 java.lang.RuntimeException:无法编译的源代码 - 错误的符号类型:java.awt.event.InvocationEvent.dispatch 处 Main$1.run(Main.java:53) 处的 createAndShowGUI( InvocationEvent.java:251) 在 java.awt.EventQueue.dispatchEventImpl(EventQueue.java:727) 在 java.awt.EventQueue.access$200(EventQueue.java:103) 在 java.awt.EventQueue$3.run(EventQueue.java :688) 在 java.awt.EventQueue$3.run(EventQueue.java:686) 在 java.security.AccessController.doPrivileged(Native Method) 在 java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) 在 java. awt.EventQueue.dispatchEvent(EventQueue.java:697) 在 java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242) 在 java.awt.EventDispatchThread。pumpEventsForFilter(EventDispatchThread.java:161) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java :138) 在 java.awt.EventDispatchThread.run(EventDispatchThread.java:91) 构建成功(总时间:3 秒)