1

私はJava Swingのコードに取り組んでいます。JTable に JComboBox を作成しました。それは働いています:)。ただし、値を選択して保存またはキャンセル ボタンをクリックすると、デフォルト値 (コンボ ボックスの最初の値) にリセットする必要があります。のような方法をたくさん試しましたcombobox.setSelectedIndex(0)。これは機能していません。コード:

String[] manTimeHr = { "00","01", "02", "03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23"};
        String[] manTimeMin = {"00","01", "02", "03","04","05","06","07","08","09","10","11","12","13", "14", "15","16","17","18","19","20","21","22","23","24","25", "26", "27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59"};
        String[][] data = {{"-select-","-select-"}};
        String[] cols = {"Hrs","Mins"};
        String[][] data1 = {{"-select-","-select-"}};
        String[] cols1 = {"Hrs","Mins"};
        JLabel manTimeStart = new JLabel("Start From",JLabel.LEFT);
        STimeTbl = new JTable(data,cols);
        hrsColumn=STimeTbl.getColumnModel().getColumn(0);
        minsColumn=STimeTbl.getColumnModel().getColumn(1);
        manSiteStimeHrCBx = new JComboBox(manTimeHr);
        manSiteStimeHrCBx.setSelectedIndex(0);
        hrsColumn.setCellEditor(new DefaultCellEditor(manSiteStimeHrCBx));
        manSiteStimeMinCBx = new JComboBox(manTimeMin);
        manSiteStimeMinCBx.setSelectedIndex(0);
        minsColumn.setCellEditor(new DefaultCellEditor(manSiteStimeMinCBx));
        JLabel manTimeEnd = new JLabel("End To",JLabel.LEFT);
        ETimeTbl = new JTable(data1,cols1);
        hrsColumn1=ETimeTbl.getColumnModel().getColumn(0);
        minsColumn1=ETimeTbl.getColumnModel().getColumn(1);
        manSiteEtimeHrCBx = new JComboBox(manTimeHr);
        manSiteEtimeHrCBx.setSelectedIndex(0);
        hrsColumn1.setCellEditor(new DefaultCellEditor(manSiteEtimeHrCBx));
        manSiteEtimeMinCBx = new JComboBox(manTimeMin);
        manSiteEtimeMinCBx.setSelectedIndex(0);
        minsColumn1.setCellEditor(new DefaultCellEditor(manSiteEtimeMinCBx));
        .
        .
        .
        .
        if("Save".equals(e.getActionCommand())) {
        try{
                    mSHr = Integer.parseInt((String)manSiteStimeHrCBx.getSelectedItem());
                    mEHr=Integer.parseInt((String)manSiteEtimeHrCBx.getSelectedItem());
                    mSMin=Integer.parseInt((String)manSiteStimeMinCBx.getSelectedItem());
                    mEMin=Integer.parseInt((String)manServEtimeMinCBx.getSelectedItem());
                }catch (Exception en){
                System.out.println("Main Exception : "+ en);
                    return;
                }
                if(validateBlockTime(mSHr,mEHr,mSMin,mEMin) != true)
                {
                    System.out.println("Enter valid Time");
                    return;
                }
                manSiteStimeHrCBx.setSelectedIndex(0);
                manSiteStimeMinCBx.setSelectedIndex(0);
                manSiteEtimeHrCBx.setSelectedIndex(0);
                manSiteEtimeMinCBx.setSelectedIndex(0);
        .
        .
        .
        private static boolean validateBlockTime(int val3, int val4, int val5, int val6){
        if(val4 > val3)
            return true;
        else if((val4 == val3) && (val6 > val5))
            return true;
        else
            return false;
        }
4

1 に答える 1

3

ここに画像の説明を入力ここに画像の説明を入力

チュートリアルコードに基づくクイックコード(怠け者で申し訳ありません)

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import javax.swing.JButton;

public class TableRenderDemo extends JPanel {

    private static final long serialVersionUID = 1L;
    private boolean DEBUG = false;

    public TableRenderDemo() {
        super(new BorderLayout(5, 5));
        final JTable table = new JTable(new MyTableModel());
        table.setRowHeight(18);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        initColumnSizes(table);
        setUpSportColumn(table, table.getColumnModel().getColumn(2));
        add(scrollPane);
        JButton resetButton = new JButton("Reset to default");
        resetButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
               for (int i = 0; i < table.getRowCount(); i++) {
                    table.getModel().setValueAt("None of the above", i, 2);
               }
            }
        });
        add(resetButton, BorderLayout.SOUTH);
    }

    private void initColumnSizes(JTable table) {
        MyTableModel model = (MyTableModel) table.getModel();
        TableColumn column = null;
        Component comp = null;
        int headerWidth = 0;
        int cellWidth = 0;
        Object[] longValues = model.longValues;
        TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
        for (int i = 0; i < 5; i++) {
            column = table.getColumnModel().getColumn(i);
            comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
            headerWidth = comp.getPreferredSize().width;
            comp = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table, longValues[i], false, false, 0, i);
            cellWidth = comp.getPreferredSize().width;
            if (DEBUG) {
                System.out.println("Initializing width of column " + i + ". " + "headerWidth = " + headerWidth + "; cellWidth = " + cellWidth);
            }
            column.setPreferredWidth(Math.max(headerWidth, cellWidth));
        }
    }

    private void setUpSportColumn(JTable table, TableColumn sportColumn) {
        JComboBox comboBox = new JComboBox();
        comboBox.addItem("Snowboarding");
        comboBox.addItem("Rowing");
        comboBox.addItem("Knitting");
        comboBox.addItem("Speed reading");
        comboBox.addItem("Pool");
        comboBox.addItem("None of the above");
        sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setToolTipText("Click for combo box");
        sportColumn.setCellRenderer(renderer);
    }

    private class MyTableModel extends AbstractTableModel {

        private static final long serialVersionUID = 1L;
        private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
        private Object[][] data = {
            {"Kathy", "Smith", "Snowboarding", new Integer(5), false},
            {"John", "Doe", "Rowing", new Integer(3), true},
            {"Sue", "Black", "Knitting", new Integer(2), false},
            {"Jane", "White", "Speed reading", new Integer(20), true},
            {"Joe", "Brown", "Pool", new Integer(10), false}
        };
        public final Object[] longValues = {"Jane", "Kathy", "None of the above", new Integer(20), Boolean.TRUE};

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

        public int getRowCount() {
            return data.length;
        }

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

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }

        @Override
        public Class<?> getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        @Override
        public boolean isCellEditable(int row, int col) {
            if (col < 2) {
                return false;
            } else {
                return true;
            }
        }

        @Override
        public void setValueAt(Object value, int row, int col) {
            data[row][col] = value;
            fireTableCellUpdated(row, col);
            System.out.println(getValueAt(row, col));
        }
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("TableRenderDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        TableRenderDemo newContentPane = new TableRenderDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                createAndShowGUI();
            }
        });
    }
}

からの出力AbstractTableModel、コード行135th.

run:
None of the above
None of the above
None of the above
None of the above
None of the above
BUILD SUCCESSFUL (total time: 37 seconds)
于 2012-09-06T10:40:47.787 に答える