0
我試圖讓這個代碼垂直堆疊每個JLabel一個新消息(當添加消息被調用時)。這樣你就可以通過滾動查看每條消息。我對此很陌生,所以有什麼想法?現在,代碼只是用新消息替換textLabel。向ScrollPane添加多個JLabel
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JScrollPane;
import javax.swing.border.LineBorder;
import javax.swing.BoxLayout;
public class ChatWindow {
static JFrame frame;
static JScrollPane jScrollPane;
public ChatWindow() {
frame = new JFrame("Ring Chat");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Label");
label.setPreferredSize(new Dimension(100, 100));
jScrollPane = new JScrollPane(label);
JLabel textLabel = new JLabel("Welcome to Ring Chat!", SwingConstants.CENTER);
textLabel.setPreferredSize(new Dimension(300, 100));
jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jScrollPane.getViewport().add(textLabel);
frame.add(jScrollPane, BorderLayout.CENTER);
frame.setSize(400, 800);
frame.setVisible(true);
}
public static void addMessage(String msg) {
JLabel textLabel = new JLabel(msg, SwingConstants.CENTER);
textLabel.setPreferredSize(new Dimension(300, 100));
jScrollPane.getViewport().add(textLabel, null);
frame.add(jScrollPane, BorderLayout.CENTER);
}
public static void createWindow() {
ChatWindow stuff = new ChatWindow();
}
public static void updateWindow() {
frame.setVisible(true);
}
}