在GUI中显示数组

时间:2018-02-06 18:19:56

标签: java swing

我一直在用Bubblesort算法做一个程序。我已经用算法制作了一个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.
}

1 个答案:

答案 0 :(得分:3)

我认为你应该使用追加

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);