2010-04-22 198 views
1

我正在爲通訊錄編寫基本佈局,我想知道如何讓3個測試按鈕像箭頭按鈕那樣跨越邊緣。JButton佈局問題

private static class ButtonHandler implements ActionListener { 
    public void actionPerformed(ActionEvent e) { 
    System.out.println("Code Placeholder"); 
    } 
} 

public static void main(String[] args) { 

    //down button 
    ImageIcon downArrow = new ImageIcon("down.png"); 
    JButton downButton = new JButton(downArrow); 
    ButtonHandler downListener = new ButtonHandler(); 
    downButton.addActionListener(downListener); 

    //up button 
    ImageIcon upArrow = new ImageIcon("up.png"); 
    JButton upButton = new JButton(upArrow); 
    ButtonHandler upListener = new ButtonHandler(); 
    upButton.addActionListener(upListener); 

    //contacts 
    JButton test1Button = new JButton("Code Placeholder"); 
    JButton test2Button = new JButton("Code Placeholder"); 
    JButton test3Button = new JButton("Code Placeholder"); 

    Box box = Box.createVerticalBox(); 
    box.add(test1Button); 
    box.add(test2Button); 
    box.add(test3Button); 

    JPanel content = new JPanel(); 
    content.setLayout(new BorderLayout()); 
    content.add(box, BorderLayout.CENTER); 
    content.add(downButton, BorderLayout.SOUTH); 
    content.add(upButton, BorderLayout.NORTH); 

    JFrame window = new JFrame("Contacts"); 
    window.setContentPane(content); 
    window.setSize(400, 600); 
    window.setLocation(100, 100); 
    window.setVisible(true); 

} 
+1

你有沒有考慮使用網格佈局(http://java.sun.com/docs/books/tutorial/uiswing/layout/grid.html )? – kloffy 2010-04-22 23:17:50

+0

是的,我嘗試過,當我設置它會拋出一個AWTError,因爲我認爲盒默認爲BoxLayout。 setLayout(LayoutManager l) 拋出AWTError,因爲Box只能使用BoxLayout。 從http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/Box.html – 2010-04-22 23:22:37

+2

我認爲@kloffy建議您將「Box」轉換爲「JPanel」爲佈局管理器使用'GridLayout'。 – Ash 2010-04-22 23:30:30

回答

1

上@ kloffy的建議跟進:

package playground.tests; 

import java.awt.GridLayout; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

import junit.framework.TestCase; 

public class ButtonTest extends TestCase { 

    public void testThreeButtons() throws Exception { 
      JPanel panel = new JPanel(); 
      panel.setLayout(new GridLayout()); 
      JButton button1 = new JButton("A"); 
      JButton button2 = new JButton("B"); 
      JButton button3 = new JButton("C"); 
      panel.add(button1); 
      panel.add(button2); 
      panel.add(button3); 

      JFrame window = new JFrame("Contacts"); 
      window.setContentPane(panel); 
      window.setSize(300, 600); 
      window.pack(); 
      window.setVisible(true); 
      int width = button1.getWidth(); 
      assertEquals(width, button2.getWidth()); 
      assertEquals(width, button3.getWidth()); 
    } 
}