我正在尝试制作一系列标签。每个标签都有一个不同的值,这些值来自一个函数。我不知道要使用的标签的确切数量。我的意思是可以打印任意数量的值。请帮我做这件事。
问问题
45293 次
5 回答
7
很简单,只需一个方法返回一个数组或一些 JLabel 集合,然后将它们全部添加到您的 JComponent(例如 JPanel)中
class MyPanel extends JPanel{
public MyPanel(){
super();
showGUI();
}
private JLabel[] createLabels(){
JLabel[] labels=new JLabel[10]
for (int i=0;i<10;i++){
labels[i]=new JLabel("message" + i);
}
return labels;
}
private void showGUI(){
JLabel[] labels=createLabels();
for (int i=0;i<labels.length();i++){
this.add(labels[i]);
}
}
}
于 2010-04-26T09:59:24.110 回答
2
于 2010-04-26T10:12:34.217 回答
0
Are you kiddin ? Well, in case you're serious, first take a look at some of the Java APIs, like JLabel, JPanel, and some of the language elements.
Then you'll be able to do something like (I'm sure my code won't compile)
public static JPanel getLabels(int count) {
JPanel panel = new JPanel(new FlowLayout());
for(int i =0; i<count; i++) {
panel.add(new JLabel(theFunctionThatCannotBeNamedHere(i)));
}
return panel;
}
Notice that theFunctionThatCannotBeNamedHere
is the function you talked about.
于 2010-04-26T09:53:14.117 回答
0
import java.awt.*;
public class frame4array extends Frame
{
Checkbox c1[]; /* Same as checkbox and TextField now you add an array of Label in
Frame and Applet also and if you want to create an array of swing components now write
same as JTextField jt[];*/
TextField t1[];
int i;
frame4array(String p)
{
super(p);
c1=new Checkbox[2];
t1=new TextField[2];
for(i=0;i<2;i++)
{
t1[0]=new TextField();
t1[0].setBounds(200, 50, 150, 30);
t1[1]=new TextField();
t1[1].setBounds(200, 80, 150, 30);
c1[0]=new Checkbox("Singing");
c1[0].setBackground(Color.red);
c1[0].setBounds(430,200,120,40);
c1[1]=new Checkbox("Cricket",true);
}
for(i=0;i<2;i++)
{
add(t1[i]);
add(c1[i]);
}
setFont(new Font("Arial",Font.ITALIC,40));
}
public static void main(String s[])
{
frame4array f1=new frame4array("hello");
f1.setSize(600,500);
f1.setVisible(true);
}
}
/* run and enjoy */
于 2021-05-27T06:05:02.460 回答
0
您实际上可以创建一个包含任何 Swing 组件的数组,因为每个 Swing 组件基本上都是复合数据类型。尝试这个:
javax.swing.JTextField[] array = new javax.swing.JTextField[number_of_elements];
于 2017-12-03T18:16:15.593 回答