单击第二个按钮后,JPanel不会显示组件

时间:2014-05-29 18:27:56

标签: java swing jpanel jbutton jtextpane

我想在单击按钮时将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();
}       
}

1 个答案:

答案 0 :(得分:0)

帕特里克:你是对的!我真的忘了改变gridbagconstraints

addComponent(panel, gbl, textPane[i], 0, i, 1, 1, 1, 1);

而不是

addComponent(panel, gbl, textPane[i], 0, counter, 1, 1, 1, 1);