Created
March 25, 2020 19:52
-
-
Save sedran/a7fc0e6b1cdb8021b64accd0550e64b4 to your computer and use it in GitHub Desktop.
A custom java.awt.LayoutManager implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* AltAlta.java | |
* for the example code, click the link below: | |
* http://pastebin.com/AUNZqL58 | |
* Serdar KUZUCU - http://blog.asosyalbebe.com | |
* Java'da Kendi LayoutManager'ımızı Yaratalım | |
* http://serdarkuzucu.com/java-swing-custom-layoutmanager | |
*/ | |
package sedran.layoutManagers; | |
import java.awt.Component; | |
import java.awt.Container; | |
import java.awt.Dimension; | |
import java.awt.Insets; | |
import java.awt.LayoutManager; | |
public class AltAlta implements LayoutManager { | |
// Space between Components | |
private int gap = 5; | |
// Default border width | |
private int myInsets = 5; | |
public AltAlta() {} | |
public AltAlta(int gap) { | |
this.gap = gap; | |
} | |
public void addLayoutComponent(String arg0, Component arg1) {} | |
public void removeLayoutComponent(Component arg0) {} | |
public void layoutContainer(Container parent) { | |
int nComp = parent.getComponentCount(); | |
Dimension d = null; | |
int maxWidth = 0; | |
for(int i=0; i<nComp; i++) { | |
d = parent.getComponent(i).getPreferredSize(); | |
if( d.width > maxWidth ) { | |
maxWidth = d.width; | |
} | |
} | |
Insets borders = parent.getInsets(); | |
int top = borders.top + myInsets; | |
for(int i=0; i<nComp; i++) { | |
Component c = parent.getComponent(i); | |
d = c.getPreferredSize(); | |
c.setBounds(borders.left + myInsets, top, maxWidth, d.height); | |
top += d.height + gap; | |
} | |
} | |
public Dimension minimumLayoutSize(Container parent) { | |
Insets borders = parent.getInsets(); | |
int nComp = parent.getComponentCount(); | |
Dimension d = null; | |
int maxWidth = 0; | |
int sumHeight = 0; | |
for(int i=0; i<nComp; i++) { | |
d = parent.getComponent(i).getPreferredSize(); | |
if( d.width > maxWidth ) { | |
maxWidth = d.width; | |
} | |
sumHeight += d.height; | |
} | |
int height = sumHeight + borders.top + myInsets*2 + borders.bottom + gap*(nComp-1); | |
int width = maxWidth + borders.left + borders.right + myInsets*2; | |
return new Dimension(width, height); | |
} | |
public Dimension preferredLayoutSize(Container parent) { | |
return minimumLayoutSize(parent); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment