开发者

JButton actionListener

I programmed a JFrame that have a Button and JList , and when i click on the Button , the JList list will be displayed . Instead it shows nothing unless i click on maximaze , or refresh the frame. the button listener class

class b0listener implements ActionListener{

                @Override
                public void actionPerformed(ActionEvent e) {
                 开发者_如何学JAVA   // TODO Auto-generated method stub
                    MessageList.removeAll();    
                    Messages = new JList(lireRepertoire("C:/Documents and Settings/Java/eclipse data file"));


                    Pane =new JScrollPane(Messages);
                    Pane.setPreferredSize(new Dimension(400,400));
                    //Messages.setMaximumSize(MessageList.getPreferredSize()) ;
                    MessageList.add( Pane);

                }}

the class constructor code

Fframe.setTitle("Boite Message");
        Fframe.setSize(800,300);
        Fframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Fframe.setVisible(true);    
        //  panels Layout 

        ButtonMenu.setLayout(new BoxLayout(ButtonMenu, BoxLayout.Y_AXIS));//Jpanel
        MessageList.setLayout(new FlowLayout());//JPanel
        ButtonMenu.setBackground(Color.LIGHT_GRAY);
        MessageList.setBackground(Color.orange);
        MessageList.setPreferredSize(new Dimension(400, 400));

                Fframe.add(ButtonMenu,BorderLayout.WEST);
        Fframe.add(MessageList,BorderLayout.CENTER);
        ButtonMenu.add(b0);
                b0.addActionListener(new b0listener());
                 Pane =new JScrollPane(Messages);
        Messages.setPreferredSize(new Dimension(800,250));
        //Pane.setMaximumSize(MessageList.getSize()) ;
        MessageList.add( Pane);

I already declared the Jpanels and Jframe , button as class members


First of all, learn an use the proper Java naming conventions. Variables should not start with an upper case character.

When dynamically adding/removing components from a panel you need to revalidate() the panel:

messageList.add( pane); 
messageList.revalidate();
messageList.repaint();


Instead of changing the components inside your frame you should instead think about your design and if it really is necessary to do so.

In your case the only effect is to change the content inside a JList. Therefore you should not rebuild the GUI but instead use the view-model separation and change the model content only. You can find an example in How to Use Lists - Adding Items to and Removing Items from a List.


Call

// Add the component againt to appear in the interface.
Fframe.add(MessageList,BorderLayout.CENTER);
Frame.repaint();

This is because, if you add components to the frame, calling repaint will refresh the underlying structure with the interface.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜