我正在尝试使用Java Swing制作聊天应用程序,但是在聊天气泡方面遇到了问题。我成功地实现了气泡效果,但似乎无法正确放置它们。以下是我的代码:
package messagebubble;
import java.awt.BorderLayout;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import messagebubble.RoundedBorder;
public class Main {
public static void main(String[] args) {
JFrame window = new JFrame();
JPanel chat = new JPanel();
chat.setLayout(new BoxLayout(chat, BoxLayout.PAGE_AXIS));
JPanel painel = new JPanel(new BorderLayout());
JPanel painel2 = new JPanel(new BorderLayout());
JTextArea msg = new JTextArea();
msg.setLineWrap(true);
msg.setWrapStyleWord(true);
msg.setText("ola tudo bem meus caros amigos, como estão? há muito que não vos via por estas bandas haha lol");
msg.setBorder(new RoundedBorder());
msg.setColumns(msg.getLineCount());
JTextArea msg2 = new JTextArea();
msg2.setLineWrap(true);
msg2.setWrapStyleWord(true);
msg2.setText("ola tudo bem");
msg2.setBorder(new RoundedBorder());
painel.add(msg,BorderLayout.NORTH);
chat.add(painel);
painel2.add(msg2,BorderLayout.NORTH);
chat.add(painel2);
window.add(chat);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 500);
window.setVisible(true);
}
}
这里是圆角边框
package GUI;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.geom.Area;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import javax.swing.border.AbstractBorder;
public class RoundedBorder extends AbstractBorder {
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width,
int height) {
Graphics2D graph = (Graphics2D) g.create();
RoundRectangle2D round = new RoundRectangle2D.Float(x, y, width - 1,
height - 1, 30, 30);
Container parent = c.getParent();
if (parent != null) {
graph.setColor(parent.getBackground());
Area canto = new Area(new Rectangle2D.Float(x,y,width,height));
canto.subtract(new Area(round));
graph.fill(canto);
}
graph.setColor(Color.GRAY);
graph.draw(round);
graph.dispose();
}
@Override
public Insets getBorderInsets(Component c) {
return new Insets(5, 10, 5, 10);
}
@Override
public Insets getBorderInsets(Component c, Insets insets) {
insets.left = 10;
insets.right = insets.left;
insets.top = 5;
insets.bottom = insets.top;
return insets;
}
输出结果看起来像这样Output。我无法去除消息之间的空白空格或底部JTextArea中的空白空格。
我还尝试将面板的最大大小设置为其首选大小,它看起来像这样Output2,太窄了。
有什么想法可以解决这个问题吗?我想要实现的是这样的东西ideal