0

Hi, I'm having trouble with setting up my table. How do i get the header to show initially. I want "code", "Number" and "Value" as the header. And I want to know if the way i added the table is correct? Can you help me please. Thank you!

import model.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;

public class Shares extends JPanel
{
    private JButton btnFind = new JButton();
    private JTextField txtId = new JTextField(10);
    private JTable tableShare = new JTable();
    Customers customers = null;
    
    public Shares(Trader trader)
    {
        customers = trader.customers();
        setup();
        build();
    }
    
    private void setup()
    {
        setLayout(new FlowLayout());
        setBorder(BorderFactory.createLineBorder(Color.blue));
    }
    
    private void build()
    {
        Box box1 = Box.createHorizontalBox();
        box1.add(new JLabel("Your id"));
        box1.add(txtId);
        btnFind.setText("Find");
        box1.add(btnFind);
        Box box2 = Box.createVerticalBox();
        box2.add(box1);
        box2.add(Box.createVerticalStrut(20));
        setTable();
        box2.add(tableShare);
        add(box2);
        setBtnFind();
    }
    
    private void setBtnFind()
    {
        btnFind.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnFindActionPerformed(evt);
            }
        });
    }
    
    private void btnFindActionPerformed(java.awt.event.ActionEvent evt){       
        Customer customer = customer();
        LinkedList<Share> shares= customer.shares();
        int j =0;
        for(Share share: shares){       
            tableShare.setValueAt(share.code(), j, 0);
            tableShare.setValueAt(share.number()+"", j, 1);
            tableShare.setValueAt(share.cost()+"", j, 2);
            j++;
        }   
    }
    
    private Customer customer(){
        int custId = Integer.parseInt(txtId.getText());
        Customer customer = customers.customer(custId);
        return customer;
    }
    
    private void setTable(){
        tableShare.setModel(new DefaultTableModel(
            new String[][]{
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
            },
            new String[]{
                "Code","Number","Value"
            }
        ));
    }
}
2
Contributors
1
Reply
4
Views
5 Years
Discussion Span
Last Post by mKorbel
0
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.table.*;

public class TableWithTimer extends JFrame {

    private static final long serialVersionUID = 1L;
    private JScrollPane scroll = new JScrollPane();
    private JTable myTable;
    private int count = 0;
    private int delay = 3;
    private javax.swing.Timer timer = null;

    public TableWithTimer() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        String[] head = {"One", "Two", "Three", "Four", "Five", "Six"};
        String[][] data = new String[25][6];
        myTable = new JTable(data, head);
        myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        myTable.setGridColor(Color.gray);
        myTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        final TableCellRenderer cellRendener = myTable.getTableHeader().getDefaultRenderer();
        myTable.getTableHeader().setDefaultRenderer(new TableCellRenderer() {

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
                JLabel label = (JLabel) cellRendener.getTableCellRendererComponent(
                        table, value, isSelected, hasFocus, row, column);
                label.setBackground(Color.orange);
                label.setForeground(Color.darkGray);
                label.setFont(new Font("SansSerif", Font.BOLD, 12));
                label.setBorder(BorderFactory.createCompoundBorder(label.getBorder(),
                        BorderFactory.createEmptyBorder(0, 5, 0, 0)));
                label.setHorizontalAlignment(SwingConstants.LEFT);
                label.setHorizontalAlignment(SwingConstants.CENTER);
                if ((label.getText().equals("First")) || (label.getText().equals("Second"))) {
                    label.setForeground(Color.red);
                }
                if ((label.getText().equals("Day")) || (label.getText().equals("Month")) || (label.getText().equals("Year"))) {
                    label.setForeground(Color.blue);
                }
                if ((label.getText().equals("Time"))) {
                    label.setForeground(Color.green);
                }
                return label;
            }
        });
        TableColumnModel cm = myTable.getColumnModel();
        for (int column1 = 0; column1 < cm.getColumnCount(); column1++) {
            TableColumn colLeft1 = cm.getColumn(column1);
            cm.getColumn(column1).setWidth(140);
            cm.getColumn(column1).setPreferredWidth(140);
        }
        //myTable.setFillsViewportHeight(true); // apply paintComponent for whole Viewport
        JButton cornerButtonTop = new JButton();
        cornerButtonTop.setBackground(scroll.getViewport().getBackground());
        JButton cornerButtonBottom = new JButton();
        cornerButtonBottom.setOpaque(false);
        scroll.setCorner(JScrollPane.UPPER_RIGHT_CORNER, cornerButtonTop);
        scroll.setCorner(JScrollPane.LOWER_RIGHT_CORNER, cornerButtonBottom);
        scroll.setViewportView(myTable);
        myTable.setPreferredScrollableViewportSize(myTable.getPreferredSize());
        add(scroll);
        setLocation(100, 100);
        pack();
        setVisible(true);
        start();
    }

    public Action updateCol() {
        return new AbstractAction("text load action") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("updating row " + (count + 1));
                TableModel model = myTable.getModel();
                int cols = model.getColumnCount();
                int row = 0;
                for (int j = 0; j < cols; j++) {
                    row = count;
                    myTable.changeSelection(row, 0, false, false);
                    timer.setDelay(200);
                    Object value = "row " + (count + 1) + " item " + (j + 1);
                    model.setValueAt(value, count, j);
                }
                count++;
                if (count >= myTable.getRowCount()) {
                    myTable.changeSelection(0, 0, false, false);
                    timer.stop();
                    for (int j = 0; j < cols; j++) {
                        String colName = model.getColumnName(j);
                        if (colName.equals("One")) {
                            myTable.getColumnModel().getColumn(j).setHeaderValue("First");
                        }
                        if (colName.equals("Two")) {
                            myTable.getColumnModel().getColumn(j).setHeaderValue("Second");
                        }
                        if (colName.equals("Three")) {
                            myTable.getColumnModel().getColumn(j).setHeaderValue("Day");
                        }
                        if (colName.equals("Four")) {
                            myTable.getColumnModel().getColumn(j).setHeaderValue("Month");
                        }
                        if (colName.equals("Five")) {
                            myTable.getColumnModel().getColumn(j).setHeaderValue("Year");
                        }
                        if (colName.equals("Six")) {
                            myTable.getColumnModel().getColumn(j).setHeaderValue("Time");
                        }
                    }
                    JTableHeader hdr = myTable.getTableHeader();
                    //hdr.revalidate();
                    hdr.repaint();
                    System.out.println("update cycle completed");
                    myTable.clearSelection();
                }
            }
        };
    }

    private void start() {
        timer = new javax.swing.Timer(delay * 100, updateCol());
        timer.start();
    }

    public static void main(String args[]) {
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                System.out.println(info.getName());
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        TableWithTimer tableWithTimer = new TableWithTimer();
    }
}

Edited by mKorbel: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.