我想在单击按钮时将JTextPane组件放在带有GridBagLayout的JPanel中。 我的代码适用于第一次单击按钮,但之后,下一个组件不会显示。
这是我的代码:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class RefreshPanel {
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
private JTextPane [] textPane;// = new JTextPane[1];
private JScrollPane scrollbar;
private ArrayList arrayList = new ArrayList();
private JButton newItem = new JButton("new");
private int counter=0;
private GridBagLayout gbl = new GridBagLayout();
RefreshPanel() {
scrollbar = new JScrollPane(panel);
panel.setBackground(Color.WHITE);
panel.setLayout(gbl);
addButtonListener();
createFrame();
} //constructor
public void addButtonListener() {
newItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
arrayList.add("data");
textPane = generateTextPane(arrayList.size(), arrayList);
System.out.println(textPane.length);
for(int i=0;i<textPane.length;i++) {
System.out.println(textPane[i].getText());
addComponent(panel, gbl, textPane[i], 0, counter, 1, 1,1,1);
panel.revalidate();
}
}
});
}
private JTextPane[] generateTextPane(int arraySize, ArrayList arrayList) {
JTextPane [] textPane = new JTextPane[arraySize];
for(int i=0;i<textPane.length;i++) {
textPane[i]=new JTextPane();
textPane[i].setText((String) arrayList.get(i));
}
return textPane;
}
public void addComponent(Container cont,
GridBagLayout gbl,
Component c,
int x, int y,
int width, int height,
double weightx, double weighty) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = x; gbc.gridy = y;
gbc.gridwidth = width; gbc.gridheight = height;
gbc.weightx = weightx; gbc.weighty = weighty;
gbl.setConstraints( c, gbc );
cont.add( c );
}
public void createFrame() {
//frame.getContentPane().setLayout(new FlowLayout());
frame.add(scrollbar, BorderLayout.CENTER);
frame.add(newItem, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300,300));
frame.setVisible(true);
}
public static void main(String [] args) {
new RefreshPanel();
}
}
答案 0 :(得分:0)
addComponent(panel, gbl, textPane[i], 0, i, 1, 1, 1, 1);
而不是
addComponent(panel, gbl, textPane[i], 0, counter, 1, 1, 1, 1);