禁用组件时,鼠标单击时输入提示消失

时间:2015-02-22 18:42:32

标签: java input focus jtextfield focuslistener

感谢Bart Kiers在其他人的帖子中提供的非常有用的帖子,我设法让我的输入提示正常工作。欢呼!不幸的是,我似乎无法得到一个小故障停止发生。

在正常操作过程中,HintTextFields被禁用并启用以允许或禁止编辑。输入提示应仅在字段为空且未选中时显示,但是当我左键单击这些框时,即使禁用并包含文本,文本也会消失,有利于提示。然后,当我点击其他内容时,我完全丢失了内容。

我已经添加了一个额外的位来if if then语句有关获得和失去焦点,以防止它在禁用组件时运行该代码,但问题仍然存在。它必须与JTextField类(或者可能是FocusListener?)进行一些小的交互。我也在该子句中尝试了getParent(),以防我误解'this'关键字,但这没有帮助。下面的课程:

class HintTextField extends JTextField implements FocusListener {

  private final String hint;
  private boolean showingHint;

  public HintTextField(final String hint) {
    super(hint);
    this.hint = hint;
    this.showingHint = true;
    super.addFocusListener(this);
  }

  @Override
  public void focusGained(FocusEvent e) {
    if(this.getText().isEmpty() && this.isEnabled()) {
      super.setText("");
      showingHint = false;
    }
  }
  @Override
  public void focusLost(FocusEvent e) {
    if(this.getText().isEmpty() && this.isEnabled()) {
      super.setText(hint);
      showingHint = true;
    }
  }

  @Override
  public String getText() {
    return showingHint ? "" : super.getText();
  }
}

原帖如果有人想要投入精彩的巴特基尔斯。 Java JTextField with input hint

此外,这是初始化。这开始是一个JDeveloper gui。

    startDateField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    startDateField.setToolTipText(notes);
    startDateField.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
    startDateField.setMaximumSize(new java.awt.Dimension(2, 16));
    startDateField.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            startDateFieldMouseClicked(evt);
        }
    });

private void startDateFieldMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_startDateFieldMouseClicked
if (SwingUtilities.isRightMouseButton(evt)) {
    editNote();
}
}


public void editNote() {
    int selected = -1;
    for (int a = 0; a < spinner.bitem.bldg.stallArray[1].length; a ++) {
        if (spinner.bitem.bldg.stallArray[1][a].equals(stallName)) {
            selected = a;
        }
    }
    String oldNote = notes;
    JTextField xField = new JTextField(oldNote);
    xField.setPreferredSize(new Dimension(200,30));

    JPanel myPanel = new JPanel();
    myPanel.add(new JLabel("Note:"));
    myPanel.add(xField);
    int result =
        JOptionPane.showConfirmDialog(this, myPanel, "Please enter note.",
                                      JOptionPane.OK_CANCEL_OPTION);

    if (result == JOptionPane.OK_OPTION) {
        String note = xField.getText();
        if (!note.equals(oldNote)) {
            notes = note;
            spinner.bitem.bldg.stallArray[9][selected] = notes;
            spinner.bitem.master.sendNoteDataToSQL(spinner.bitem.bldg.buildingName, spinner.bitem.bldg.stallArray[1][selected], notes);
            spinner.updateScreen();
        }
    }

}

0 个答案:

没有答案