Swing レイアウト 3
ナビゲーションに移動
検索に移動
Swing レイアウト 3
Swing |
LayoutManagerのカスタマイズ
ソースコード
import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.UIManager; @SuppressWarnings("serial") public class LayoutTest3 extends JFrame { /** * Custom layout test * @see http://java.sun.com/docs/books/tutorial/uiswing/layout/custom.html */ public void testCustomLayout() { JFrame frame = new JFrame("Custom Layout Test"); Container pane = frame.getContentPane(); pane.setLayout(new ZigzagLayout()); for (int i=0; i<25; i++) { pane.add(new JButton(String.valueOf(i))); } frame.pack(); frame.setVisible(true); } /** * カスタマイズした、LayoutManager */ class ZigzagLayout implements LayoutManager { public void addLayoutComponent(String name, Component comp) {} public void removeLayoutComponent(Component comp) {} public Dimension minimumLayoutSize(Container parent) { return new Dimension(300,150); } public Dimension preferredLayoutSize(Container parent) { return new Dimension(300,150); } public void layoutContainer(Container parent) { int compCnt = parent.getComponentCount(); int x = 0; int y = 0; int width = 25; int height = 25; boolean isDown = true; for (int i=0; i<compCnt; i++) { Component c = parent.getComponent(i); if (c.isVisible()) { if (i > 0) { if (i % 5 == 0) { isDown = !isDown; } if (isDown) { y += height; } else { y -= height; } x += width / 2; } c.setBounds(x, y, width, height); } } } } /* ******* 以下メニュー用 ********* */ public LayoutTest3() { setTitle("Layout Test 2"); JButton btn1 = new JButton("custom"); btn1.addActionListener(new MyActionListener("custom")); JPanel pane = new JPanel(); pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); pane.add(btn1); getContentPane().add(pane); pack(); } class MyActionListener implements ActionListener { private String type = null; public MyActionListener(String type) { this.type = type; } public void actionPerformed(ActionEvent e) { if ("custom".equals(this.type)) { testCustomLayout(); } } } public static void main(String[] args) { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); } catch (Exception e) { e.printStackTrace(); } SwingUtilities.invokeLater( new Runnable() { public void run() { LayoutTest3 lt = new LayoutTest3(); lt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); lt.setVisible(true); } } ); } }
© 2006 矢木浩人