None of the standard layout managers provide this functionality directly.
Check out the Relative Layout. It will allocate space to each component as a percentage of the total space available. The allocation will change dynamically as the available space changes.
Basic logic:
RelativeLayout rl = new RelativeLayout(RelativeLayout.X_AXIS);
JPanel panel = new JPanel( rl );
panel.add(smallLabel, new Float(3));
panel.add(largeLabel, new Float(7));
Using the standard layout managers you might be able to use the BoxLayout
. It respects the "maximum" size of components, so you might be able to override the getMaximumSize()
size method to do what you want.
Something like:
import java.awt.*;
import javax.swing.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
setLayout( new BoxLayout(this, BoxLayout.X_AXIS) );
JLabel small = new JLabel("some long text that will get truncated")
{
@Override
public Dimension getMaximumSize()
{
Dimension size = getParent().getSize();
Dimension maximum = super.getMaximumSize();
maximum.width = (int)(size.width * .3);
return maximum;
}
};
small.setOpaque(true);
small.setBackground(Color.YELLOW);
add(small);
JLabel large = new JLabel("text")
{
@Override
public Dimension getMaximumSize()
{
Dimension size = getParent().getSize();
Dimension maximum = super.getMaximumSize();
maximum.width = (int)(size.width * .7);
return maximum;
}
};
large.setOpaque(true);
large.setBackground(Color.ORANGE);
add(large);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
}
}