将 JLabel 数组导入 JComponent

Posted

技术标签:

【中文标题】将 JLabel 数组导入 JComponent【英文标题】:Importing a JLabel array into a JComponent 【发布时间】:2012-07-05 07:34:48 【问题描述】:

我环顾四周试图解决我的问题,但找不到任何解决此问题的方法。我对 java 很陌生,我正在尝试在不使用控制台的情况下完成书中的项目,但这就是我所拥有的,

import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;


public class FutureInvestmentValue 
public static void main(String[] args) 
    double investmentAmount = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter in the investment amount as a double.", "Investment Amout",
            JOptionPane.PLAIN_MESSAGE));

    double monthlyInterestRate = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter in the monthly interest rate as a double.", "Monthly Interest Rate",
            JOptionPane.PLAIN_MESSAGE));

    int years = 30;

    final JComponent[] outputHeader = new JComponent[] 
            new JLabel("The amount invested: " + investmentAmount),
            new JLabel("Annual interest Rate: " + monthlyInterestRate),
            new JLabel("Years       Future Value"),
    ;


    JOptionPane.showMessageDialog(null, outputHeader + futureInvestmentValue(investmentAmount, monthlyInterestRate, years), "Future Investment Value",
            JOptionPane.INFORMATION_MESSAGE);


public static JComponent[] futureInvestmentValue(double investmentAmount, double monthlyInterestRate, int years) 
    final JComponent[] investmentArray = new JComponent[years];
    for (int i = 1; i <= years; i++) 
        double investmentTotal = investmentAmount + (investmentAmount * ((monthlyInterestRate / 10) * i));
        investmentArray[i] = new JLabel(i + "              " + investmentTotal);
    

return investmentArray;


似乎我收到了要更改 futureInvestmentValue(); 的错误。到一个 Jcomponent,当我这样做时,会发生另一个错误,它只是让我绕圈子,从 JLabel 更改为 JLabel[] 到 Jcomponent 到 Jcomponent[] 等等。任何可以用不会让新手感到困惑的术语向我解释的帮助将不胜感激。

【问题讨论】:

【参考方案1】: 为什么要创建一个 JLabel 数组,来用 JTable 代替,

import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Random;
import java.util.concurrent.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.DefaultTableModel;

public class ChangeNotifiersOnEvent extends JFrame implements Runnable 

    private static final long serialVersionUID = 1L;
    private boolean runProcess = true;
    private Random random = new Random();
    private javax.swing.Timer timerRun;
    private Executor executor = Executors.newCachedThreadPool();
    private String[] columnNames = "Source", "Hit", "Last", "Ur_Diff";
    private JTable table;
    private Object[][] data = "Swing Timer", 2.99, 5, 1.01,
        "Swing Worker", 7.10, 5, 1.010, "TableModelListener", 25.05, 5, 1.01;
    private DefaultTableModel model = new DefaultTableModel(data, columnNames);

    public ChangeNotifiersOnEvent() 
        table = new JTable(model) 

            private static final long serialVersionUID = 1L;

            @Override
            public Class getColumnClass(int column) 
                return getValueAt(0, column).getClass();
            
        ;
        model.addTableModelListener(new TableModelListener() 

            @Override
            public void tableChanged(TableModelEvent tme) 
                if (tme.getType() == TableModelEvent.UPDATE) 
                    if (tme.getColumn() == 1 && tme.getLastRow() == 2) 
                        double dbl = ((Double) table.getModel().getValueAt(2, 1))
                                - ((Integer) table.getModel().getValueAt(2, 2));
                        table.getModel().setValueAt(dbl, 2, 3);
                     else if (tme.getColumn() == 1 && tme.getLastRow() == 0) 
                        prepareUpdateTableCell();
                     else if (tme.getColumn() == 1 && tme.getLastRow() == 1) 
                        executor.execute(new MyTask(MyTask.UPDATE_TABLE_COLUMN));
                    
                
            
        );
        table.setRowHeight(30);
        table.setFont(new Font("Serif", Font.BOLD, 20));
        table.getColumnModel().getColumn(0).setPreferredWidth(180);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);
        new Thread(this).start();
    

    private void prepareUpdateTableCell() 
        timerRun = new javax.swing.Timer(10, UpdateTableCell());
        timerRun.setRepeats(false);
        timerRun.start();
    

    private Action UpdateTableCell() 
        return new AbstractAction("Update Table Cell") 

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) 
                double dbl = ((Double) table.getModel().getValueAt(0, 1))
                        - ((Integer) table.getModel().getValueAt(0, 2));
                table.getModel().setValueAt(dbl, 0, 3);
            
        ;
    

    @Override
    public void run() 
        while (runProcess) 
            try 
                Thread.sleep(330);
             catch (Exception e) 
                e.printStackTrace();
            
            changeTableValues();
        
    

    private void changeTableValues() 
        Runnable doRun = new Runnable() 

            @Override
            public void run() 
                table.getModel().setValueAt(random.nextInt(128) + random.nextDouble(), 0, 1);
                table.getModel().setValueAt(random.nextInt(256) + random.nextDouble(), 1, 1);
                table.getModel().setValueAt(random.nextInt(512) + random.nextDouble(), 2, 1);

                table.getModel().setValueAt(random.nextInt(128), 0, 2);
                table.getModel().setValueAt(random.nextInt(128), 1, 2);
                table.getModel().setValueAt(random.nextInt(128), 2, 2);
            
        ;
        SwingUtilities.invokeLater(doRun);
    

    private class MyTask extends SwingWorker<Void, Integer> 

        private static final String UPDATE_TABLE_COLUMN = "update";
        private String namePr;
        private double dbl;

        MyTask(String str) 
            this.namePr = str;
        

        @Override
        protected Void doInBackground() throws Exception 
            dbl = ((Double) table.getModel().getValueAt(1, 1))
                    - ((Integer) table.getModel().getValueAt(1, 2));
            return null;
        

        @Override
        protected void done() 
            SwingUtilities.invokeLater(new Runnable() 

                @Override
                public void run() 
                    table.getModel().setValueAt(dbl, 1, 3);
                
            );
        
    

    public static void main(String[] args) 
        SwingUtilities.invokeLater(new Runnable() 

            @Override
            public void run() 
                ChangeNotifiersOnEvent frame = new ChangeNotifiersOnEvent();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.setLocation(150, 150);
                frame.pack();
                frame.setVisible(true);
            
        );
    

您可以在运行时添加/删除行,

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.table.*;

public class RemoveAddRows extends JFrame 

    private static final long serialVersionUID = 1L;
    private Object[] columnNames = "Type", "Company", "Shares", "Price";
    private Object[][] data = 
        "Buy", "IBM", new Integer(1000), new Double(80.50),
        "Sell", "MicroSoft", new Integer(2000), new Double(6.25),
        "Sell", "Apple", new Integer(3000), new Double(7.35),
        "Buy", "Nortel", new Integer(4000), new Double(20.00)
    ;
    private JTable table;
    private DefaultTableModel model;

    public RemoveAddRows() 

        model = new DefaultTableModel(data, columnNames) 

            private static final long serialVersionUID = 1L;

            @Override
            public Class getColumnClass(int column) 
                return getValueAt(0, column).getClass();
            
        ;
        table = new JTable(model) 

            private static final long serialVersionUID = 1L;

            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) 
                Component c = super.prepareRenderer(renderer, row, column);
                int firstRow = 0;
                int lastRow = table.getRowCount() - 1;
                int width = 0;
                if (row == lastRow) 
                    ((JComponent) c).setBackground(Color.red);
                 else if (row == firstRow) 
                    ((JComponent) c).setBackground(Color.blue);
                 else 
                    ((JComponent) c).setBackground(table.getBackground());
                
                /*if (!isRowSelected(row)) 
                String type = (String) getModel().getValueAt(row, 0);
                c.setBackground("Buy".equals(type) ? Color.GREEN : Color.YELLOW);
                
                if (isRowSelected(row) && isColumnSelected(column)) 
                ((JComponent) c).setBorder(new LineBorder(Color.red));
                */
                return c;
            
        ;
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
        JButton button1 = new JButton("Remove all rows");
        button1.addActionListener(new ActionListener() 

            public void actionPerformed(ActionEvent arg0) 
                if (model.getRowCount() > 0) 
                    for (int i = model.getRowCount() - 1; i > -1; i--) 
                        model.removeRow(i);
                    
                
                System.out.println("model.getRowCount() --->" + model.getRowCount());
            
        );
        JButton button2 = new JButton("Add new rows");
        button2.addActionListener(new ActionListener() 

            public void actionPerformed(ActionEvent arg0) 
                Object[] data0 = "Buy", "IBM", new Integer(1000), new Double(80.50);
                model.addRow(data0);
                Object[] data1 = "Sell", "MicroSoft", new Integer(2000), new Double(6.25);
                model.addRow(data1);
                Object[] data2 = "Sell", "Apple", new Integer(3000), new Double(7.35);
                model.addRow(data2);
                Object[] data3 = "Buy", "Nortel", new Integer(4000), new Double(20.00);
                model.addRow(data3);
                System.out.println("model.getRowCount() --->" + model.getRowCount());
            
        );
        JPanel southPanel = new JPanel();
        southPanel.add(button1);
        southPanel.add(button2);
        add(southPanel, BorderLayout.SOUTH);
    

    public static void main(String[] args) 
        RemoveAddRows frame = new RemoveAddRows();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    

【讨论】:

@user1329572:mKorbel 的解决方案是正确的 (1+),但您的解决方案也是可行的。当你删除它时,我正在投票。 :( 是的 mKorbels 解决方案对于像我这样的人来说绝对是很酷的,user1329572 对于像我这样的人来说更容易理解,但我会花一些时间查看 mKorbels 代码以了解如何从中实现我的解决方案。谢谢你们。

以上是关于将 JLabel 数组导入 JComponent的主要内容,如果未能解决你的问题,请参考以下文章

如何将 JLabel 中的图标(拖放)移动到另一个 JLabel 而不是复制它?

JLabel自动将其自身集中在GridBagLayout中

如何将图标从 JLabel 转换为 BufferedImage?

如何将 JLabel 的文本放在其图标下

如何将 JLabel 对齐到 JPanel 的左侧?

将JLabel图标转换为Java中的字节