이미지 설명을 입력합니다. 일반적으로 GridBagLayout
이 내 첫 선택입니다.
편집가 : PIC는 (! 감사 trashgod)를 추가
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MessageAppDemo implements Runnable
{
private String[] messages = new String[] {
"Hello?",
"Hey, what's up?",
"Where are you?",
"Right behind you.",
"Stop following me!",
"But you owe me money.",
"I'll gladly repay you on Tuesday.",
"You said that last week!",
"But now I actually have a job."
};
private int msgCounter = 0;
private JPanel panel;
private JScrollPane scrollPane;
private Timer timer;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new MessageAppDemo());
}
public void run()
{
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
scrollPane = new JScrollPane(panel);
scrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_NEVER);
scrollPane.setAutoscrolls(true);
JFrame frame = new JFrame("Message App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.setSize(260, 180);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
timer = new Timer(1500, new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if (msgCounter < messages.length)
{
addMessage(messages[msgCounter]);
}
else
{
timer.stop();
}
}
});
timer.start();
}
private void addMessage(String text)
{
boolean rightAligned = msgCounter % 2 != 0;
Color color = rightAligned ? Color.CYAN : Color.ORANGE;
JLabel label = new JLabel(text);
label.setOpaque(true);
label.setBackground(color);
label.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.BLUE),
BorderFactory.createEmptyBorder(2,4,2,4)
));
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.setBorder(BorderFactory.createEmptyBorder(2,4,2,4));
if (rightAligned)
{
p.add(Box.createHorizontalGlue());
p.add(label);
}
else
{
p.add(label);
p.add(Box.createHorizontalGlue());
}
panel.add(p);
panel.revalidate();
int x = panel.getPreferredSize().width;
int y = panel.getPreferredSize().height;
panel.scrollRectToVisible(new Rectangle(x-1 ,y-1, 1, 1));
msgCounter++;
}
}
더 나은 도움말은 빨리, 게시하시기 바랍니다 [최소한의 완벽한 예] (http://stackoverflow.com/help/mcve) 당신이 시도한 것을 보여줍니다. – splungebob
레이아웃 권장 사항까지,'BoxLayout'을 사용하는 것은 다소 쉬울 것입니다 (저는 몇 분 안에 모의 연습을했습니다). 'GridBagLayout'을 사용하면 조금 더 효과적 일지 모르지만 조금 더 멋지게 보일 것입니다. – splungebob
내 표가 GridBagLayout으로 이동합니다. 그리드 폭을 GridBagConstraints.REMAINDER로 설정하고 적절한 앵커를 사용하면 원하는 결과가 생성됩니다. – MadProgrammer