how to put a component at the center of other component that sit in a JPanel

僤鯓⒐⒋嵵緔 提交于 2019-12-13 04:09:38

问题


I wondered how do I put a JLabel or a JPanel at the center of a JTable that Sit in a JPanel. I saw one example with BufferedImage but I could not convert it for some resone, here is the example link: Put JLabel on Component in JPanel

I put also an image to show what I mean. Press to see the result I need by the way this is how it looks like when I uses windows 8 now... any idea ?


回答1:


You can add any component directly to the table (this is how an editor works).

You just need to set the size/location of the component:

JLabel label = new JLabel( "Please Wait" );
label.setSize( label.getPreferredSize() );
label.setLocation(20, 20);
table.add( label );
table.repaint();

Or you could use the JLayer class to decorate the JTable. Read the section from the Swing tutorial on How to Decorate Components With the JLayer Class for more information and working examples.

Edit:

A simple example of a proper MCVE"

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

public class PleaseWait extends JPanel
{
    PleaseWait()
    {
        JTable table = new JTable(5, 5);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        add( new JScrollPane( table ) );

        JLabel label = new JLabel("Please Wait");
        label.setOpaque(true);
        label.setBackground(Color.LIGHT_GRAY);
        label.setBorder( new EmptyBorder(10, 10, 10, 10) );
        label.setSize( label.getPreferredSize() );
        label.setLocation(150, 20);
        table.add( label );
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("PleaseWait");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new PleaseWait());
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args) throws Exception
    {
        EventQueue.invokeLater( () -> createAndShowGUI() );
/*
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
*/
    }
}


来源:https://stackoverflow.com/questions/52884348/how-to-put-a-component-at-the-center-of-other-component-that-sit-in-a-jpanel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!