我目前正在为初学者开设 CS106A 斯坦福 Java 类(class)。我被困在第 7 号讲义上,要求我创建一个简单的程序,在 Canvas 上绘制带有 GLabel 的 GRects,然后允许我拖动它们、再次删除它们或清除整个 Canvas 。为了添加这样一个框,我在 SOUTH 添加了一个 JTextField 来输入框的名称,以及 ADD/REMOVE/CLEAR 按钮。
在文本字段中输入名称以添加框是可行的。我的问题是我在 JTextField 中输入的文本虽然已记录(因为它显示在新框上)但并未显示在 JTextField 本身中,因此在我点击“ADD”并阅读它之前我看不到我输入的内容在盒子本身上。
这是我的代码:
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>();
}
最佳答案
您要将 5 个不同的组件(标签、文本字段和 3 个按钮)添加到布局中的同一位置(边框布局的南部分)。
您应该将这 5 个组件添加到另一个 JPanel,例如使用 FlowLayout,然后将此面板添加到主面板的 SOUTH。
关于java - 为什么在我工作的 JTextField 中输入的文本不可见/不可选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13432675/