简体   繁体   中英

How to dynamically update a JTable based on JComboBox values that are located in the same JPanel in Java?

I'm creating a JFrame with JPanel, which has 2 comboboxes: month and year selection.

Then underneath them there is a JTable that is based on a CalendarModel. The initial values of the CalendarModel is based on the first default selected month and year.

How can I update the table dynamically each time a different value is selected in each combobox?

My code (apologies - not yet arranged in classes and methods), is below:

Thanks!

UPDATE: I forgot to add the panel.add(scrollPane, BorderLayout.CENTER);

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class Main {
    
    public static void main(String[] args) throws IOException {

        final Boolean[] isPressed = {false};
        
        JFrame frame = new JFrame("Timesheet creator");
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 305);
        frame.setLocation(430, 100);
        
        JPanel panel = new JPanel();
        panel.setBackground( Color.ORANGE );
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); // added code
        frame.add(panel);
        
        panel.add(new JLabel("\t")); // spacing label
        
        JLabel lbl = new JLabel("Select a month & year and click Create");
        lbl.setAlignmentX( Component.CENTER_ALIGNMENT);
        panel.add(lbl);
        
        panel.add(new JLabel("\t"));
        
        String[] monthsList = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
        Integer[] yearChoiceList = {2020,2021,2022,2023,2024,2025,2026,2027,2028,2028,2030};
        
        final JComboBox<String> cbMonth = new JComboBox<String>(monthsList);
        final JComboBox<Integer> cbYear = new JComboBox<Integer>(yearChoiceList);
        
        cbMonth.setMaximumSize(cbMonth.getPreferredSize());
        cbMonth.setAlignmentX(Component.CENTER_ALIGNMENT);
        cbMonth.addActionListener( new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Month selected: " + cbMonth.getSelectedItem());
                CalendarModel model = new CalendarModel();
                model.setMonth(cbYear.getSelectedIndex() + 1998, cbMonth.getSelectedIndex());
            }
        } );
        panel.add(cbMonth);
        
        cbYear.setMaximumSize(cbYear.getPreferredSize());
        cbYear.setAlignmentX(Component.CENTER_ALIGNMENT);
        cbYear.addActionListener( new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Year selected: " + cbYear.getSelectedItem());
                CalendarModel model = new CalendarModel();
                model.setMonth(cbYear.getSelectedIndex() + 1998, cbMonth.getSelectedIndex());
            }
        } );
        panel.add(cbYear);
        
        JButton btnCreate = new JButton("Create");
        btnCreate.setAlignmentX(Component.CENTER_ALIGNMENT); // added code
        btnCreate.addActionListener( new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Button pressed");
                isPressed[0] = true;
            }
        } );

        panel.setBorder( new EmptyBorder( 0,20,0,20 ) );
        panel.setSize( 150,60 );
        
        //Table creation:
        CalendarModel model = new CalendarModel();
        JTable table = new JTable(model);
        
        table.setBounds(130, 0, 80, 50);
        
        model.setMonth(cbYear.getSelectedIndex() + 1998, cbMonth.getSelectedIndex());
        model.fireTableDataChanged();
        table.setGridColor(Color.black);
        table.setShowGrid(true);
        table.setAlignmentX(Component.WIDTH);

        JScrollPane scrollPane = new JScrollPane(table);

        scrollPane.setBorder( new BevelBorder( 1 ) );
        scrollPane.setBorder( new EmptyBorder( 4,20,20,20 ) );
        scrollPane.setBackground( Color.ORANGE );
        scrollPane.getViewport().setViewPosition(new Point(50,50));
        scrollPane.setColumnHeaderView( table.getTableHeader() );
        scrollPane.getColumnHeader().setBackground( Color.ORANGE );
        table.getTableHeader().setVisible( false );

        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(btnCreate);
        frame.setVisible(true);
    }
}

CalendarModel class:

import javax.swing.table.AbstractTableModel;

class CalendarModel extends AbstractTableModel {
    String[] days = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
    
    int[] numDays = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    
    String[][] calendar = new String[7][7];
    
    public CalendarModel() {
        for (int i = 0; i < days.length; ++i)
            calendar[0][i] = days[i];
        for (int i = 1; i < 7; ++i)
            for (int j = 0; j < 7; ++j)
                calendar[i][j] = " ";
    }
    
    public int getRowCount() {
        return 7;
    }
    
    public int getColumnCount() {
        return 7;
    }
    
    public Object getValueAt(int row, int column) {
        return calendar[row][column];
    }
    
    public void setValueAt(Object value, int row, int column) {
        calendar[row][column] = (String) value;
    }
    
    public void setMonth(int year, int month) {
        for (int i = 1; i < 7; ++i)
            for (int j = 0; j < 7; ++j)
                calendar[i][j] = " ";
        java.util.GregorianCalendar cal = new java.util.GregorianCalendar();
        cal.set(year, month, 1);
        int offset = cal.get(java.util.GregorianCalendar.DAY_OF_WEEK) - 1;
        offset += 7;
        int num = daysInMonth(year, month);
        for (int i = 0; i < num; ++i) {
            calendar[offset / 7][offset % 7] = Integer.toString(i + 1);
            ++offset;
        }
    }
    
    public boolean isLeapYear(int year) {
        if (year % 4 == 0)
            return true;
        return false;
    }
    
    public int daysInMonth(int year, int month) {
        int days = numDays[month];
        if (month == 1 && isLeapYear(year))
            ++days;
        return days;
    }
}
CalendarModel model = new CalendarModel();
model.setMonth(cbYear.getSelectedIndex() + 1998, cbMonth.getSelectedIndex());

The above code does nothing. You create a new model and set the month but don't do anything with the model.

You have two options:

  1. replace the model in the table with the new model.

Code:

CalendarModel model = new CalendarModel();
model.setMonth(cbYear.getSelectedIndex() + 1998, cbMonth.getSelectedIndex());
table.setModel( model );
  1. update the existing model in the table to reset the month:

Code:

CalendarModel model = (CalendarModel)table.getModel();
model.setMonth(cbYear.getSelectedIndex() + 1998, cbMonth.getSelectedIndex());

In both cases this will mean that you need to define the JTable as an instace variable of your class, not a local variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM