2015-11-26 65 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

相关问题