本文介绍了在单击JButton时显示JLabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
点击我的节目JButton
时,我想看到Jlabel
,但是它不起作用!
I want to see Jlabel
when my show JButton
is clicked, but it doesn't work!
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;
}
}
推荐答案
作为@nicecow注释,您已经add(showButton, BorderLayout.PAGE_START);
在与面板相同的位置.您只能在同一位置添加一个组件.
As @nicecow comment you've already add(showButton, BorderLayout.PAGE_START);
in the same location as the panel. Only one component you can add at same location.
另外,调用validate也不错.
Also it is not bad to call 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");
}
}
通过不建议在JFrame
类中实现ActionListener
的方式,也不需要扩展JFrame
By the way i don't recommend implementing ActionListener
in JFrame
class, also you don't need to extend 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();
}
})
}
这篇关于在单击JButton时显示JLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!