的目标是显示单元,其中所有单元都彼此独立的表,每个单元有几个可选的显示器(试想一个数谜板,危险板,分机)包含卡布局的网格布局 - 可以完成吗?
这是我在挥杆的第一次尝试。经过大量的阅读,我决定我的方法是首先使用卡片布局(这部分我很满意)独立设计每个单元格,然后将其“包裹”在网格布局中。 这可能是我的地方缺乏基本的Swing理解提高其头:
当设计我创建了一个框架和面板添加到它的每个单元:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Cell extends Component{
JFrame frame = new JFrame();
/* we'll use a card layout with a panel for each look of the cell */
CardLayout cardLayout = new CardLayout();
JPanel containterPanel = new JPanel();
JPanel firstPanel = new JPanel();
JPanel secondPanel = new JPanel();
JPanel thridpanel = new JPanel();
public Cell(){
/* assign the card layout to the container panel */
containterPanel.setLayout(cardLayout);
/* assign objects to the different panels - details not important for the sake of the question */
//....
/* add the different panels to the container panel and show the initial one */
containterPanel.add(firstPanel, "firstPanel");
containterPanel.add(secondPanel, "secondPanel");
containterPanel.add(thridpanel, "thridpanel");
cardLayout.show(containterPanel, "firstPanel");
/* add the container to the frame and display it*/
frame.add(containterPanel);
frame.setVisible(true);
}
}
这很好地表现。 但我试图把它包在一个网格布局,其中每个单元的行为就像这是很笨拙:
import java.awt.*;
public class Board{
private static final int COLUMNS_NUM = 3;
private static final int ROWS_NUM = 3;
JFrame frame = new JFrame();
JPanel panel = new JPanel();
Cell cells[] = new Cell[COLUMNS_NUM * ROWS_NUM];
public Board(){
panel.setLayout(new GridLayout(ROWS_NUM, COLUMNS_NUM));
for (int i = 0; i <ROWS_NUM * COLUMNS_NUM; i++)
{
cells[i] = new Cell();
panel.add(cells[i]);
}
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args) {
new Board();
}
}
我得到的是一堆不相关的帧,从主板框架分离。很明显,我没有正确处理帧(应该只创建一个..?)。 任何帮助引导我到正确的方法将不胜感激。
1)*“网格布局包含卡布局 - 就可以了被做?“是的。 2)为了更快地获得更好的帮助,请发布[MCVE]或[简短,独立,正确的示例](http://www.sscce.org/)。 –
感谢@AndrewThompson,这里相对较新 - 我做了小小的编辑,我相信它现在拥有'最小,完整和可验证'的要求。请让我知道,如果不是。 – yonikes
如果要将单元格添加到Board中,请将它们设置为JPanel而不是JFrame – c0der