Using FlowLayout for the Panel, instead of GridBagLayout,
resizing works properly, as illustrated here with a working applet and source
code modified from Resizing using GridBagLayout
to use FlowLayout instead of GridBagLayout. Reducing the size of the Frame
can be done until one gets to one bar.
The source code for the applet on this page is shown below.
It differs from the code on Resizing using GridBagLayout
only in its use of FlowLayout instead of GridBagLayout and in the lack of any
padding in the line in setBounds:
int barsToShow = height/barHeight;
The source code is shown below and can be downloaded from this link:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class ResizingFlow extends Applet {
public void init()
{
setBackground(Color.yellow);
PoliteFrame frame = new PoliteFrame("A frame");
PanelWithBars panelWithBars = new PanelWithBars();
frame.add(panelWithBars);
frame.setBounds(300, 100, 400, 550);
frame.validate();
frame.show();
}
} // END OF Class ResizingFlow
class PanelWithBars extends Panel {
int barsShowing, maxBars, barHeight, pad;
Bar[] bar;
PanelWithBars()
{
setLayout(new FlowLayout());
barsShowing = maxBars = 4;
barHeight = 100;
pad = 5;
bar = new Bar[maxBars];
for (int i=0; i<maxBars; i++)
{
bar[i] = new Bar(barHeight);
add(bar[i]);
}
}
public void setBounds(int x, int y, int width, int height)
{
int barsToShow = height/barHeight;
if (barsToShow > maxBars) barsToShow = maxBars;
if (barsToShow < barsShowing) for (int i = barsToShow; i<barsShowing; i++) remove(bar[i]);
else if (barsToShow > barsShowing) for (int i = barsShowing; i<barsToShow; i++) add(bar[i]);
barsShowing = barsToShow;
super.setBounds(x, y, width, height);
}
} // END OF Class PanelWithBars
class PoliteFrame extends Frame implements WindowListener
{
PoliteFrame(String s)
{
super(s);
addWindowListener(this);
}
public void windowOpened(WindowEvent we){}
public void windowClosed(WindowEvent we){}
public void windowIconified(WindowEvent we){}
public void windowDeiconified(WindowEvent we){}
public void windowActivated(WindowEvent we){}
public void windowDeactivated(WindowEvent we){}
public void windowClosing(WindowEvent we)
{
if (we.getSource() == this)
{
setVisible(false);
dispose();
}
}
} // END OF Class PoliteFrame
final class Bar extends Canvas {
int width;
int height;
Bar(int height)
{
this.height = height;
}
public void addNotify()
{
super.addNotify();
repaint();
}
public final void paint(Graphics g)
{
width = getSize().width;
g.setColor(Color.blue);
g.fillRect(0, 0, width, height);
}
public final Dimension getMinimumSize()
{
return(new Dimension(10, height));
}
public final Dimension getPreferredSize()
{
return(new Dimension(300, height));
}
} // END OF Class Bar