我正在使用Java和Art of Science(使用Java SE 6u45)學習Java。試圖通過在JTextField中輸入新的字體類型來更改文本的字體。但問題是我無法在JTextField中輸入任何文本。這個問題對於我用過的JButton,JCheckBox等其他swing組件來說很常見。但在後面的組件中,我可以看到選擇的效果,即使視覺選擇保持不變,這意味着即使在單擊之後該複選框仍保持選中狀態,但代碼顯示未選中框的結果。無法在JTextfield中鍵入或刪除文本
但是在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;
}
的ACM API是純粹的AWT,但 'J' 組件是搖擺。您可能需要調用該功能以允許[AWT和Swing混合](http://www.oracle.com/technetwork/articles/java/mixing-components-433992.html)。 – 2013-05-06 05:18:58
我想是這樣,但這需要我時間來理解。嘗試了教程中的示例,指向效果組件層次結構,但沒有效果。我想稍後會回到這個問題。 – 2013-05-06 06:59:20
爲更好地幫助發佈[SSCCE](http://sscce.org/),簡短,可運行,可編譯,(拍攝到黑暗)BTW使用未裝飾的JDialog代替J/Window – mKorbel 2013-05-06 07:15:01