JTable空白渲染

时间:2016-04-06 05:43:04

标签: java swing jframe jtable

当我运行JFrame时,JTable不会渲染,除非我选择行或单击其中一个列标题。 这是运行后的程序: http://puu.sh/o7U79/399f4208de.png

JTable工作,除非我选择如下所示的行,否则将运行但不会渲染: enter image description here

这是我创建JFrame的项目代码:

import com.skype.Skype;
import com.skype.User;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.TableModel;

class MenuExample
        extends     JFrame
        implements  ActionListener
{
    private final int   ITEM_PLAIN  =   0;  // Item types
    private final int   ITEM_CHECK  =   1;
    private final int   ITEM_RADIO  =   2;

    private JPanel      topPanel;
    private JTable      table;
    private JScrollPane scrollPane;
    private JMenuBar    menuBar;
    private JMenu       menuFile;
    private JMenu       menuEdit;
    private JMenu       menuProperty;
    private JMenuItem   menuPropertySystem;
    private JMenuItem   menuPropertyEditor;
    private JMenuItem   menuPropertyDisplay;
    private JMenuItem   menuFileNew;
    private JMenuItem   menuFileOpen;
    private JMenuItem   menuFileSave;
    private JMenuItem   menuFileSaveAs;
    private JMenuItem   menuFileExit;
    private JMenuItem   menuEditCopy;
    private JMenuItem   menuEditCut;
    private JMenuItem   menuEditPaste;

    public MenuExample()
    {
        //Pack and center
        pack();
        setLocationRelativeTo(null);
        setSize( 600, 400 );

        //Create a panel
        topPanel = new JPanel();
        topPanel.setLayout( new BorderLayout() );
        getContentPane().add( topPanel );

        //Create a table with my object as input
        TableModel dataModel = new UserTableModel();
        table = new JTable(dataModel);
        table.setDefaultRenderer(String.class,new BoardTableCellRenderer());
        table.setFillsViewportHeight(true);
        table.addMouseListener(new PopClickListener());
        scrollPane = new JScrollPane(table);
        topPanel.add(scrollPane);add(scrollPane);

        // Create the menu bar
        menuBar = new JMenuBar();

        // Set this instance as the application's menu bar
        setJMenuBar( menuBar );

        // Build the property sub-menu
        menuProperty = new JMenu( "Properties" );
        menuProperty.setMnemonic( 'P' );

        // Create property items
        menuPropertySystem = CreateMenuItem( menuProperty, ITEM_PLAIN, "System...", null, 'S', null );
        menuPropertyEditor = CreateMenuItem( menuProperty, ITEM_PLAIN, "Editor...", null, 'E', null );
        menuPropertyDisplay = CreateMenuItem( menuProperty, ITEM_PLAIN, "Display...", null, 'D', null );

        // Create the file menu
        menuFile = new JMenu( "File" );
        menuFile.setMnemonic( 'F' );
        menuBar.add( menuFile );

        // Create the file menu
        // Build a file menu items
        menuFileNew = CreateMenuItem( menuFile, ITEM_PLAIN, "New", null, 'N', null );
        menuFileNew.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //do shit
            }
        });
        menuFileOpen = CreateMenuItem( menuFile, ITEM_PLAIN, "Open...", new ImageIcon( "open.gif" ), 'O', "Open a new file" );
        menuFileSave = CreateMenuItem( menuFile, ITEM_PLAIN, "Save", new ImageIcon( "save.gif" ), 'S'," Save this file" );
        menuFileSaveAs = CreateMenuItem( menuFile, ITEM_PLAIN, "Save As...", null, 'A', "Save this data to a new file" );

        // Add the property menu
        menuFile.addSeparator();
        menuFile.add( menuProperty );
        menuFile.addSeparator();
        menuFileExit = CreateMenuItem( menuFile, ITEM_PLAIN, "Exit", null, 'x', "Exit the program" );


        // Create the file menu
        menuEdit = new JMenu( "Edit" );
        menuEdit.setMnemonic( 'E' );
        menuBar.add( menuEdit );

        // Create edit menu options
        menuEditCut = CreateMenuItem( menuEdit, ITEM_PLAIN, "Cut", null, 't', "Cut data to the clipboard" );
        menuEditCopy = CreateMenuItem( menuEdit, ITEM_PLAIN, "Copy", null, 'C', "Copy data to the clipboard" );
        menuEditPaste = CreateMenuItem( menuEdit, ITEM_PLAIN, "Paste", null, 'P', "Paste data from the clipboard" );


        try {
            setTitle("SkypeMAX - " + Skype.getProfile().getId().toString());
        } catch (Exception ex) {  }
    }

    class PopUpDemo extends JPopupMenu {
        JMenuItem messageItem;
        public PopUpDemo(){
            //Message item start
            if(table.getSelectedRowCount() == 1) { messageItem = new JMenuItem("Message " +
                    table.getModel().getValueAt(table.getSelectedRow(), 1).toString()); } else{ messageItem = new JMenuItem("Message group");  }
            ImageIcon imageIcon = new ImageIcon(getClass().getResource("/MESSAGE.gif"));
            messageItem.setIcon(imageIcon);
            messageItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        if(table.getSelectedRowCount() == 1) {
                            try {
                                User u = Functions.returnUser(table.getModel().getValueAt(table.getSelectedRow(), 1).toString());
                                String message = JOptionPane.showInputDialog("Please enter the message you want to send to " + u.getId());
                                Skype.chat(u.getId()).send(Functions.formatText(message,u));
                            } catch (Exception ex) {  }
                        }else{
                            Functions.messageGroup(table,JOptionPane.showInputDialog("Please enter the group message:"));
                        }

                    } catch (Exception ex) {
                        System.out.println("Error with messaging.");
                    }

                }
            });
            add(messageItem);
            //Message item end
        }
    }

    class PopClickListener extends MouseAdapter {
        public void mousePressed(MouseEvent e){
            if (e.isPopupTrigger())
                doPop(e);
        }

        public void mouseReleased(MouseEvent e){
            if (e.isPopupTrigger())
                doPop(e);
        }

        private void doPop(MouseEvent e){
            PopUpDemo menu = new PopUpDemo();
            menu.show(e.getComponent(), e.getX(), e.getY());
        }
    }

    public JMenuItem CreateMenuItem( JMenu menu, int iType, String sText, ImageIcon image, int acceleratorKey, String sToolTip )
    {
        // Create the item
        JMenuItem menuItem;
        switch( iType )
        {
            case ITEM_RADIO:
                menuItem = new JRadioButtonMenuItem();
                break;

            case ITEM_CHECK:
                menuItem = new JCheckBoxMenuItem();
                break;

            default:
                menuItem = new JMenuItem();
                break;
        }

        // Add the item test
        menuItem.setText( sText );

        // Add the optional icon
        if( image != null )
            menuItem.setIcon( image );

        // Add the accelerator key
        if( acceleratorKey > 0 )
            menuItem.setMnemonic( acceleratorKey );

        // Add the optional tool tip text
        if( sToolTip != null )
            menuItem.setToolTipText( sToolTip );
        // Add an action handler to this menu item
        menuItem.addActionListener( this );
        menu.add( menuItem );
        return menuItem;
    }

    public void actionPerformed( ActionEvent event )
    {
        System.out.println( event );
    }

    public static void main( String args[] )
    {
        MenuExample mainFrame = new MenuExample();
        mainFrame.setVisible( true );
    }
}

这是我使用的UserTableModel。

import com.skype.Skype;
import com.skype.User;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
import java.util.Date;

class UserTableModel extends AbstractTableModel
{
    private String[] columnNames =
            {       "Status",
                    "Username",
                    "Country",
                    "Name"
            };

    private ArrayList<User> users;

    public UserTableModel()
    {
        users = new ArrayList<User>();
        try {
            for (User s : Skype.getContactList().getAllFriends()) {
                if(!s.isBlocked() && s.isAuthorized()) {
                    users.add(s);
                }
            }
        } catch (Exception ex) { }
    }

    @Override
    public int getColumnCount()
    {
        return columnNames.length;
    }

    @Override
    public String getColumnName(int column)
    {
        return columnNames[column];
    }

    @Override
    public int getRowCount()
    {
        return users.size();
    }

    @Override
    public Class getColumnClass(int column)
    {
        switch (column)
        {
            case 0: return ImageIcon.class;
            default: return String.class;
        }
    }

    @Override
    public boolean isCellEditable(int row, int column)
    {
        switch (column)
        {
            //case 2: return true; // only the birth date is editable
            default: return false;
        }
    }

    @Override
    public Object getValueAt(int row, int column)
    {
        User user = getUser(row);

        switch (column)
        {
            case 0:
                try {
                    ImageIcon imageIcon = new ImageIcon(getClass().getResource("/" + user.getStatus().toString() + ".png"));
                    return imageIcon;
                } catch(Exception ex) {  }
            case 1: return user.getId();
            case 2: try { return user.getCountry(); } catch(Exception ex) {  }
            case 3: try { return user.getFullName(); } catch(Exception ex) {  }
            default: return null;
        }
    }

    @Override
    public void setValueAt(Object value, int row, int column)
    {
        User user = getUser(row);

        switch (column)
        {
            case 0: user.getId(); break;
            case 1: try { user.getStatus().toString(); } catch(Exception ex) {  } break;
            case 2: try { user.getFullName(); } catch(Exception ex) {  } break;
        }

        fireTableCellUpdated(row, column);
    }

    public User getUser(int row)
    {
        return users.get( row );
    }

    public void addUser(User user)
    {
        insertPerson(getRowCount(), user);
    }

    public void insertPerson(int row, User user)
    {
        users.add(row, user);
        fireTableRowsInserted(row, row);
    }

    public void removeUser(int row)
    {
        users.remove(row);
        fireTableRowsDeleted(row, row);
    }

}

0 个答案:

没有答案