有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么在我的工作JTextField中输入的文本不可见/不可选择?

我目前正在为初学者学习CS106A斯坦福Java课程。我被第7号讲义困住了,要求我创建一个简单的程序,在画布上绘制带有GLabel的grect,然后允许我拖动它们,再次移除它们或清除整个画布。为了添加这样一个框,我在南方添加了一个JTextField来输入框的名称,并添加/删除/清除按钮

在文本字段中输入一个名称以添加一个框是有效的。我的问题是,我在JTextField中键入的文本虽然已记录(因为它显示在新框中),但没有显示在JTextField本身中,因此我在点击“添加”并在框本身上阅读之前,看不到我键入的内容

这是我的密码:

    package handout07Interactors;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.util.HashMap;

import javax.swing.*;

import acm.graphics.*;
import acm.program.*;

@SuppressWarnings("serial")
public class Box_Diagram extends GraphicsProgram{

    public void init() {
        displayButtons();
        addActionListeners();

        //TODO make draggable

    }

    public void actionPerformed(ActionEvent e) {

        if (e.getActionCommand().equals("ADD")) {

            //create box
            GCompound canvasBox = createBox(tf.getText());

            //add box to HashMap
            map.put(tf.getText(), canvasBox);

            //add box to canvas
            int x = (int) (getWidth() - canvasBox.getWidth()) / 2;
            int y = (int) (getHeight() - canvasBox.getHeight()) / 2;
            add(canvasBox, x, y);

        } else if (e.getActionCommand().equals("REMOVE")) {

            //remove box with name
            if (map.get(tf.getText()) != null) {remove(map.get(tf.getText()));}; //if box exists, remove it 

        } else {

            for( String name: map.keySet() )
            {
                remove(map.get(name));
            }



        }

    }

    private GCompound createBox(String text) {

        // GCompound
        GCompound box = new GCompound();

        // create GRect
        GRect rect = new GRect(BOX_WIDTH, BOX_HEIGHT);
        box.add(rect);

        // add GLabel
        GLabel label = new GLabel(text);
        int x = (int) (rect.getWidth() - label.getWidth()) / 2;
        int y = 30; //manual entry, somehow calculation didn't work as it does for width
        box.add(label, x, y);

        map.put(text, box);

        return box;

    }

    private void displayButtons() {

        //label
        add(new JLabel("Name:"), SOUTH);

        //textfield
        tf = new JTextField(30);
        tf.addActionListener(this);
        add(tf, SOUTH);

        //ADD REMOVE CLEAR
        add(new JButton("ADD"), SOUTH);
        add(new JButton("REMOVE"), SOUTH);
        add(new JButton("CLEAR"), SOUTH);

    }

    //IVARS
    private JTextField tf;
    public static final int BOX_WIDTH = 100;
    public static final int BOX_HEIGHT = 50;
    public HashMap<String, GCompound> map = new HashMap<String, GCompound>();



}

共 (2) 个答案

  1. # 1 楼答案

    对不起,我的英语不是我的第一语言。 我在NameSurfer(编程作业)中遇到了这种“奇怪的行为”№6 CS106A)当我试图使用JTextField时,但在作业中№7节作业(与作者指出的相同)JTextField一切正常

    我注意到,如果我在北部/西部地区使用JTextField,JTextField效果很好,在南部/东部我使用TextField

  2. # 2 楼答案

    将5个不同的组件(标签、文本字段和3个按钮)添加到布局中的同一位置(边框布局的南段)

    您应该将这5个组件添加到另一个JPanel,例如使用FlowLayout,然后将此面板添加到主面板的南部