我試圖在每次單擊按鈕時創建標籤。標籤的位置應該改變。每次點擊時它應該高於另一個。但它不起作用。不創建任何標籤。我甚至不能從按鈕點擊偵聽器代碼創建單個JLabel。但是執行發生在最內層的'if'聲明中。動態地將JLabel添加到java中的UI上使用單個對象進行按鈕單擊
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);
}
}
你需要調用'重新驗證()'和'重繪()'在容器上你從中添加或刪除組件的任何時間。你的第一個嚴重錯誤是使用空佈局 - 避免這些因爲他們會回來困擾你,保證。 –
另外,我不得不懷疑,如果您最好使用JList。 –