从Listener调用时,JPanel.add不起作用

时间:2015-05-19 14:00:34

标签: java swing jpanel layout-manager

我在点击对象时尝试添加到 leftPanel 。该对象在打印出预定义的刺痛时会听取咔嗒声。它不会抛出错误或异常。

public void AddToEventList(Event event) {

    JPanel panel = new JPanel();
    panel.setBorder(new LineBorder(Color.BLACK));
    JLabel act = new JLabel(event.getAct());
    JLabel session = new JLabel("Session: " + event.getSession());
    JLabel venue = new JLabel("Venue: " + event.getVenue());

    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    panel.setPreferredSize(new Dimension(260,50));
    panel.add(act);
    panel.add(session);
    panel.add(venue);

    panel.addMouseListener(new MouseAdapter() {
         @Override
         public void mousePressed(MouseEvent e) {
             AddToPlan(event);
             System.out.println(event.getAct()+";"+event.getSession()+";"+event.getVenue());
         }
      });

    rightPanel.add(panel,"West");
}

这是添加面板的函数。事件我正在创建一个新的JPanel,它不会将它添加到左侧面板。

public void AddToPlan( Event event) {

    JPanel panelL = new JPanel();
    panelL.setBorder(new LineBorder(Color.BLACK));
    JLabel act = new JLabel(event.getAct());
    JLabel session = new JLabel("Session: " + event.getSession());
    JLabel venue = new JLabel("Venue: " + event.getVenue());

    panelL.setLayout(new BoxLayout(panelL, BoxLayout.Y_AXIS));
    panelL.setPreferredSize(new Dimension(260,50));
    panelL.add(act);
    panelL.add(session);
    panelL.add(venue);

    leftPanel.add(panelL,"West");
}

    rightPanel.add(panel,"West");
} 

1 个答案:

答案 0 :(得分:0)

@Jhonskeet和@MadProgrammer提供的答案

添加同一对象的多个实例会导致冲突。添加到JPanel后,应始终使用revalidate并重新绘制。