gpt4 book ai didi

java - 在 GUI 中显示数组

转载 作者:行者123 更新时间:2023-12-01 19:58:48 26 4
gpt4 key购买 nike

我一直在用冒泡排序算法编写一个程序。我已经用该算法制作了一个GUI,但是我的结束数组(从最小到最大的数字)似乎没有出现,唯一出现的是最后一个(也是最大的)数字。我知道该算法是正确的,因为我使用 System.out.print 进行了一些测试来检查它是否正确,确实如此。我正在使用 JTextArea ,我的代码如下:

JButton button = new JButton("Berechnen");
JTextField z1 = new JTextField();
JTextField z2 = new JTextField();
JTextField z3 = new JTextField();
JTextField z4 = new JTextField();

JLabel n1 = new JLabel("Erste Zahl");
JLabel n2 = new JLabel("Zweite Zahl");
JLabel n3 = new JLabel("Dritte Zahl");
JLabel n4 = new JLabel("Vierte Zahl");
JTextArea res = new JTextArea("Ergebnis");

public static void main(String[] args) {

new Sortieren();
}

public Sortieren() {

this.setTitle("Bubblesort");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(400, 400);
this.setLayout(null);
this.setVisible(true);

this.add(z1);
z1.setBounds(150,10,120,20);
this.add(z2);
z2.setBounds(150,40,120,20);
this.add(z3);
z3.setBounds(150,70,120,20);
this.add(z4);
z4.setBounds(150,100,120,20);
this.add(n1);
n1.setBounds(10,10,120,20);
this.add(n2);
n2.setBounds(10,40,120,20);
this.add(n3);
n3.setBounds(10,70,120,20);
this.add(n4);
n4.setBounds(10,100,120,20);
this.add(res);
res.setBounds(10,130,200,20);
this.add(button);
button.setBounds(70,160,100,20);

button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {

String text1= z1.getText();
String text2= z2.getText();
String text3= z3.getText();
String text4= z4.getText();

int behaelter = 0;
int zahl1 = Integer.parseInt(text1);
int zahl2 = Integer.parseInt(text2);
int zahl3 = Integer.parseInt(text3);
int zahl4 = Integer.parseInt(text4);

int[] sort = {zahl1, zahl2, zahl3, zahl4};

for (int i = 0; i < sort.length; i++) {
for (int j = 1; j < (sort.length - i); j++) {
if (sort[j - 1] > sort[j]) {
behaelter = sort[j - 1];
sort[j - 1] = sort[j];
sort[j] = behaelter;

}

}
}

for (int i = 0; i < sort.length; i++) {
System.out.print(sort[i]+" ");
res.setText(String.valueOf(sort[i]+" "));
}

}

});



}

@Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

最佳答案

我认为你应该使用附加

for (int i = 0; i < sort.length; i++) 
res.append(sort[i]);

或者另一个解决方案应该将其保存到字符串中:

String result = "";
for (int i = 0; i < sort.length; i++)
result += Integer.toString(sort[i]) + " ";

然后将文本设置为res

res.setText(result);

关于java - 在 GUI 中显示数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48649504/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com