我正在使用Java艺术和科学(使用Java SE 6u45)学习Java。尝试通过在JTextField中输入新的字体类型来更改文本的字体。但是问题是我无法在JTextField中输入任何文本。这个问题对于我使用过的其他Swing组件(例如JButton,JCheckBox)是常见的。但是在后面的组件中,即使视觉选择保持不变,我仍然可以看到选择的效果,这意味着即使单击后复选框仍保持选中状态,但是代码显示未选中框的结果。

但是对于JTextField,甚至没有显示效果。我也不能删除放在JTextField中的测试文本。尝试使用isEditable()grabFocus()isFocusable()。可能是Java错误吗?

/**
* Example 10.9
 *
 * This program prints the given text in the font inputted by the user in JTextField
 */
package ASJ_Examples;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JLabel;
import javax.swing.JTextField;

import acm.graphics.GLabel;
import acm.program.GraphicsProgram;

public class FontSampler extends GraphicsProgram implements ActionListener{
/**
 * Eclispe Generated
 */
private static final long serialVersionUID = -5734136235409079420L;
private static final String TEST_STRING = "This is a test";
private static final double LEFT_MARGIN = 3;
private static final int MAX_FONT_NAME = 10;

public void init(){
    addJFontLabel();
    addJFontTextField();
    lastY = 0;
    addGLabel();
}
/**
 * Adds a text field to enter the required font
 */
private void addJFontTextField() {
    String test = "new";
    fontField = new JTextField(test, MAX_FONT_NAME);    //added to see if Jtextfiled is responding
//      fontField.setEnabled(true);
//      fontField.setEditable(true);
    fontField.addActionListener(this);
    //added these to give focus to jtextfield but no effect
    fontField.isEditable();
    fontField.grabFocus();
    fontField.isFocusable();
    //add to window
    add(fontField, SOUTH);

}
/**
 * Adds JFontLAbel to denote the text input field
 */
private void addJFontLabel() {
    add(new JLabel("Font"), SOUTH);

}

/**
 * Adds the test label to canvas
 */
private void addGLabel() {
    lastLabel = new GLabel(TEST_STRING);
    add(lastLabel, 20, 20);

}

public void ActionPerformed(ActionEvent e){
    if(e.getSource() == fontField){
        GLabel label = new GLabel(TEST_STRING);
        label.setFont(lastLabel.getFont()); //to display the text even if the suer entered a non-allowed font
        label.setFont(fontField.getText()); //change the font to u4ser demanded font
        addGlabel(label);
        lastLabel = label;
    }
}
/**
 *adds a Glabel on the next line adjusting for heights
 * @param label
 */
private void addGlabel(GLabel label) {
    lastY += label.getHeight();
    lastY += lastLabel.getDescent() - label.getDescent();
    add(label, LEFT_MARGIN, lastY);

}
/**
 * JTextField to enter font
 */
private JTextField fontField;
/**
 * GLabel which is being worked on
 */
private GLabel lastLabel;
/**
 *
 */
private double lastY;
}

最佳答案

尝试使用fontField.requestFocus();代替fontField.grabFocus();
fontField.setEditable(true);而不是fontField.isEditable();
fontField.setFocusable(true);代替fontField.isFocusable();

btw fontField.setEditable(true);fontField.setFocusable(true);在默认情况下不是必需的,它们设置为true。

09-25 22:22