private void initMsgPanel(){ msgPanel=new JPanel(); msgPanel.setLayout(new BoxLayout(msgPanel, BoxLayout.Y_AXIS)); msgPanel.setBackground(Color.WHITE); JScrollPane scrollPane = new JScrollPane(msgPanel); scrollPane.setBounds(5,5,370,330); add(scrollPane); } 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(),vertical = scrollPane.getVerticalScrollBar(); vertical.setValue(vertical.getMaximum());; }报错::Exception in thread "Thread-4" java.lang.NullPointerException
时间: 2024-02-19 19:58:44 浏览: 85
JPanel_Example.java
根据您提供的代码和报错信息,可以看出问题出在 `msgAddToMsgPanel()` 方法中的这行代码:
```
vertical = scrollPane.getVerticalScrollBar();
```
这里的 `scrollPane` 对象是在 `initMsgPanel()` 方法中创建的,但是您在 `msgAddToMsgPanel()` 方法中并没有将 `scrollPane` 对象传递进来,因此在这里使用 `scrollPane` 对象时会出现空指针异常。
解决这个问题的方法是,将 `scrollPane` 对象作为参数传递给 `msgAddToMsgPanel()` 方法。您可以将 `scrollPane` 对象作为类成员变量,然后在 `initMsgPanel()` 方法中初始化它,然后在 `msgAddToMsgPanel()` 方法中直接使用这个成员变量。
修改后的代码如下所示:
```
private JScrollPane scrollPane; // 声明成员变量
private void initMsgPanel() {
msgPanel = new JPanel();
msgPanel.setLayout(new BoxLayout(msgPanel, BoxLayout.Y_AXIS));
msgPanel.setBackground(Color.WHITE);
scrollPane = new JScrollPane(msgPanel); // 初始化成员变量
scrollPane.setBounds(5, 5, 370, 330);
add(scrollPane);
}
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();
JScrollBar vertical = scrollPane.getVerticalScrollBar(); // 直接使用成员变量
vertical.setValue(vertical.getMaximum());
}
```
希望这个修改可以解决您的问题。
阅读全文