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.
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.