1

Jlabel自分の番組がクリックされたときを見たいのですJButtonが、うまくいきません!

public class d5 extends JFrame implements ActionListener {

    JButton showButton;
    static JLabel[] lbl;
    JPanel panel;

    public d5() {

        showButton = new JButton("Show");
        showButton.addActionListener(this);
        add(showButton, BorderLayout.PAGE_START);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 500);
        setLocation(300, 30);
        setVisible(true);
    }

    public JPanel mypanel() {
        panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        lbl = recordsLabel();
        for (JLabel jLabel : lbl) {
            panel.add(jLabel);
        }
        return panel;
    }

    public static void main(String[] args) {
        new d5();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == showButton) {
            add(mypanel(), BorderLayout.PAGE_START);
            setVisible(true);
            System.out.println("show button clicked");
        }
    }

    public JLabel[] recordsLabel() {
        ArrayList<String> lableList = new ArrayList<>();
        lableList.add("one");
        lableList.add("two");
        lableList.add("three");
        Object[] arrayResultRow = lableList.toArray();

        int rows = 3;

        lbl = new JLabel[rows];
        for (int i = 0; i < rows; i++) {
            lbl[i] = new JLabel(arrayResultRow[i].toString());
        }
        return lbl;
    }
}
4

1 に答える 1

3

@nicecow のコメント add(showButton, BorderLayout.PAGE_START);として、既にパネルと同じ場所にいます。同じ場所に追加できるコンポーネントは 1 つだけです。

また、validate を呼び出すことも悪くありません。

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == showButton) {
        add(mypanel(), BorderLayout.PAGE_START); // set another position or remove previous component here
        validate(); 
        System.out.println("show button clicked");

    }
}

ちなみに、クラスでの実装はお勧めしませんActionListenerJFrameまた、拡張する必要もありませんJFrame

public class D5 { 

private JFrame frame;

.
. // is some part in constrcutor
.
  showButton.addActionListener(new ActionListener(){
        @Override 
         public void actionPerformed(ActionEvent evt){
              frame.add(mypanel(),BorderLayout.PAGE_START);
              frame.validate();
         }
  })
}
于 2013-07-11T14:23:39.930 に答える