简体   繁体   English

如何根据位于 Java 中同一 JPanel 中的 JComboBox 值动态更新 JTable?

[英]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.我正在使用 JPanel 创建一个 JFrame,它有 2 个组合框:月份和年份选择。

Then underneath them there is a JTable that is based on a CalendarModel.然后在它们下面有一个基于 CalendarModel 的 JTable。 The initial values of the CalendarModel is based on the first default selected month and year. CalendarModel 的初始值基于第一个默认选择的月份和年份。

How can I update the table dynamically each time a different value is selected in each combobox?每次在每个 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);更新:我忘了添加 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:日历型号 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.您创建一个新的 model 并设置月份,但不对 model 执行任何操作。

You have two options:你有两个选择:

  1. replace the model in the table with the new model.用新的 model 替换表中的 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:更新表中现有的 model 以重置月份:

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.在这两种情况下,这意味着您需要将 JTable 定义为 class 的实例变量,而不是局部变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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