Writing something in JList

萝らか妹 提交于 2019-12-02 11:12:18

This is somewhat difficult to follow, but from what I gather, you are using your Zmienne_pomocnicze class in two places, and both of them seem to do nothing.

First, in jButton2ActionPerformed you instantiate a new Zmienne_pomocnicze and try to get the data from it using the getPrzechowaj method. This will return n, but as you have just instantiated the instance, n is null. As I cant infer from the method names of the following code, I cant figure out what you want to do with that data, but this action is most certainly not what you want to do.

In the second case, jButton1ActionPerformed takes the value from the text field and then test for validity (legnth is greater than 0). If the validation passes, you then create a new Zmienne_pomocnicze, call setPrezechowaj with the text field value and then let the new object fall out of scope. Again, this is certainly not the desired effect.

It would be interesting to see what the flow of your program is supposed to be, ie what button triggers which jButton[12]ActionPerformed methods and how you expect them to interact.

Here's a simple example of adding entries to a JList.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;

public class JListTest {

    private static final Random random = new Random();

    public static final void main(String args[]) throws Exception {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        final JFrame frame = new JFrame("Test");
        final DefaultListModel dlm = new DefaultListModel();
        final JList list = new JList(dlm);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(new JScrollPane(list));
        frame.add(new JButton("Add") {
            {
                addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        dlm.addElement("A" + (random.nextInt(9000) + 1000));
                    }
                });
            }
        }, BorderLayout.SOUTH);
        frame.setLocationRelativeTo(null);
        frame.pack();
        frame.setVisible(true);
    }
}

I always recommend reading the API for basic information.

If you read the JList API you will find a link to the Swing tutorial on "How to Use Lists". The example there shows how to dynamically add and remove entries from the ListModel.

Tutorials are a good place to start because you find working examples as well as explanations as to how the code works. Then, if required you can ask a specific question about a specific piece of code.

Not only that you now have a reference that might come in handy for other problems.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!