JTable 不改变外观

JTable not changing appearance

你好,早上好,

我请求帮助正确设置 JTable 的样式。我是 Java GUI 的新手,因此我很难让它正常工作。

我的目标是尝试尽可能地重新创建 Jeopardy 计分板。

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

  1. 试图将所有数据(包括 headers)集中在 table
  2. 正在尝试更改 header 字体颜色和背景
  3. 正在尝试扩展 table 以适应它所在的 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                   
}

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

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);
    }

I am very new to Java GUIs

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

1.Trying to center all data (including headers) in the table

tblQuestions.setDefaultRenderer(Integer.class, centerRenderer);

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

然而,即使这样还不够。您现在需要通过将 TableModel 的 getColumnClass(...) 方法重写为 return Integer.class.

来告诉 table 每列中的数据类型

然而,最简单的解决方案是您的代码,所以请使用:

tblQuestions.setDefaultRenderer(Object.class, centerRenderer);

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

对于页眉,您需要访问默认渲染器以更改对齐方式:

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

2.Trying to change the header font color and background

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

也许这篇文章会有所帮助:Nimbus - override color for TableHeader

3.Trying to extend the table to fit the full frame of the JPanel it is in

table 的首选大小基于 table 中每行的高度。这个高度不会动态变化。如果你想让每一行的高度更大,那么使用:

table.setRowHeight(32);

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

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

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