private void initMsgPanel(){ /* msgPanel=new JPanel(); msgPanel.setBounds(5,5,370,330); msgPanel.setBackground(Color.WHITE); add(msgPanel);} private void msgAddToMsgPanel(String msg,int align){ System.out.println("==========msgAddToMsgPanel==========="+msg); JLabel msgLbl=new JLabel(msg,SwingConstants.CENTER); msgLbl.setForeground(Color.decode("#61565A")); msgLbl.setBackground(Color.decode("#BACCD9")); msgLbl.setSize(50,25); msgLbl.setBorder(BorderFactory.createLineBorder(Color.getColor("#8FB2C9"),2,true)); msgLbl.setOpaque(true);//设置不透明 JPanel itemPanel=new JPanel(); itemPanel.setBackground(Color.WHITE); //将每一条消息所在的面板宽度,和消息面板的面板宽度相同 itemPanel.setPreferredSize(new Dimension(msgPanel.getWidth(),25)); itemPanel.add(msgLbl); //设置左右对齐 FlowLayout layout = (FlowLayout) itemPanel.getLayout(); layout.setAlignment(align); msgPanel.add(itemPanel); //更新界面 msgPanel.updateUI(); },使消息能正常显示的同时让消息面板能拥有垂直滑动条
时间: 2024-01-27 19:02:51 浏览: 115
您可以将msgPanel放入一个带有垂直滚动条的JScrollPane中,以使其具有垂直滑动条。以下是修改后的代码:
```
private JScrollPane msgScrollPane;
private void initMsgPanel(){
msgPanel=new JPanel();
msgPanel.setBackground(Color.WHITE);
msgScrollPane = new JScrollPane(msgPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
msgScrollPane.setBounds(5,5,370,330);
add(msgScrollPane);
}
```
这样,msgPanel就能够具有垂直滑动条了,并且您可以通过msgScrollPane对象来操作滚动条。同时,您需要修改msgAddToMsgPanel方法中的代码,将消息添加到msgPanel中而不是添加到itemPanel中。
```
private void msgAddToMsgPanel(String msg,int align){
System.out.println("==========msgAddToMsgPanel==========="+msg);
JLabel msgLbl=new JLabel(msg,SwingConstants.CENTER);
msgLbl.setForeground(Color.decode("#61565A"));
msgLbl.setBackground(Color.decode("#BACCD9"));
msgLbl.setSize(50,25);
msgLbl.setBorder(BorderFactory.createLineBorder(Color.getColor("#8FB2C9"),2,true));
msgLbl.setOpaque(true);//设置不透明
JPanel itemPanel=new JPanel();
itemPanel.setBackground(Color.WHITE);
//将每一条消息所在的面板宽度,和消息面板的面板宽度相同
itemPanel.setPreferredSize(new Dimension(msgPanel.getWidth(),25));
itemPanel.add(msgLbl);
//设置左右对齐
FlowLayout layout = (FlowLayout) itemPanel.getLayout();
layout.setAlignment(align);
msgPanel.add(itemPanel);
//更新界面
msgScrollPane.getVerticalScrollBar().setValue(msgScrollPane.getVerticalScrollBar().getMaximum());
}
```
这样,消息就能正常显示,并且能够拥有垂直滑动条了。
阅读全文