我有一个由两个以上GridLayouts(8,4)组成的GridLayout(2,1)。我在主JFrame中添加了(2,1)布局,但是当我运行它时,仅显示8,4布局之一。我想发生的事情是两者都堆叠在一起。
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Pos extends JFrame {
JTextField oneTicks;
JTextField twoTicks;
JTextField threeTicks;
JTextField fiveTicks;
JTextField tenTicks;
JTextField twentyTicks;
JTextField twentyFiveTicks;
JTextField thirtyTicks;
JTextField[] ticks = { oneTicks, twoTicks, threeTicks, fiveTicks, tenTicks,
twentyTicks, twentyFiveTicks, thirtyTicks };
JTextField oneAmount;
JTextField twoAmount;
JTextField threeAmount;
JTextField fiveAmount;
JTextField tenAmount;
JTextField twentyAmount;
JTextField twentyFiveAmount;
JTextField thirtyAmount;
JTextField[] amounts = { oneAmount, twoAmount, threeAmount, fiveAmount,
tenAmount, twentyAmount, twentyFiveAmount, thirtyAmount };
JLabel oneLabel = new JLabel("$ 1 Games");
JLabel twoLabel = new JLabel("$ 2 Games");
JLabel threeLabel = new JLabel("$ 3 Games");
JLabel fiveLabel = new JLabel("$ 5 Games");
JLabel tenLabel = new JLabel("$ 10 Games");
JLabel twentyLabel = new JLabel("$ 20 Games");
JLabel twentyFiveLabel = new JLabel("$ 25 Games");
JLabel thirtyLabel = new JLabel("$ 30 Games");
JLabel[] gameLabel = { oneLabel, twoLabel, threeLabel, fiveLabel, tenLabel,
twentyLabel, twentyFiveLabel, thirtyLabel };
JLabel oneXLabel = new JLabel("X $ 1");
JLabel twoXLabel = new JLabel("X $ 2");
JLabel threeXLabel = new JLabel("X $ 3");
JLabel fiveXLabel = new JLabel("X $ 5");
JLabel tenXLabel = new JLabel("X $ 10");
JLabel twentyXLabel = new JLabel("X $ 20");
JLabel twentyFiveXLabel = new JLabel("X $ 25");
JLabel thirtyXLabel = new JLabel("X $ 30");
JLabel[] multiLabel = { oneXLabel, twoXLabel, threeXLabel, fiveXLabel,
tenXLabel, twentyXLabel, twentyFiveXLabel, thirtyXLabel };
Pos() {
initJTextField(ticks);
initJTextField(amounts);
JPanel lottoPanel = new JPanel(new GridLayout(2, 1));
JPanel startGrid = new JPanel(new GridLayout(8, 4));
JPanel endGrid = new JPanel(new GridLayout(8, 4));
initLottoPanel(startGrid);
initLottoPanel(endGrid);
lottoPanel.add(startGrid);
lottoPanel.add(endGrid);
this.add(lottoPanel, BorderLayout.LINE_START);
}
// init all JTextfields
void initJTextField(JTextField[] jArray) {
for (int i = 0; i < ticks.length; i++) {
jArray[i] = new JTextField();
}
}
void initLottoPanel(JPanel panel) {
for (int i = 0; i < gameLabel.length; i++) {
panel.add(gameLabel[i]);
panel.add(ticks[i]);
panel.add(multiLabel[i]);
panel.add(amounts[i]);
}
}
public static void main(String[] args) {
Pos pos = new Pos();
pos.setSize(600, 600);
pos.setLocationRelativeTo(null);
pos.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pos.pack();
pos.setVisible(true);
}
}
最佳答案
两个面板都被添加到JFrame中,但是其中之一完全是空的。当调用initLottoPanel方法时,实际上是将所有子组件(JLabels,JTextFeild等)重新分配给正在传递的新面板。
要解决此问题,您需要具有两组子组件,每组仅对应一个面板。