- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个奇怪的问题。我有一个类,其行为类似于下拉列表。
package test.view;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellRenderer;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;
public class AutoCompleteJComboBoxer extends PlainDocument {
private JComboBox comboBox;
private ComboBoxModel model;
private JTextComponent editor;
private boolean hidePopupOnFocusLoss;
public AutoCompleteJComboBoxer(JComboBox comboBox) {
this.comboBox = comboBox;
comboBox.setEditable(true);
model = comboBox.getModel();
editor = (JTextComponent)comboBox.getEditor().getEditorComponent();
editor.setDocument(this);
// Bug 5100422 on Java 1.5: Editable JComboBox won't hide popup when tabbing out
hidePopupOnFocusLoss = System.getProperty("java.version").startsWith("1.5");
// Highlight whole text when focus gets lost
editor.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
highlightCompletedText(0);
// Workaround for Bug 5100422 - Hide Popup on focus loss
if (hidePopupOnFocusLoss) AutoCompleteJComboBoxer.this.comboBox.setPopupVisible(false);
}
});
// Highlight whole text when user hits enter
editor.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
highlightCompletedText(0);
} else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
AutoCompleteJComboBoxer.this.comboBox.setSelectedIndex(0);
AutoCompleteJComboBoxer.this.editor.setText(AutoCompleteJComboBoxer.this.comboBox.getSelectedItem().toString());
highlightCompletedText(0);
}
}
});
// Handle initially selected object
Object selected = comboBox.getSelectedItem();
if (selected != null) editor.setText(selected.toString());
}
public AutoCompleteJComboBoxer(List<String> list){
comboBox = new JComboBox(list.toArray());
comboBox.setEditable(true);
comboBox.setMaximumRowCount(8);
comboBox.setSelectedIndex(-1);
model = comboBox.getModel();
editor = (JTextComponent)comboBox.getEditor().getEditorComponent();
editor.setDocument(this);
hidePopupOnFocusLoss = System.getProperty("java.version").startsWith("1.5");
editor.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
highlightCompletedText(0);
if (hidePopupOnFocusLoss) AutoCompleteJComboBoxer.this.comboBox.setPopupVisible(false);
}
});
editor.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
highlightCompletedText(0);
} else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
AutoCompleteJComboBoxer.this.comboBox.setSelectedIndex(0);
AutoCompleteJComboBoxer.this.editor.setText(AutoCompleteJComboBoxer.this.comboBox.getSelectedItem().toString());
highlightCompletedText(0);
}
}
});
// Handle initially selected object
Object selected = comboBox.getSelectedItem();
if (selected != null) editor.setText(selected.toString());
editor = (JTextComponent)comboBox.getEditor().getEditorComponent();
editor.setDocument(this);
editor.setBackground(Color.WHITE);
}
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
// construct the resulting string
String currentText = getText(0, getLength());
String beforeOffset = currentText.substring(0, offs);
String afterOffset = currentText.substring(offs, currentText.length());
String futureText = beforeOffset + str + afterOffset;
// lookup and select a matching item
Object item = lookupItem(futureText);
if (item != null) {
comboBox.setSelectedItem(item);
} else {
// keep old item selected if there is no match
item = comboBox.getSelectedItem();
// imitate no insert (later on offs will be incremented by str.length(): selection won't move forward)
offs = offs-str.length();
// provide feedback to the user that his input has been received but can not be accepted
comboBox.getToolkit().beep(); // when available use: UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
}
// remove all text and insert the completed string
super.remove(0, getLength());
super.insertString(0, item.toString(), a);
// if the user selects an item via mouse the the whole string will be inserted.
// highlight the entire text if this happens.
if (item.toString().equals(str) && offs==0) {
highlightCompletedText(0);
} else {
highlightCompletedText(offs+str.length());
// show popup when the user type
comboBox.setPopupVisible(true); // THERE PROGRAM CRASHES
}
}
private void highlightCompletedText(int start) {
editor.setCaretPosition(getLength());
editor.moveCaretPosition(start);
}
private Object lookupItem(String pattern) {
Object selectedItem = model.getSelectedItem();
// only search for a different item if the currently selected does not match
if (selectedItem != null && startsWithIgnoreCase(selectedItem.toString(), pattern)) {
return selectedItem;
} else {
// iterate over all items
for (int i=0, n=model.getSize(); i < n; i++) {
Object currentItem = model.getElementAt(i);
// current item starts with the pattern?
if (startsWithIgnoreCase(currentItem.toString(), pattern)) {
return currentItem;
}
}
}
// no item starts with the pattern => return null
return null;
}
// checks if str1 starts with str2 - ignores case
private boolean startsWithIgnoreCase(String str1, String str2) {
return str1.toUpperCase().startsWith(str2.toUpperCase());
}
public void resetColor(){
this.editor.setBackground(Color.WHITE);
}
public void setSuccessfulColor(){
this.editor.setBackground(Color.GREEN);
}
public void setUnsuccessfulColor(){
this.editor.setBackground(Color.RED);
}
public void setColor(Color color){
this.editor.setBackground(color);
}
public JTextComponent getEditor(){
return this.editor;
}
public JComboBox getComboBox(){
return this.comboBox;
}
public void setComboBox(JComboBox comboBox){
this.comboBox=comboBox;
}
private static void createAndShowGUI() {
JComboBox comboBox = new JComboBox(new Object[] { "clear","delete", "read", "read_all", "write","write_all","a","b","c"});
comboBox.setEditable(true);
comboBox.setMaximumRowCount(8);
comboBox.setSelectedIndex(-1);
JTextComponent editor = (JTextComponent)comboBox.getEditor().getEditorComponent();
editor.setDocument(new AutoCompleteJComboBoxer(comboBox));
editor.setBackground(Color.WHITE);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(comboBox);
frame.pack(); frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
我将该类(成员)中的 JComboBox 放入
DefaultCellEditor dceName=new DefaultCellEditor(cmbName);
并将其放入 JTable 中,但是当我单击时,出现错误
Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
at java.awt.Component.getLocationOnScreen_NoTreeLock(Unknown Source)
at java.awt.Component.getLocationOnScreen(Unknown Source)
at javax.swing.JPopupMenu.show(Unknown Source)
at javax.swing.plaf.basic.BasicComboPopup.show(Unknown Source)
at javax.swing.plaf.basic.BasicComboBoxUI.setPopupVisible(Unknown Source)
at javax.swing.JComboBox.setPopupVisible(Unknown Source)
at bacnet_debug_tool.view.AutoCompleteJComboBoxer.insertString(AutoCompleteJComboBoxer.java:142)
有人知道出了什么问题吗?我在 JTable 中有普通的 JComboBox 并且它可以工作。
最佳答案
没什么复杂的
1/取TableRenderDemo.java来 self 发布到您上一个主题的链接2/下载Auto complete ComboBox (有两个单独的类)并且两个类都保存到您的项目中
然后只需从 TableRenderDemo.java 修改/更改整个 void public void setUpSportColumn(JTable table, TableColumn sportColumn) {...}
并替换为以下代码
public void setUpSportColumn(JTable table, TableColumn sportColumn) {
//Set up the editor for the sport cells.
ArrayList<String> listSomeString = new ArrayList<String>();
listSomeString.add("Snowboarding");
listSomeString.add("Rowing");
listSomeString.add("Knitting");
listSomeString.add("Speed reading");
listSomeString.add("Pool");
listSomeString.add("None of the above");
Java2sAutoComboBox comboBox = new Java2sAutoComboBox(listSomeString);
comboBox.setDataList(listSomeString);
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
//Set up tool tips for the sport cells.
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
sportColumn.setCellRenderer(renderer);
}
编辑:也许更好的方法是用于 JTable 第二类 Java2sAutoTextField.class,在 TableCell 中看起来比 JComboBox 更好...
关于当我单击 JTable 问题中的 JComboBox 时,出现 java.awt.IllegalComponentStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6045523/
SQLite、Content provider 和 Shared Preference 之间的所有已知区别。 但我想知道什么时候需要根据情况使用 SQLite 或 Content Provider 或
警告:我正在使用一个我无法完全控制的后端,所以我正在努力解决 Backbone 中的一些注意事项,这些注意事项可能在其他地方更好地解决......不幸的是,我别无选择,只能在这里处理它们! 所以,我的
我一整天都在挣扎。我的预输入搜索表达式与远程 json 数据完美配合。但是当我尝试使用相同的 json 数据作为预取数据时,建议为空。点击第一个标志后,我收到预定义消息“无法找到任何内容...”,结果
我正在制作一个模拟 NHL 选秀彩票的程序,其中屏幕右侧应该有一个 JTextField,并且在左侧绘制弹跳的选秀球。我创建了一个名为 Ball 的类,它实现了 Runnable,并在我的主 Draf
这个问题已经有答案了: How can I calculate a time span in Java and format the output? (18 个回答) 已关闭 9 年前。 这是我的代码
我有一个 ASP.NET Web API 应用程序在我的本地 IIS 实例上运行。 Web 应用程序配置有 CORS。我调用的 Web API 方法类似于: [POST("/API/{foo}/{ba
我将用户输入的时间和日期作为: DatePicker dp = (DatePicker) findViewById(R.id.datePicker); TimePicker tp = (TimePic
放宽“邻居”的标准是否足够,或者是否有其他标准行动可以采取? 最佳答案 如果所有相邻解决方案都是 Tabu,则听起来您的 Tabu 列表的大小太长或您的释放策略太严格。一个好的 Tabu 列表长度是
我正在阅读来自 cppreference 的代码示例: #include #include #include #include template void print_queue(T& q)
我快疯了,我试图理解工具提示的行为,但没有成功。 1. 第一个问题是当我尝试通过插件(按钮 1)在点击事件中使用它时 -> 如果您转到 Fiddle,您会在“内容”内看到该函数' 每次点击都会调用该属
我在功能组件中有以下代码: const [ folder, setFolder ] = useState([]); const folderData = useContext(FolderContex
我在使用预签名网址和 AFNetworking 3.0 从 S3 获取图像时遇到问题。我可以使用 NSMutableURLRequest 和 NSURLSession 获取图像,但是当我使用 AFHT
我正在使用 Oracle ojdbc 12 和 Java 8 处理 Oracle UCP 管理器的问题。当 UCP 池启动失败时,我希望关闭它创建的连接。 当池初始化期间遇到 ORA-02391:超过
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 9 年前。 Improve
引用这个plunker: https://plnkr.co/edit/GWsbdDWVvBYNMqyxzlLY?p=preview 我在 styles.css 文件和 src/app.ts 文件中指定
为什么我的条形这么细?我尝试将宽度设置为 1,它们变得非常厚。我不知道还能尝试什么。默认厚度为 0.8,这是应该的样子吗? import matplotlib.pyplot as plt import
当我编写时,查询按预期执行: SELECT id, day2.count - day1.count AS diff FROM day1 NATURAL JOIN day2; 但我真正想要的是右连接。当
我有以下时间数据: 0 08/01/16 13:07:46,335437 1 18/02/16 08:40:40,565575 2 14/01/16 22:2
一些背景知识 -我的 NodeJS 服务器在端口 3001 上运行,我的 React 应用程序在端口 3000 上运行。我在 React 应用程序 package.json 中设置了一个代理来代理对端
我面临着一个愚蠢的问题。我试图在我的 Angular 应用程序中延迟加载我的图像,我已经尝试过这个2: 但是他们都设置了 src attr 而不是 data-src,我在这里遗漏了什么吗?保留 d
我是一名优秀的程序员,十分优秀!