2015-11-26 81 views
0

我想知道如何在代碼中調整'alarmClockButton'的大小,我試過setSize();和setPreferredSize();但是他們都不起作用。我爲此使用了GridBagLayout。有任何想法嗎?調整JButton的大小

public class MainMenu { 

    // JFrame = the actual menu/frame. 
    private JFrame frame; 
    // JLabel = provides text instructions or information on a GUI — 
    // display a single line of read-only text, an image or both text and an image. 
    private JLabel background, logo; 
    // JButton = button. 
    private JButton alarmClockButton; 

    // Constructor to create menu 
    public MainMenu() { 
     frame = new JFrame("Alarm Clock"); 
     alarmClockButton = new JButton("Timer"); 
     alarmClockButton.setPreferredSize(new Dimension(1000, 1000)); 
     // Add an event to clicking the button. 
     alarmClockButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       // TODO: CHANGE TO SOMETHING NICER 
       JOptionPane.showMessageDialog(null, "This feature hasn't been implemented yet.", "We're sorry!", 
         JOptionPane.ERROR_MESSAGE); 
      } 
     }); 
     // Creating the background 
     try { 
      background = new JLabel(new ImageIcon(ImageIO.read(getClass() 
        .getResourceAsStream("/me/devy/alarm/clock/resources/background.jpg")))); 
      logo = new JLabel(new ImageIcon(ImageIO.read(getClass() 
      .getResourceAsStream("/me/devy/alarm/clock/resources/logo.png")))); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     background.setLayout(new GridBagLayout()); 
     frame.setContentPane(background); 
     GridBagConstraints gbc = new GridBagConstraints(); 
     // Inset = spacing between each component 
     gbc.insets = new Insets(15,15, 15, 15); 
     // Positioning 
     gbc.gridx = 0; 
     gbc.gridy = 0; 
     frame.add(logo, gbc); 
     // Positioning 
     // Keep x the same = aligned. On same x-coordinate (think math!) 
     gbc.gridx = 0; 
     // Y = 2 down 
     gbc.gridy = 1; 
     frame.add(alarmClockButton, gbc); 
     frame.setVisible(true); 
     frame.setSize(550, 200); 
     frame.setResizable(false); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     alarmClockButton.setForeground(Color.RED); 
    } 

} 

謝謝!

+0

「不起作用」是什麼意思?你究竟想達到什麼目的?你究竟得到了什麼?更有針對性的說明會有很大的幫助。 –

+0

最好使用不同大小的字體或不同長度的文字,改變圖標的​​大小或更改頁邊距來調整大小。 –

回答

2

您可以通過GridBagConstraints影響按鈕的大小,例如...

使用ipadxipady,這增加了部件preferredSize

gbc.ipadx = 100; 
gbc.ipady = 100; 

可生產類似...

enter image description here

您也可以使用...

gbc.weightx = 1; 
gbc.weighty = 1; 
gbc.fill = GridBagConstraints.BOTH; 

,其改變的空間,該組件將佔用和組件是如何填補內它給細胞量...

Clock

注:

因爲你如果您使用JLabel作爲背景部件,則您將被限制爲標籤的首選尺寸,該尺寸通過icon和計算得出只有屬性,它不會使用佈局管理器來計算這些結果。

+0

完美!這工作。最後一個問題,(不確定是否應該把它放在另一個線程中),但是當我打開程序時,按鈕位於GUI的中心,我怎樣才能將它放在左邊?我試圖讓gridx成爲負面的,但是這給了我一個ArraysOutOfBountException。 – TheCoder24

+0

您可以使用'GridBagConstraints'的'anchor'屬性,但在這種情況下我不會使用'fill'屬性 – MadProgrammer

+0

這很有效,謝謝! – TheCoder24