简体   繁体   中英

Swing - how to add a band of color on application window

I am very new to using swing for java development, and only had experience with coding in java and never creating a GUI. Done some reading and made a decision to go with Swing.

Now i need to setup my application window, i would like the window to be a particular color, with 2 bands of another color along to top and bottom, with additional areas within the window to be another color again.

Can anyone give me some tips on how i would go about this?

Thanks

Almost always you will want to have a BorderLayout as a first step in representing your application.

You can create JPanels , set their background colors, and then with BorderLayout add them North and South.

Make sure you set minimum height on the JPanel to something or you won't see anything. If you want two JPanels on top of each other (on the top and bottom), then you could embed a Borderlayout in the north, and one in the south, each one have a panel north, and one south.

As long as the height has been defined correctly for the JPanel then it should work.

As already stated, you can create a tree-like hierarchy of panels (components) that each set their background color to whatever you want. The downside with this approach is that it will be more difficult to place components over this tree. However, you can always override JPanel paintComponent to paint whatever you want. For example:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Test extends JFrame
{
    public Test()
    {
        super( "Test" );

        JPanel mainPanel = new BackgroundPanel();
        mainPanel.setPreferredSize( new Dimension( 400, 300 ) );

        getContentPane().add( mainPanel );
        pack();
        setLocationRelativeTo( null );
        setDefaultCloseOperation( EXIT_ON_CLOSE );

        setVisible( true );
    }

    public static void main( String[] args )
    {
        SwingUtilities.invokeLater( new Runnable() 
        {
            @Override
            public void run()
            {
                new Test();    
            }
        });
    }

}

class BackgroundPanel extends JPanel
{
    @Override
    protected void paintComponent( Graphics g )
    {
        g.setColor( Color.RED );
        g.fillRect( 0, 0, getWidth(), 20 );
        g.setColor( Color.BLUE );
        g.fillRect( 0, getHeight() - 20, getWidth(), 20 );
    }
}

In this case you can add components to the main panel as usual.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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