在文本字段中添加名称时,它是垂直的,但是当我从队列中删除用户时,它会水平更改。其次,我在改变用户的位置方面遇到了问题。当用户从队列中删除时,我希望下面的用户采取他们的位置,例如哈利,2。汤姆,3。格雷格(删除按钮)。 汤姆,2。格雷格。
答案 0 :(得分:0)
根据我对您的代码的理解,您没有采用实际索引,您已将“count”作为参考变量并显示在添加和删除中。检查以下代码以获得预期结果:
private static Queue<String> myQ = new LinkedList<String>();
private static JTextField jTextField1 = null;
private static JTextArea jTextArea1 = null;
private static void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String name = jTextField1.getText(); // get text from text field
jTextArea1.setText(""); // remove all text in text area
myQ.add(name);// add text field data
int count = 0;
for (String str : myQ) { // iterate
jTextArea1.append(count + " " + str + "\n");// append into text area
count++;
}
System.out.print(myQ);
}
private static void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
myQ.remove();
System.out.print(myQ);
jTextArea1.setText("");
Iterator it = myQ.iterator();
int count = 0;
while (it.hasNext()) {
Object e = it.next();
jTextArea1.append(count + " " + e + "\n");
count++;
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Button Example");
jTextField1 = new JTextField();
jTextField1.setBounds(50, 50, 150, 20);
JButton addUsersButton = new JButton("Add User");
addUsersButton.setBounds(50, 100, 95, 30);
JButton removeUsersButton = new JButton("Remove User");
removeUsersButton.setBounds(150, 100, 95, 30);
jTextArea1 = new JTextArea();
jTextArea1.setBounds(60, 150, 200, 200);
addUsersButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jButton1ActionPerformed(e);
}
});
removeUsersButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jButton2ActionPerformed(e);
}
});
f.add(addUsersButton);
f.add(removeUsersButton);
f.add(jTextField1);
f.add(jTextArea1);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}