2017-05-30 71 views
-1

我已经搜索了一段时间,但我没有找到我要找的东西。我正在尝试构建一个简单的GUI,其中我的contentPane包含一个带有GridLayout的JPanel。Java Swing:n x m GridLayout,例如[n-1,m-1] =绿色

我想要一个表示3x3的网格,并用绿色背景jpanel填充右下角的单元格。其余的细胞现在应该是白色的。我如何实现这一目标?

我知道我可以for-loop并用white-background-jpanels填充所有其他单元格。但对于其他项目来说这是不可行的。什么是适当/非骇人的方式来做到这一点?我只想要一个网格,我可以说“看,这是N×M,现在我只想填补,例如第3行第4列”

+4

您是否在所有单元中都有'JPanels'?你可以有一个'JPanel'的'nxm'的数组,它被添加到'GridLayout'中,然后你可以直接访问'grid [n] [m]'JPanel'并设置它的颜色。 –

+0

这听起来很直截了当。你有什么尝试?向我们展示您的代码!它以什么方式失败? –

+1

在我看来,问题是你的代码是如何确定行和列的数量,以便它可以使用右下角单元格的正确索引。如何做到这一点,没有上下文我们就无法分辨。也许你可以[创建一个最小,完整和可验证的例子](https://stackoverflow.com/help/mcve)? –

回答

1

好吧,我知道了:))谢谢Sanket Makani,我遵循你的想法! 现在我可以在我的网格中修改任何我想要的字段。以下是完整的代码示例:

import java.awt.event.*; 
import java.awt.*; 
import javax.swing.*; 


public class Test { 

    public static void main(String[] args) { 

     // frame 
     JFrame frame = new JFrame("Pedigree Builder"); 
     frame.setPreferredSize(new Dimension(400, 300)); 

     // menu bar 
     JMenuBar menubar = new JMenuBar(); 
     frame.setJMenuBar(menubar); 

     // "file" menu 
     JMenu fileMenu = new JMenu("File"); 
     menubar.add(fileMenu); 

     // exit button for "file" menu 
     JMenuItem exitMenuItem = new JMenuItem("Exit"); 
     exitMenuItem.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent event) { 
       System.exit(0); 
      } 

     }); 
     fileMenu.add(exitMenuItem); 

     // content pane = grid 
     JPanel contentPane = new JPanel(new GridLayout(0, 3)); 
     frame.setContentPane(contentPane); 

     // init array of fields for the grid 
     JPanel[] fieldArray = new JPanel[9]; 
     for (int i = 0; i < fieldArray.length; i++){ 
      fieldArray[i] = new JPanel(); 
      contentPane.add(fieldArray[i]); 
     } 

     // modify content of particular cell (in this case: bottom right) 
     fieldArray[8].setBackground(Color.green); 

     frame.pack(); 
     frame.setVisible(true); 

    } 

}