【发布时间】:2015-11-24 22:47:26
【问题描述】:
当JTextField 位于JScrollPanel 中时,如果面板已滚动,则只要JComboBox 的下拉列表位于JTextField 上方,文本字段就会通过下拉列表显示。
这仅在内容滚动后发生(而不是在应用程序启动时)。
主要问题是我们如何解决这个问题? 如果回答,则加分:
- 不是黑客
- 首先解释为什么会发生这种情况
我尝试过的事情:
- 将下拉菜单移到滚动窗格之外(无变化)
- 为我在滚动条上找到的所有容器添加重绘(无变化)
- 滚动窗格内容的不同布局管理器(无变化)
代码示例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextFieldShowsThrough{
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createScrollDemo());
frame.pack();
// For demonstration purposes
frame.setSize(frame.getWidth() + 100, frame.getHeight() - 100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static JScrollPane createScrollDemo(){
final Box optionsPanel = Box.createVerticalBox();
optionsPanel.add(createDropDown());
optionsPanel.add(createTextField("Option1"));
optionsPanel.add(createTextField("Option2"));
optionsPanel.add(createTextField("Option3"));
optionsPanel.add(createTextField("Option4"));
optionsPanel.add(createTextField("Option5"));
optionsPanel.add(Box.createVerticalGlue());
JScrollPane result = new JScrollPane(optionsPanel);
// Made attempts to fix here, but to no avail
/*result.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
result.repaint();
}
});*/
return result;
}
public static Box createDropDown(){
Box b = Box.createVerticalBox();
b.setAlignmentX(JLabel.LEFT_ALIGNMENT);
b.add(new JLabel("Language"));
JComboBox combo = new JComboBox(new String[]{"en", "fr", "es"});
combo.setMaximumSize(new Dimension(500, 25));
b.add(combo);
return b;
}
public static Box createTextField(String label){
Box mainBox = Box.createVerticalBox();
mainBox.setOpaque(true);
mainBox.setBackground(new Color((int)(Math.random() * 0x1000000))); // because fun
JLabel jLabel = new JLabel(label);
jLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
mainBox.add(jLabel);
Box secondaryBox = Box.createHorizontalBox();
secondaryBox.setAlignmentX(JLabel.LEFT_ALIGNMENT);
TextField tf = new TextField();
tf.setMaximumSize(new Dimension(500, 25));
secondaryBox.add(tf);
mainBox.add(secondaryBox);
return mainBox;
}
}
【问题讨论】: