java设置按钮位置,在Java中设置按钮的位置和大小

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);

}

}

解决方案

Here's a picture of the Periodic Table that I got from DuckDuckGo.

hmXqg.jpg

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.

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.

By using the model JPanels, you can more easily color the background.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值