在Java中设置按钮的位置和大小 [英] setting a position and size for buttons in java
问题描述
我正在制作项目(周期表),但Swing和GridBagLayout有点问题,即当我想要更大的按钮时,什么也没有改变,或者我得到了占用我整个屏幕的按钮.为什么?我怎样才能使其稍大一些?以及如何将按钮设置为不在中心? 我的代码(我正在使用Swing和GridBagLayout):
I'm making project (periodic table) and have a little problem with Swing and GridBagLayout, i.e. when I want to get little bigger buttons, nothing changes or I get buttons that takes all of my screen. Why? How can I get it slightly bigger? And how can I set the buttons to NOT be in center? My code (I'm using Swing and GridBagLayout):
GridBagConstraints c = new GridBagConstraints();
JButton H,He,Li,Be,B,C,N,O,F,Ne;
public MyPanel() {
setPreferredSize(new Dimension(500,500));
setBackground(Color.GREEN);
setLayout(new GridBagLayout());
//Wodór
H=new JButton("H");
c.anchor=GridBagConstraints.FIRST_LINE_START;
c.weightx=1;
c.weighty=1;
c.gridwidth=2;
c.gridheight=2;
c.gridx=0;
c.gridy=0;
add(H,c);
//Hel
He=new JButton("He");
c.anchor=GridBagConstraints.FIRST_LINE_END;
c.gridx=34;
add(He,c);
//Lit
Li=new JButton("Li");
c.weighty=0;
c.gridx=0;
c.gridy=2;
add(Li,c);
//Beryl
Be=new JButton("Be");
c.gridx=2;
add(Be,c);
//Bar
B=new JButton("B");
c.gridx=24;
add(B,c);
//Węgiel
C=new JButton("C");
c.gridx=26;
add(C,c);
//Azot
N=new JButton("N");
c.gridx=28;
add(N,c);
//Tlen
O=new JButton("O");
c.gridx=30;
add(O,c);
//Fluor
F=new JButton("F");
c.gridx=32;
add(F,c);
//Neon
Ne=new JButton("Ne");
c.gridx=34;
add(Ne,c);
}
}
推荐答案
这是我从DuckDuckGo获得的元素周期表的图片.
Here's a picture of the Periodic Table that I got from DuckDuckGo.
看表,我建议在底部建议两个GridLayouts
,一个用于元素,一个用于两个系列.您必须使用虚拟JPanels
填充元素GridLayout
的空白部分.
Looking at the table, I'd suggest two GridLayouts
, one for the elements and one for the two series at the bottom. You'd have to use dummy JPanels
to fill out the empty portion of the elements GridLayout
.
我还建议您创建一个模型JPanel
来代替元素JButtons
,以保存元素的缩写,元素名称,原子序数和原子量.您将为每个元素创建模型JPanel
的实例.
I'd also suggest that instead of JButtons
, you create a model JPanel
to hold the element abbreviation, element name, atomic number, and atomic weight. You'd create an instance of the model JPanel
for each element.
通过使用模型JPanels
,您可以更轻松地为背景着色.
By using the model JPanels
, you can more easily color the background.
这篇关于在Java中设置按钮的位置和大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!