【问题标题】:JTable not changing appearanceJTable不改变外观
【发布时间】:2018-07-15 16:52:51
【问题描述】:

你好,早上好,

我请求帮助以适当地设置 JTable 的样式。我对 Java GUI 很陌生,因此我花了很长时间试图让它正常工作。

我的目标是尽可能接近地重新创建 Jeopardy 记分牌。

现在,我正在努力完成 3 件事:

  1. 尝试将表格中的所有数据(包括标题)居中
  2. 尝试更改标题字体颜色和背景
  3. 试图扩展表格以适应它所在的 JPanel 的整个框架

我的代码如下所示。任何帮助、反馈或指导将不胜感激。

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package QuestionBoard;

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

/**
 *
 * @author Kelly
 */


public class WiP_QuestionBoard extends javax.swing.JFrame {

    /**
     * Creates new form frameQuestionBoard
     */

    public WiP_QuestionBoard() {
        initComponents();

        //Trying to center components
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment( SwingConstants.CENTER );
        tblQuestions.setDefaultRenderer(Integer.class, centerRenderer);

        //Trying to change header settings
        JTableHeader Theader = tblQuestions.getTableHeader();
        Theader.setBackground(Color.BLUE);
       // Theader.setFontColor???(Color.YELLOW);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        panelQuestions = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblQuestions = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        tblQuestions.setBackground(new java.awt.Color(51, 102, 255));
        tblQuestions.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));
        tblQuestions.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        tblQuestions.setForeground(new java.awt.Color(204, 153, 0));
        tblQuestions.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"200", "200", "200", "200", "200", "200"},
                {"400", "400", "400", "400", "400", "400"},
                {"600", "600", "600", "600", "600", "600"},
                {"800", "800", "800", "800", "800", "800"},
                {"1000", "1000", "1000", "1000", "1000", "1000"}
            },
            new String [] {
                "Category 1", "Category 2", "Category 3", "Category 4", "Category 5", "Category 6"
            }
        ));
        tblQuestions.setDoubleBuffered(true);
        tblQuestions.setGridColor(new java.awt.Color(0, 0, 0));
        tblQuestions.setRowMargin(2);
        tblQuestions.setSelectionBackground(new java.awt.Color(0, 51, 255));
        tblQuestions.setSelectionForeground(new java.awt.Color(204, 204, 0));
        tblQuestions.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tblQuestions);

        javax.swing.GroupLayout panelQuestionsLayout = new javax.swing.GroupLayout(panelQuestions);
        panelQuestions.setLayout(panelQuestionsLayout);
        panelQuestionsLayout.setHorizontalGroup(
            panelQuestionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 675, Short.MAX_VALUE)
        );
        panelQuestionsLayout.setVerticalGroup(
            panelQuestionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelQuestionsLayout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 313, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelQuestions, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelQuestions, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(WiP_QuestionBoard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(WiP_QuestionBoard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(WiP_QuestionBoard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(WiP_QuestionBoard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new WiP_QuestionBoard().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel panelQuestions;
    private javax.swing.JTable tblQuestions;
    // End of variables declaration                   
}

【问题讨论】:

    标签: java swing user-interface netbeans jtable


    【解决方案1】:

    我对 Java GUI 很陌生

    我建议您不要使用 IDE 来生成代码。您花时间学习 IDE 而不是 Swing。使用 IDE 帮助编译、调试等。

    1.尝试将表格中的所有数据(包括表头)居中

    tblQuestions.setDefaultRenderer(Integer.class, centerRenderer);
    

    TableModel 中的所有数据都是 String 数据而不是 Integer 数据。如果您想要整数数据,则需要将整数对象添加到模型中。

    但是,即使这样还不够。您现在需要通过覆盖 TableModel 的 getColumnClass(...) 方法以返回 Integer.class 来告诉表每列中的数据类型。

    但是,根据您的代码而言,最简单的解决方案就是这样使用:

    tblQuestions.setDefaultRenderer(Object.class, centerRenderer);
    

    因为默认的 getColumnClass(...) 实现只为所有列返回 Object.class。

    对于header你需要访问默认渲染器来改变对齐方式:

    DefaultTableCellRenderer renderer = (DefaultTableCellRenderer)tblQuestions.getTableHeader().getDefaultRenderer();
    renderer.setHorizontalAlignment(SwingConstants.CENTER);
    

    2.尝试更改页眉字体颜色和背景

    这是 Nimbus LAF 的一个问题。默认渲染器似乎忽略了 setBackground() 方法。不知道如何解决。

    也许这个帖子会有所帮助:Nimbus - override color for TableHeader

    3.尝试扩展表格以适应它所在的 JPanel 的整个框架

    表格的首选大小取决于表格中每一行的高度。这个高度不会动态改变。如果您希望每行的高度更大,请使用:

    table.setRowHeight(32);
    

    此外,根据我最初的评论,我不会使用 IDE 来生成布局代码。 GroupLayout 过于复杂。我会简单地利用框架的默认 BorderLayout 来创建 GUI,代码如下:

    JTable table = new JTable(...);
    frame.add(new JScrollPane( table ), BorderLayout.PAGE_START);
    frame.pack();
    frame.setVisible();
    

    使用简单的布局代码,表格将以其首选大小显示在框架的顶部。随着框架宽度的改变,列将调整大小。如果更改框架高度,则不会发生任何事情,因此您可能希望使框架不可调整大小以确保表格始终填满框架。

    【讨论】:

    • 非常感谢您的详细帖子。我知道与新手打交道可能会令人沮丧,但我很感激您花时间为我布置所有这些步骤。我一直在阅读您所写的内容,然后查看文档以尝试了解更多信息,因此我当然很感激。谢谢你。我会尽快尝试实施(终于吃午饭了:))
    【解决方案2】:

    这是满足您要求的代码,将您的构造函数更改为以下内容(有一些 cmets 可以帮助您):

    public WiP_QuestionBoard() {
            initComponents();
    
            //Makes the table header text centered.
            ((DefaultTableCellRenderer) tblQuestions.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(SwingConstants.CENTER);
    
            //This will center the text in table (header not included).
            DefaultTableCellRenderer centerAlign = new DefaultTableCellRenderer();
    
            //center columns.
            centerAlign.setHorizontalAlignment(SwingConstants.CENTER);
            for (int i = 0; i < tblQuestions.getColumnCount(); i++) {
                tblQuestions.getColumnModel().getColumn(i).setCellRenderer(centerAlign);
            }
    
            //makes the table span the panel it is in.
            tblQuestions.setPreferredSize(this.panelQuestions.getPreferredSize());
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    

    【讨论】:

    • 你是救生员!非常感谢您提供一些快速、简单的方法来完成我的目标。但是,我认为我措辞不正确,我正在尝试观看 YT 视频以实施修复,但我似乎无法理解问题出在哪里。例如,在您的图片中,我希望表格(以及行/列等)跨越该面板的整个宽度。有没有办法做到这一点?还是我被小桌子困住了?再次,谢谢你。您的解决方案效果很好。
    • 如果您将 JFrame 的尺寸变大(即最大化窗口),它们会跨越。如果您愿意,可以在 for 循环中添加它 tblQuestions.getColumnModel().getColumn(i).setMinWidth(200); 并添加以下 if (tblQuestions.getPreferredSize().width &lt; panelQuestions.getPreferredSize().width) { tblQuestions.setPreferredSize(panelQuestions.getPreferredSize()); } else { panelQuestions.setPreferredSize(tblQuestions.getPreferredSize()); } 而不是 tblQuestions.setPreferredSize(this.panelQuestions.getPreferredSize());
    • 另外,在结束构造函数之前添加pack();,我忘了。
    • 非常感谢您的帮助。碰巧,你是教练吗?非常感谢您的帮助。
    • 不客气!我希望我是一名讲师,几个月前我刚完成本科。
    猜你喜欢
    • 2011-10-25
    • 1970-01-01
    • 2020-02-24
    • 2014-03-29
    • 2012-02-04
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多