javaswing如何解决打印值的问题

t1qtbnec  于 2021-07-07  发布在  Java
关注(0)|答案(1)|浏览(359)

我正在编写java swing,背包算法我有四个参数,我想通过textfield取值
n-->元素
重量-->重量
val-->值
w-->容量
应该打印 val 在label java中,我的代码不打印label中的任何内容,我不知道为什么没有错误
在我的代码里:算法里面的动作按钮‘run’

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.JLabel;

import java.util.Scanner;
public class Knapsack_frame extends JFrame {
private JPanel contentPane;
private JTextField textField_4;
private JLabel lebel_out;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Knapsack_frame frame = new Knapsack_frame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public Knapsack_frame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 871, 531);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    textField = new JTextField();
    textField.setColumns(10);
    textField.setBounds(408, 121, 213, 20);
    contentPane.add(textField);

    textField_1 = new JTextField();
    textField_1.setColumns(10);
    textField_1.setBounds(408, 149, 213, 20);
    contentPane.add(textField_1);

    textField_2 = new JTextField();
    textField_2.setColumns(10);
    textField_2.setBounds(408, 189, 213, 20);
    contentPane.add(textField_2);

    textField_4 = new JTextField();
    textField_4.setBounds(408, 228, 213, 20);
    contentPane.add(textField_4);
    textField_4.setColumns(10);

    //-----------------------------------------------------------------------------------------
    lebel_out = new JLabel("");
    lebel_out.setBounds(192, 289, 499, 52);
    contentPane.add(lebel_out);

    JLabel lblNewLabel = new JLabel("Enter number of elements :");
    lblNewLabel.setBounds(211, 124, 166, 14);
    contentPane.add(lblNewLabel);

    // here button run 
    JButton btnNewButton = new JButton("Knapsack Run");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
             // here my algorithm Knapsack
             //four argement, input by text Filed 
            class Zero_One_Knapsack
            {
                public void solve(int[] wt, int[] val, int W, int N)
                {
                    int NEGATIVE_INFINITY = Integer.MIN_VALUE;
                    int[][] m = new int[N + 1][W + 1];
                    int[][] sol = new int[N + 1][W + 1];
                    for (int i = 1; i <= N; i++)
                    {
                        for (int j = 0; j <= W; j++)
                        {
                            int m1 = m[i - 1][j];
                            int m2 = NEGATIVE_INFINITY; 
                            if (j >= wt[i])
                                m2 = m[i - 1][j - wt[i]] + val[i];
                            m[i][j] = Math.max(m1, m2);
                            sol[i][j] = m2 > m1 ? 1 : 0;
                        }
                    }        
                    int[] selected = new int[N + 1];
                    for (int n = N, w = W; n > 0; n--)
                    {
                        if (sol[n][w] != 0)
                        {
                            selected[n] = 1;
                            w = w - wt[n];
                        }
                        else
                            selected[n] = 0;
                    }

                    for (int i = 1; i < N + 1; i++)
                        if (selected[i] == 1)

                lebel_out.setText("\nItems with weight "+ val[i] + "  " + "are selected by knapsack 
                 algorithm."  );
                }
                public void main (String[] args) 
                {

                    Zero_One_Knapsack ks = new Zero_One_Knapsack();

                  int n = Integer.parseInt(textField.getText());
                    int[] wt = new int[n + 1];
                    int[] val = new int[n + 1];
             //----------------------------------------------------------------------
                    int valueWt =Integer.parseInt(textField_1.getText());
                    for (int i = 1; i <= n; i++)
                        wt[i] = valueWt;
            //-----------------------------------------------------------------------
                    int valueV =Integer.parseInt(textField_2.getText());
                    for (int i = 1; i <= n; i++)
                        val[i] =  valueV;
            //----------------------------------------------------------------------

                    int W = Integer.parseInt(textField_4.getText());
                    ks.solve(wt, val, W, n);

                }
            }

        }
    });
    btnNewButton.setBounds(355, 41, 192, 23);
    contentPane.add(btnNewButton);

    JLabel lblEnterWeightFor = new JLabel("Enter weight for 4 elements :");
    lblEnterWeightFor.setBounds(211, 152, 166, 14);
    contentPane.add(lblEnterWeightFor);

    JLabel lblEnterValueFor = new JLabel("Enter value for 4 elements :");
    lblEnterValueFor.setBounds(211, 189, 166, 14);
    contentPane.add(lblEnterValueFor);

    JLabel lblEnterCapacity = new JLabel("Enter capacity :");
    lblEnterCapacity.setBounds(211, 231, 166, 14);
    contentPane.add(lblEnterCapacity);

}
}
piv4azn7

piv4azn71#

不要延伸 JFrame 不必要的
不要使用 null / AbsoluteLayout 在这里查看一些layoutmanager选项
不要手动呼叫 setBounds 在零部件上,使用 LayoutManager 让组件自行调整大小,只需调用 pack()JFrame 不要打电话 setContentPaneJFrame 只需添加 JPanel ,任一呼叫 JFrame#getContentPane() 或者只是打个电话 JFrame#add(...) ,也许这是我的偏好
你的类名不是你通常在java中看到的(下划线小写字母),它们应该是pascal大小写的。 KnapsackApp , ZeroOneKnapsack 没有下划线等,虽然它是有效的,但它不是正常的惯例。
同样的情况也适用于变量名(textfield\ 1),通常是驼峰大小写,即。 textField1 也许给他们起个更好的名字会更好。 elementsLabel .
把你的关注点分开,你有一个嵌套在 JButton s actionPerformed (我假设可以访问 JTextField ,但这不是必需的),在单独的文件中创建它,将参数传递给 solve 方法并返回结果,然后使用该结果设置结果 JLabel 价值观。
您甚至不创建 Zero_One_Knapsack 要调用的类 solve 在按钮上 actionPerformed .
也许用一个 SwingWorker 在后台完成工作,然后将结果发布到ui(这样ui就不会冻结),如果背包可能需要那么长时间的话。
要接受逗号分隔的整数并将其转换为整数数组,可以使用java 8流:

String line = "1,2,3,1,2,2,1,2,3,"; // example from textFeild.getText()
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();

这里是代码重构,给你一些你应该瞄准什么的想法,我不是说它按你想的那样工作,但是希望有一些事情被清理了,你将得到一个良好的基础和理解来完成它:

背包应用程序.java:

import java.awt.event.ActionEvent;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;

public class KnapsackApp {

    public KnapsackApp() {
        initComponents();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(KnapsackApp::new);
    }

    private void initComponents() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // setup JPanel and LayoutManager
        JPanel panel = new JPanel();
        panel.setBorder(new EmptyBorder(5, 5, 5, 5));
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        JLabel elementsLabel = new JLabel("Enter number of elements :");
        panel.add(elementsLabel);
        JTextField elementsTextField = new JTextField();
        elementsTextField.setColumns(10);
        panel.add(elementsTextField);

        JLabel lblEnterWeightFor = new JLabel("Enter weight for 4 elements :");
        panel.add(lblEnterWeightFor);
        JTextField weightTextField = new JTextField();
        weightTextField.setColumns(10);
        panel.add(weightTextField);

        JLabel lblEnterValueFor = new JLabel("Enter value for 4 elements :");
        panel.add(lblEnterValueFor);
        JTextField valueTextFields = new JTextField();
        valueTextFields.setColumns(10);
        panel.add(valueTextFields);

        JLabel lblEnterCapacity = new JLabel("Enter capacity :");
        panel.add(lblEnterCapacity);
        JTextField capacityTextField = new JTextField();
        panel.add(capacityTextField);
        capacityTextField.setColumns(10);

        JLabel resultLabel = new JLabel("Result: ");
        panel.add(resultLabel);

        JButton btnNewButton = new JButton("Knapsack Run");
        panel.add(btnNewButton);

        btnNewButton.addActionListener((ActionEvent e) -> {
            int n = Integer.parseInt(elementsTextField.getText());
            int[] wt = new int[n + 1];
            int[] val = new int[n + 1];

            int valueWt = Integer.parseInt(weightTextField.getText());
            for (int i = 1; i <= n; i++) {
                wt[i] = valueWt;
            }
            int valueV = Integer.parseInt(valueTextFields.getText());
            for (int i = 1; i <= n; i++) {
                val[i] = valueV;
            }

            int W = Integer.parseInt(capacityTextField.getText());

            SwingWorker backgroundWorker = new SwingWorker<Integer, Void>() {
                @Override
                public Integer doInBackground() throws Exception {
                    // do the work
                    return new ZeroOneKnapsack().solve(wt, val, W, n);
                }

                @Override
                protected void done() {
                    int result;
                    try {
                        // get and display the result from solve
                        result = get();
                        resultLabel.setText("Result: " + result);
                    } catch (InterruptedException | ExecutionException ex) {
                        Logger.getLogger(KnapsackApp.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            };
            backgroundWorker.execute();
        });

        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }

}

ZeroOne背包.java:

public class ZeroOneKnapsack {

    public int solve(int[] wt, int[] val, int W, int N) {
        int NEGATIVE_INFINITY = Integer.MIN_VALUE;
        int[][] m = new int[N + 1][W + 1];
        int[][] sol = new int[N + 1][W + 1];
        for (int i = 1; i <= N; i++) {
            for (int j = 0; j <= W; j++) {
                int m1 = m[i - 1][j];
                int m2 = NEGATIVE_INFINITY;
                if (j >= wt[i]) {
                    m2 = m[i - 1][j - wt[i]] + val[i];
                }
                m[i][j] = Math.max(m1, m2);
                sol[i][j] = m2 > m1 ? 1 : 0;
            }
        }
        int[] selected = new int[N + 1];
        for (int n = N, w = W; n > 0; n--) {
            if (sol[n][w] != 0) {
                selected[n] = 1;
                w = w - wt[n];
            } else {
                selected[n] = 0;
            }
        }

        for (int i = 1; i < N + 1; i++) {
            if (selected[i] == 1) {
                return val[i];
            }
        }

        return -1;
    }
}

相关问题