我试图让这段代码用新消息垂直堆叠每个JLabel(调用添加消息时)。这样,您可以通过滚动查看每条消息。我是新手,所以有什么想法吗?现在,代码只是将textLabel替换为新消息。
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);
}
}
答案 0 :(得分:0)
只需添加JPanel
static JScrollPane jScrollPane;
static JPanel panel;
在JLabel
panel = new JPanel();
panel.setSize(500, 500);
panel.setLayout(new GridLayout(20, 1));
jScrollPane = new JScrollPane(panel);
panel.add(label);
JLabel textLabel = new JLabel("Welcome to Ring Chat!", SwingConstants.CENTER);
textLabel.setPreferredSize(new Dimension(300, 100));
panel.add(textLabel);
并在addMessage(String msg)
方法中将新的JLabel
添加到JPanel
,就像这样。
public static void addMessage(String msg) {
JLabel textLabel = new JLabel(msg, SwingConstants.CENTER);
textLabel.setPreferredSize(new Dimension(300, 100));
panel.add(textLabel);
frame.add(jScrollPane, BorderLayout.CENTER);
}
休息是一样的..
而不是添加JLabel
使用JPanel
,并在运行时在JPanel
添加标签。它会解决你的问题..