2017-06-07 82 views
-2
// Creating buttons 
JButton b1 = new JButton(); 
    b1.setText("Add"); 
    b1.setSize(100, 130); 
    b1.setLocation(330, 70); 
    b1.setBackground(Color.red); 
    b1.setVisible(true); 

// Creating second button  
JButton b2 = new JButton(); 
    b2.setText("Add"); 
    b2.setSize(100,100); 
    b2.setLocation(0, 0); 
    b2.setBackground(Color.blue); 
    b2.setVisible(true); 

//adding buttons to Jframe 
f.add(b1); 
f.add(b2); 

,当我运行的程序或有时,它们出现的按钮不出现,但占据整个JFrame完全按钮没有出现在JFrame的

+1

1)为了更好地帮助去更快地发布[MCVE]或[简短,独立,正确的示例](http://www.sscce.org/)。 2)Java GUI必须在不同的语言环境中使用不同的PLAF来处理不同的操作系统,屏幕大小,屏幕分辨率等。因此,它们不利于像素的完美布局。请使用布局管理器或[它们的组合](http://stackoverflow.com/a/5630271/418556)以及[white space]的布局填充和边框(http://stackoverflow.com/a/17874718/ 418556)。 3)设置BG颜色在某些外观和感觉上会失败。解决方案:改为使用彩色图标。 4)为什么.. –

+0

..做这两个按钮有相同的文字? 5)'b2.setVisible(true);'只对像JFrame','JWindow','JDialog'等顶级容器是必需的。 –

回答

2

竞猜#1

几乎一样关于这个问题的所有问题,您呼叫f.setVisible(true)之前,您添加组件到UI

所以,这样的事情应该修复它

// In some other part of your code you've not provided us 
//f.setVisible(true); 

JButton b1 = new JButton(); 
b1.setText("Add"); 
b1.setBackground(Color.red); 

JButton b2 = new JButton(); 
b2.setText("Add"); 
b2.setBackground(Color.blue); 

f.add(b1); 
f.add(b2); 
f.setVisible(true); 

竞猜#2

你不能改变JFrame的默认布局管理器,所以它依然使用的是BorderLayout

像这样的东西应该至少让互不重叠,

要显示的两个按钮
f.setLayout(new FlowLayout()); 
f.add(b1); 
f.add(b2); 
f.setVisible(true); 

我会建议花一些时间,通过Laying out Components within a Container更多细节

+0

我猜想最后一个,因为他提到_“按钮[.. 。]完全占用整个Jframe“_ – AxelH