reol44
reol44
2021-02-18 22:51
采纳率: 33.3%
浏览 62
已采纳

java 怎么使用Swing的JScrollPane写出一个聊天信息显示的效果

学习java stocket时,试着用stocket写了一个聊天室,在使用swing写界面时,设想是用JScrollPane来显示消息记录的,可是写完发现在JSrollPane里面不能用绝对布局,求怎么达到 自己的消息显示在右边, 别人消息显示在左边,按时间排下来的效果

大概长这样

 

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • allway2
    allway2 2021-02-19 07:50
    已采纳
    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.border.EmptyBorder;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JLabel;
    
    public class JScrollPaneDemo extends JFrame {
    
    	private JPanel contentPane;
    
    	/**
    	 * Launch the application.
    	 */
    	public static void main(String[] args) {
    		EventQueue.invokeLater(new Runnable() {
    			public void run() {
    				try {
    					JScrollPaneDemo frame = new JScrollPaneDemo();
    					frame.setVisible(true);
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
    		});
    	}
    
    	/**
    	 * Create the frame.
    	 */
    	public JScrollPaneDemo() {
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setBounds(100, 100, 400, 286);
    		contentPane = new JPanel();
    		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    		setContentPane(contentPane);
    		contentPane.setLayout(null);
    
    		JScrollPane scrollPane = new JScrollPane();
    		scrollPane.setBounds(26, 46, 352, 131);
    		contentPane.add(scrollPane);
    		
    		JPanel panel = new JPanel();
    		scrollPane.setViewportView(panel);
    		panel.setLayout(null);
    		
    		JLabel lblNewLabel = new JLabel("New label");
    		lblNewLabel.setBounds(0, 10, 54, 15);
    		panel.add(lblNewLabel);
    		
    		JLabel lblNewLabel_1 = new JLabel("New label");
    		lblNewLabel_1.setBounds(286, 37, 54, 15);
    		panel.add(lblNewLabel_1);
    		
    		JLabel lblNewLabel_2 = new JLabel("New label");
    		lblNewLabel_2.setBounds(0, 64, 54, 15);
    		panel.add(lblNewLabel_2);
    		
    		JLabel lblNewLabel_3 = new JLabel("New label");
    		lblNewLabel_3.setBounds(286, 92, 54, 15);
    		panel.add(lblNewLabel_3);
    		
    		JLabel lblNewLabel_4 = new JLabel("New label");
    		lblNewLabel_4.setBounds(0, 114, 54, 15);
    		panel.add(lblNewLabel_4);
    
    
    	}
    }
    点赞 1 评论
  • allway2
    allway2 2021-02-19 07:51

    在JScrollPane中添加JPanel,在JPanel中添加JLabel

    点赞 评论
  • allway2
    allway2 2021-02-19 07:55

    点赞 评论
  • reol44
    reol44 2021-02-19 10:07

    谢了找到问题了,原来是我的放置JLabel的x,y搞错了,所以才看不到显示

    点赞 评论
  • reol44
    reol44 2021-02-19 10:30
    点赞 评论

相关推荐