Home > Enterprise >  How to include a JTable and some text below the table in JOptionPane.showMessageDialog, in Java
How to include a JTable and some text below the table in JOptionPane.showMessageDialog, in Java

Time:07-08

I am trying to include a JTable in JOptionPane.showMessageDialog and adding some more text below the table. To do so, I have tried next code:

import javax.swing.JOptionPane;
import javax.swing.*;
public class TextInTable {

    public static void main(String[] args) {
            String[][] rowValues = {
                {"1","2","3"}
            };
            String[] columnNames = {
                "A","B", "C"
            };
            JTable table = new JTable(rowValues, columnNames);
            JOptionPane.showMessageDialog(null, new JScrollPane(table)  "\n"  "I need to add some text here \n"   "and here”); 
    }

}

However, the JTable does not show correctly if I put this code ( "\n" "I need to add some text here \n" "and here”) after the table.

This is what I am trying to do:

enter image description here

Any idea about how to solve it? Thanks in advance.

CodePudding user response:

You need to create your own JPanel the way you want it with the components you would like and then pass that panel to the JOptionPane. Below I provide a runnable demo of this. Read all the comments in code as they explain what is going on. You can delete them later if you like. Here is what it produces on Screen:

enter image description here

Here is the runnable code:

package joptionpanewithjtabledemo;


public class JOptionPaneWithJTableDemo {

  
    public static void main(String[] args) {
        // Application started this way to avoid the need for statics.
        new JOptionPaneWithJTableDemo().startApp(args);
    }
    
    private void startApp(String[] args) {
        /* Create a JDialog box to use as a parent for the JOptionPane
           just in case the JOptionPane has no parent and needs to be
           displyed on top of a window that has its own ON TOP property 
           set to true and the JOptionPane's parent property is set to 
           null. If this is the case then the message box will be hidden 
           behind it! If your JOptionPane will be displayed on an actual  
           parent window then use that window's variable name as parent. 
           You can then delete anything in code related to iDialog.
        */
        javax.swing.JDialog iDialog = new javax.swing.JDialog();
        iDialog.setAlwaysOnTop(true); 
        iDialog.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        iDialog.setLocationRelativeTo(null);
        
        // Create a JPanel to display within the JOptionPane MessageBox //
        javax.swing.JPanel panel = new javax.swing.JPanel();
        
        // Size the Panel to what you want to hold the JTable and JLabel
        panel.setPreferredSize(new java.awt.Dimension(400, 250));
        panel.setLayout(new java.awt.BorderLayout()); // Set BorderLayout as the layout manager
        
        // JTable Column Names
        Object[] columnNames = {"A", "B", "C"};
        // Some fictitious data for the JTable...
        Object[][] data = {
            {1000, 2000, 3000}, {1001, 2001, 3001}, {1002, 2002, 3002},
            {1003, 2003, 3003}, {1004, 2004, 3004}, {1005, 2005, 3005}, 
            {1006, 2006, 3006}, {1007, 2007, 3007}, {1008, 2008, 3008},
            {1009, 2009, 3009}, {1010, 2010, 3010}, {1011, 2011, 3011},
        };
        
        // Declare a JTable and initialize with the table data and column names.
        javax.swing.JTable table = new javax.swing.JTable(data, columnNames);
        
        /* Align JTable Header Text to Center.
           Alignment options are: Align_LEFT (2), Align_CENTER (0), Align_RIGHT (4),
           Align_LEADING (10), or Align_TRAILING (11)       */
        int alignType = 0;
        for (int i = 0; i < table.getColumnCount(); i  ) {
            table.getTableHeader().getColumnModel().getColumn(i)
                    .setHeaderRenderer(new HeaderRenderer(table, alignType));
        }

        // Declare a JScrollPane and place the JTable into it.
        javax.swing.JScrollPane tableScrollPane = new javax.swing.JScrollPane(table);
        // Ensure the ScrollPane size.
        tableScrollPane.setPreferredSize(new java.awt.Dimension(400, 200));
        panel.add(tableScrollPane, java.awt.BorderLayout.NORTH); // Add the scrollpane to top of panel.
        
        /* Use basic HTML to create you message text. Gives you more
           flexability towards how your message will look.        */
        String msg = "<html><font size='4'>I need to add some text "
                     "<font color=blue>here</font><center>and right "
                     "<font color=red>here</font>!</center></html>";
        javax.swing.JLabel msgLabel = new javax.swing.JLabel(msg);
        // Set the initial text alignment in the JLabel.
        msgLabel.setHorizontalAlignment(javax.swing.JLabel.CENTER);
        //msgLabel.setBorder(BorderFactory.createLineBorder(Color.blue, 1));
        // Ensure label width and desired height.
        msgLabel.setPreferredSize(new java.awt.Dimension(panel.getWidth(), 50));
        panel.add(msgLabel, java.awt.BorderLayout.SOUTH); // add label to bottom of panel.
        
        // Display The Message Box...
        javax.swing.JOptionPane.showMessageDialog(iDialog, panel, "My Table Message Box", 
                                         javax.swing.JOptionPane.INFORMATION_MESSAGE);
        iDialog.dispose();
    }
    
    // Inner class - A Header cell renderer class for header text alignment options.
    class HeaderRenderer implements javax.swing.table.TableCellRenderer {

    javax.swing.table.DefaultTableCellRenderer renderer;
    int horAlignment;

    HeaderRenderer(javax.swing.JTable table, int horizontalAlignment) {
        horAlignment = horizontalAlignment;
        renderer = (javax.swing.table.DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer();
    }

    @Override
    public java.awt.Component getTableCellRendererComponent(javax.swing.JTable table, Object value,
                                    boolean isSelected, boolean hasFocus, int row, int col) {
        java.awt.Component c = renderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
        javax.swing.JLabel label = (javax.swing.JLabel) c;
        label.setHorizontalAlignment(horAlignment);
        return label;
    }
}
    
}
  • Related