我是新来的,但我正在寻找,现在是时候问问你们的伙伴了。我在java中有一个简单的应用程序,其中包括JComboBox的itemListener。我不知道为什么,但是,它不听,但是当我将 JComboBox 放在层次结构的上层时,它可以工作,并且 itemListener 工作正常。知道为什么它在较低级别不起作用吗?
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class Notatnik extends JFrame {
JMenuBar menu;
JMenu tools, fontColor;
JComboBox<String> colors;
public Notatnik() {
this.setSize(500, 400);
menu = new JMenuBar();
tools = new JMenu("tools");
fontColor = new JMenu("Font color");
colors = new JComboBox<String>();
colors.addItem("red");
colors.addItem("green");
colors.addItem("blue");
colors.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
System.out.println(e.getItem().toString());
}
});
fontColor.add(colors);
tools.add(fontColor);
menu.add(tools);
this.setJMenuBar(menu);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
无法向JMenu
组件添加JComboBox
(不破坏侦听器(。因此,我稍微改变了实现:
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.*;
public class Stackoverflow {
// Initialize the color to your desired choice.
private static Color color = Color.RED;
public static void main(final String[] arguments) {
final JFrame frame = new JFrame("Stackoverflow | Answer");
EventQueue.invokeLater(() -> {
final JMenuBar menuBar = new JMenuBar();
final JMenu menu = new JMenu("Edit");
// This is just for debugging.
final JLabel currentColor = new JLabel(color.getRed() + "r " + color.getGreen() + "g " + color.getBlue() + "b");
final JMenuItem item01 = new JMenuItem("Red");
final JMenuItem item02 = new JMenuItem("Green");
final JMenuItem item03 = new JMenuItem("Blue");
item01.addActionListener((event -> {
Stackoverflow.setColor(currentColor, Color.RED);
}));
item02.addActionListener((event -> {
Stackoverflow.setColor(currentColor, Color.GREEN);
}));
item03.addActionListener((event -> {
Stackoverflow.setColor(currentColor, Color.BLUE);
}));
final JMenu parent = new JMenu("Color");
parent.add(currentColor);
parent.add(item01);
parent.add(item02);
parent.add(item03);
menu.add(parent);
menuBar.add(menu);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(500, 400);
frame.setLocationRelativeTo(null);
frame.setJMenuBar(menuBar);
frame.setVisible(true);
});
}
public static void setColor(final JLabel label, final Color color) {
// Update the text of the specified JLabel. Edit this part to change the actual font color.
label.setText(color.getRed() + "r " + color.getGreen() + "g " + color.getBlue() + "b");
Stackoverflow.color = color;
}
}
我知道代码不整洁或高效,但它工作得很好。在我忘记它之前,您应该绝对访问有关何时继承类的文章。