使用单个对象在单击按钮时动态地将JLabel添加到java中的UI

使用单个对象在单击按钮时动态地将JLabel添加到java中的UI,java,swing,Java,Swing,我试图在每次单击按钮时创建标签。标签的位置应该更改。每次单击时,它都应该位于彼此的上方。但它不起作用。不创建任何标签。我甚至不能从按钮单击侦听器代码创建一个JLabel。但是执行发生在最里面的“if”语句中 import javax.swing.*; import java.awt.*; import java.awt.event.*; class ChatClient{ static int y=600; static JLabel label=null; public static void

我试图在每次单击按钮时创建标签。标签的位置应该更改。每次单击时,它都应该位于彼此的上方。但它不起作用。不创建任何标签。我甚至不能从按钮单击侦听器代码创建一个JLabel。但是执行发生在最里面的“if”语句中

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class ChatClient{
static int y=600;
static JLabel label=null;
public static void main(String args[]) throws Exception{
  String defaultMessage = "Enter your message..";
  JFrame frame = new JFrame("FireFly");
  JTextField text = new JTextField(defaultMessage);
  //manipulate the default message in the text field
  text.addFocusListener(new FocusListener(){
    public void focusGained(FocusEvent ae){
      if(text.getText().equals(defaultMessage)){
          text.setText("");
      }
   }
    public void focusLost(FocusEvent ae){
      if(text.getText().isEmpty()){
        text.setText(defaultMessage);
      }
    }
  });
  text.setBounds(10,620,295,40);
  frame.add(text);
  JButton button = new JButton("SEND");
  button.setBounds(310,620,80,40);
  button.setForeground(Color.WHITE);
  button.setBackground(Color.decode("#11A458"));
  button.setFocusPainted(false);
  button.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){
      if(!text.getText().equals(defaultMessage))
      {
        if(!text.getText().isEmpty()){
          label=new JLabel(text.getText());
          label.setBounds(10,y,380,20);
          y=y-20;
          frame.add(label);
          }
      }
    }
  });

  frame.add(button);
  frame.setSize(400,700);
  frame.setLayout(null);
  frame.setVisible(true);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
}

在添加JLabel后调用容器上的revalidate和repaint将告诉GUI定位新组件并重新绘制容器,以便显示。e、 g

public void actionPerformed(ActionEvent ae) {
    if (!text.getText().equals(defaultMessage)) {
        if (!text.getText().isEmpty()) {
            label = new JLabel(text.getText());
            label.setBounds(10, y, 380, 20);
            y = y - 20;
            frame.add(label);
            frame.revalidate();
            frame.repaint();
        }
    }
}
在您的情况下,重新验证并不是绝对必要的,因为您没有使用布局管理器,但包含它仍然是一个好主意,因为您应该使用布局管理器,因为空布局是危险和脆弱的

不过最好使用JList

e、 g

导入java.awt.BorderLayout;
导入java.awt.event.ActionEvent;
导入javax.swing.*;
@抑制警告(“串行”)
公共类ChatClient2扩展了JPanel{
私有静态最终可见整数\行\计数=30;
private DefaultListModel listModel=新的DefaultListModel();
私有JList chatList=新JList(listModel);
私有发送操作发送操作=新发送操作(“发送”);
私有JTextField textField=新JTextField(20);
私有JButton sendButton=新JButton(sendAction);
公共聊天室2(){
chatList.setFocusable(false);
chatList.setVisibleRowCount(可见行数);
JScrollPane scrollPane=新的JScrollPane(聊天列表);
textField.setAction(sendAction);
JPanel bottomPanel=新的JPanel();
底部面板.setLayout(新的BoxLayout(底部面板,BoxLayout.LINE_轴));
添加(文本字段);
底部面板。添加(发送按钮);
setLayout(新的BorderLayout());
添加(滚动窗格);
添加(底部面板,边框布局。第_页结束);
}
私有类SendAction扩展了AbstractAction{
公共SendAction(字符串名称){
超级(姓名);
int助记符=(int)name.charAt(0);
putValue(助记符键,助记符);
}
@凌驾
已执行的公共无效操作(操作事件e){
String text=textField.getText();
添加(0,文本);
textField.selectAll();
textField.requestFocusInWindow();
}
}
私有静态void createAndShowGui(){
JFrame=newjframe(“聊天客户端2”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(新的ChatClient2());
frame.pack();
frame.setLocationRelativeTo(空);
frame.setVisible(true);
}
公共静态void main(字符串[]args){
调用器(()->createAndShowGui());
}
}

在容器中添加或删除组件时,需要在容器上调用
revalidate()
repaint()
。您的第一个大错误是使用空布局——避免使用这些布局,因为它们肯定会再次困扰您。此外,我确实想知道您是否最好使用JList。
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class ChatClient2 extends JPanel {
    private static final int VISIBLE_ROW_COUNT = 30;
    private DefaultListModel<String> listModel = new DefaultListModel<>();
    private JList<String> chatList = new JList<>(listModel);
    private SendAction sendAction = new SendAction("Send");
    private JTextField textField = new JTextField(20);
    private JButton sendButton = new JButton(sendAction);

    public ChatClient2() {
        chatList.setFocusable(false);
        chatList.setVisibleRowCount(VISIBLE_ROW_COUNT);
        JScrollPane scrollPane = new JScrollPane(chatList);

        textField.setAction(sendAction);
        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
        bottomPanel.add(textField);
        bottomPanel.add(sendButton);

        setLayout(new BorderLayout());
        add(scrollPane);
        add(bottomPanel, BorderLayout.PAGE_END);
    }

    private class SendAction extends AbstractAction {
        public SendAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String text = textField.getText();
            listModel.add(0, text);
            textField.selectAll();
            textField.requestFocusInWindow();
        }
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("Chat Client2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new ChatClient2());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}