我的应用程序遇到问题。我希望动态创建几个“选项卡式”滚动 Pane ,其中包含半大量称为“ImageLabels”的对象,这些对象只是带有(您猜对了)图像的标签。
我的大部分 gui 都是在 Netbeans 中制作的,因为它是半复杂的,而且我自己也不太懂。
我的问题是这样的:当添加滚动 Pane 对象(包含带有 GridLayout 的 JPanel)时,以及在尝试将图像标签添加到带有布局的 JPanel 后(我的构造函数设置为“new GridLayout(0, 5)” , 5, 5);"无限行、5 列、5 pxls 的空间。)没有显示任何内容,滚动面板也不会进入“滚动”模式。
我完全不知所措,一整天都在尝试不同的布局。这是我的一些代码...
ImageLabel 对象的构造函数..
addMouseListener(this);
setVisible(true);
setPreferredSize(new Dimension(32, 32));
如何设置我的tileHolderPanel JPanel(包含ImageLabels的面板)
myLayout = new GridLayout(0, 5, 5, 5);
tileHolderPanel.setLayout(myLayout);
构建完我希望添加到每个面板的所有 ImageLabels 后,我只需这样做
tileHolderPanel.add(label);
如果重要的话,我的 TileHolderPanel 位于 JPanel 内的滚动 Pane 内,并且它们具有 Netbeans 生成的默认 GroupLayouts。
谢谢你, -卢克
最佳答案
这是一个可以用来比较您的代码的工作示例。
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.GroupLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
/** @see http://stackoverflow.com/questions/7801870 */
public class ScrollGroup extends JPanel {
private static final int N = 8;
private static final int NN = N * N;
private static final int GAP = 5;
private static final int SIZE = 32;
public ScrollGroup() {
this.setLayout(new GridLayout(N, N, GAP, GAP));
for (int i = 0; i < NN; i++) {
JLabel label = new JLabel();
label.setOpaque(true);
label.setBackground(Color.getHSBColor((float) i / NN, 1, 1));
label.setPreferredSize(new Dimension(SIZE, SIZE));
this.add(label);
}
}
private void display() {
JFrame f = new JFrame("ScrollGroup");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane sp = new JScrollPane(this);
GroupLayout layout = new GroupLayout(f.getContentPane());
f.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setHorizontalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup().addComponent(sp)));
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup().addComponent(sp)));
f.pack();
f.setSize(N * SIZE, N * SIZE);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ScrollGroup().display();
}
});
}
}
关于java - 布局管理器和滚动 Pane 的一些问题,不显示对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7801870/