【发布时间】:2019-08-18 11:46:09
【问题描述】:
我正在尝试将多个选项重命名为相同的值。如果已经有一个选项具有我试图将另一个重命名为的值,则不会发生任何事情。
这是我目前的代码:
package main.cache;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class ComboBox {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ComboBox window = new ComboBox();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ComboBox() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
String[] values = new String[] { "null", "null", "parameter3" };
final DefaultComboBoxModel<Object> models = new DefaultComboBoxModel<Object>(values);
JComboBox<Object> comboBox = new JComboBox<Object>(models);
comboBox.setBounds(130, 82, 168, 40);
frame.getContentPane().add(comboBox);
comboBox.setEditable(true);
comboBox.addActionListener(new ActionListener() {
private int localSelectedIndex = -1;
@Override
public void actionPerformed(ActionEvent e) {
int index = comboBox.getSelectedIndex();
if (index >= 0) {
localSelectedIndex = index;
} else if ("comboBoxEdited".equals(e.getActionCommand())) {
String newValue = (String) models.getSelectedItem();
// Change the value of the selected option
Object[] objects = new String[models.getSize()];
for (int i = 0; i < objects.length; i++) {
if (localSelectedIndex == i) {
objects[i] = newValue;
} else {
objects[i] = models.getElementAt(i);
}
}
// remove the elements and re add them
models.removeAllElements();
for (int i = 0; i < objects.length; i++) {
models.addElement(objects[i]);
}
// re-select the edited item
comboBox.setSelectedItem(newValue);
}
}
});
}
}
例如在这里,我有 3 个选项“null”、“null”、“parameter3”。假设我也想编辑参数 3 的第二个选项。目前,什么都没有发生。
【问题讨论】:
-
因为当你有一个相等的项目并且你去添加一个新的相等的项目时,JComboBox 组件会抛出事件“comboBoxEdited”并且 JCombo 框将索引更改为你的 actionListner
-
@vincenzopalazzo 那么如何解决这个问题?你能帮我解决吗?
-
我发布了一个原始解决方案
-
"(combo box) 我正在尝试将多个选项重命名为相同的值。"这对这个软件的倒霉用户有什么意义?