2014-12-27 163 views
0

我研究了如何更改JFrame上显示的jbutton的大小。JButton不改变尺寸

我想都button.setSize(200,200)和button.setPreferredSize(新维(200,200)),但它不会改变。下面的代码:

import java.awt.Color; 
import java.awt.Dimension; 

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

public class Index extends JFrame{ 
    private String title = "This is the motherfucking title"; 
    Dimension dim = new Dimension(500,500); 

    public Index(){ 
     this.setResizable(false); 
     this.setTitle(title); 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     this.setSize(dim); 
     this.getContentPane().setBackground(Color.BLACK); 

     JButton button = new JButton("Button"); 
     button.setSize(200,200); 
     this.add(button); 

    } 


    public static void main(String args[]){ 
     Index ih = new Index(); 
     ih.setVisible(true); 
    } 
} 

这里的结果:http://i.imgur.com/Llj0pfo.png

我在做什么错?

回答

0

试试这个:

JButton button = new JButton("Button"); 
    button.setSize(200,200); 
    getContentPane().setLayout(null); 
    getContentPane().add(button); 
    setVisible(true); 

您的构造函数中。

+1

谢谢!这工作:) – Arcthor

0

使用SwingUtilities.invokeLater();在里面创建你的Index(),然后在构造函数的末尾调用setVisible(true);。同时记住默认JFrame使用BorderLayout

SwingUtilities.invokeLater(new Runnable() 
    { 
     public void run() 
     { 
     new Index(); 
     } 
    }); 
+0

我不太明白,但谢谢! – Arcthor

1
this.add(button); 

您要添加的按钮帧的内容窗格中。默认情况下,内容使用BorderLayout,并将组件添加到CENTER。添加到CENTER的任何组件都会自动获取帧中可用的额外空间。由于您将帧的大小设置为(500,500),因此可用空间很多。

作为一般规则,您不应该尝试设置组件的preferred size,因为只有组件知道应该多大才能正确绘制自己。所以你的基本代码应该是:

JButton button = new JButton("..."); 
frame.add(button); 
frame.pack(); 
frame.setVisible(true); 

现在按钮将处于其首选大小。但是,如果调整帧大小,该按钮将更改大小。如果你不想要这种行为,那么你需要使用不同的Layout Manager

+0

谢谢您提供非常丰富的答复 – Arcthor