简体   繁体   English

JTable外观不变

[英]JTable not changing appearance

Hello and good morning, 您好,早上好,

I am requesting help with styling a JTable appropriately. 我正在请求有关样式化JTable的帮助。 I am very new to Java GUIs and thus am having a hell of a time trying to get this to work appropriately. 我对Java GUI非常陌生,因此想让它正常工作真是令人费解。

My objectives are to try and recreate the Jeopardy scoreboard as closely as possible. 我的目标是尝试尽可能重新创建“危险”计分板。

Right now, I am trying to accomplish 3 things: 现在,我正在尝试完成3件事:

  1. Trying to center all data (including headers) in the table 尝试将表中的所有数据(包括标题)居中
  2. Trying to change the header font color and background 尝试更改标题字体的颜色和背景
  3. Trying to extend the table to fit the full frame of the JPanel it is in 尝试扩展表格以适合其所在的JPanel的整个框架

My code is listed below. 我的代码在下面列出。 Any help, feedback, or guidance would be appreciated. 任何帮助,反馈或指导将不胜感激。

/*
 * 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                   
}

I am very new to Java GUIs 我是Java GUI的新手

I would suggest you don't use the IDE to generate your code. 我建议您不要使用IDE生成代码。 You spend time learning the IDE not Swing. 您花时间学习IDE,而不是Swing。 Use the IDE to help compile, debug etc. 使用IDE来帮助编译,调试等。

1.Trying to center all data (including headers) in the table 1.尝试将表格中的所有数据(包括标题)居中

tblQuestions.setDefaultRenderer(Integer.class, centerRenderer);

All the data in the TableModel is String data not Integer data. TableModel中的所有数据都是String数据,而不是Integer数据。 If you want Integer data then you need to add Integer objects to the model. 如果需要整数数据,则需要将整数对象添加到模型中。

However, even that is not enough. 但是,仅此还不够。 You now need to tell the table what type of data is in each column by overriding the getColumnClass(...) method of the TableModel to return Integer.class. 现在,您需要通过重写TableModel的getColumnClass(...)方法以返回Integer.class来告诉表各列中的数据类型。

However the easiest solution as your code stands it so use: 但是,如您的代码所示,最简单的解决方案是使用:

tblQuestions.setDefaultRenderer(Object.class, centerRenderer);

because the default getColumnClass(...) implementation just returns Object.class for all columns. 因为默认的getColumnClass(...)实现只为所有列返回Object.class。

For the header you need to access the default renderer to change the alignment: 对于标题,您需要访问默认渲染器以更改对齐方式:

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

2.Trying to change the header font color and background 2.尝试更改标题字体的颜色和背景

That is an issue with the Nimbus LAF. 这是Nimbus LAF的问题。 The default renderer appears to be ignoring the setBackground() method. 默认渲染器似乎忽略了setBackground()方法。 Not sure how to fix that. 不知道如何解决。

Maybe this posting will help: Nimbus - override color for TableHeader 也许此发布会有所帮助: Nimbus-覆盖TableHeader的颜色

3.Trying to extend the table to fit the full frame of the JPanel it is in 3.尝试扩展表格以适合其所在的JPanel的整个框架

The preferred size of the table is based on the height of each row in the table. 表格的首选大小基于表格中每一行的高度。 This height does not change dynamically. 该高度不会动态变化。 If you want the height of each row to be larger then use: 如果您希望每行的高度更大,请使用:

table.setRowHeight(32);

Also, following up on my initial comment I would not use the IDE to generate the layout code. 另外,按照我的最初评论,我不会使用IDE来生成布局代码。 The GroupLayout is overly complex. GroupLayout过于复杂。 I would simply take advantage of the default BorderLayout of the frame to create the GUI with code something like: 我将简单地利用框架的默认BorderLayout来使用以下代码创建GUI:

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

With simple layout code like that the table will be displayed at the top of the frame at its preferred size. 使用简单的布局代码,表格将以其首选大小显示在框架的顶部。 As the width of the frame is changed the columns will resize. 随着框架宽度的更改,列的大小将重新调整。 Nothing will happen if the frame height is changed, so you may want to make the frame non-resizable to make sure the table always fills the frame. 如果更改框架高度,则什么也不会发生,因此您可能希望使框架不可调整大小,以确保表格始终填充框架。

Here is the code that will fulfill your requirements, change your constructor to the following (there are some comments to help you out): 这是满足您要求的代码,将构造函数更改为以下代码(有一些注释可以帮助您):

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

在此处输入图片说明

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

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