无法弄清楚为什么它不起作用,我在gridbag面板中添加了一个空白面板。我在要添加的帧之间添加了JLabel("test")
,只是为了看到正在添加的内容,它不可见?
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Label;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
public class Workspace extends JTabbedPane {
static JFrame frame = new JFrame();
private JPanel grid;
private String text = new String("testing.");
Workspace() {
this.addTab("title", growPanel());
}
public static void main(String[] args) throws IOException {
createAndShowGUI();
}
private JPanel growPanel() {
JPanel gp = new JPanel(false);
gp.setPreferredSize(new Dimension(800,600));
//Add a button that adds my frame
JButton addComponentBtn = new JButton("Add Component");
addComponentBtn.addActionListener(e-> {
try {
addComponent();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
});
gp.add(addComponentBtn, BorderLayout.PAGE_START);
grid = new JPanel(new GridLayout(0, 2, 10, 10)); //any number of rows, 2 columns, H and V gap
JScrollPane sp = new JScrollPane(grid);
sp.setPreferredSize(new Dimension(800,600));
gp.add(sp, BorderLayout.CENTER);
this.setVisible(true);
return gp;
}
void addComponent() throws IOException {
System.out.println("adding");
grid.add(new JLabel("test"));
grid.add(new intf());
this.repaint();
frame.pack();
}
private static void createAndShowGUI() throws IOException {
//Create and set up the window.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
frame.add(new Workspace(), BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
}
}
以及intf.java
的JInternalFrame
类:
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class intf extends JInternalFrame {
public intf () {
super("Document",
true, //resizable
true, //closable
true, //maximizable
true);//iconifiable
JPanel jp = new JPanel();
JLabel jl = new JLabel("Hi I'm a label");
jp.add(jl);
this.add(jp);
this.pack();
this.repaint();
}
}
编辑:JPanel用于保存布局,我不认为可以为TabbedPane分配一个吗?用户将加载出现在GridLayout左侧的图像(我将其升级为GridBag)。在所述图像上选择区域之后,图形将出现在右侧。这也是为什么我们使用scrollPane来限制加载的图像数量的原因。如果用户加载太多图像,TabbedPane将用于拆分负载(这不在此处显示的演示代码中,并且与问题无关)。我发布的代码用于测试JInternalFrame不显示的原因,因此它仅显示与使它起作用有关的内容。
谢谢大家的投入。事实证明,这是一个简单的错误,没有必要的.setVisible(true)
在addComponent()
方法下,当我替换
grid.add(new intf());
与
intf a = new intf();
a.setVisible(true);
grid.add(a);