Вывод значений матрицы в визуальную форму - Java

Узнай цену своей работы

Формулировка задачи:

Добрый день. Имеется программа, обрабатывающая матрицу и её визуальное представление в Swing. Интересует один момент: как можно отобразить саму матрицу не в консоли, а в одном из элементов Swing(в каком, в принципе, неважно) по нажатии соответствующей кнопки?
Листинг программы
  1. package javaapplication1;
  2. import java.util.Random;
  3. import java.util.Scanner;
  4. import org.apache.log4j.*;
  5. import org.apache.log4j.xml.DOMConfigurator;
  6. public class JavaApplication1 {
  7. private int[][] data;
  8. public JavaApplication1 () {
  9. data = new int [12][12];
  10. Random r = new Random();
  11. for (int i=0; i<12; i++)
  12. for (int j=0; j<12; j++) {
  13. data[i][j]=r.nextInt()%25;
  14. logger.info(data[i][j]);
  15. }
  16. logger.info("Матрица создана.");
  17. }
  18. public void Show_Matrix () {
  19. for (int i=0; i<data.length; i++) {
  20. for (int j=0; j<data.length; j++) {
  21. System.out.print(data[i][j]);
  22. System.out.print(' ');
  23. }
  24. System.out.println();
  25. }
  26. logger.info("Матрица выведена на экран.");
  27. }
  28. public void DoStuff () {
  29. for (int i=0; i<data.length; i++)
  30. for (int j=0; j<data.length; j++)
  31. if (i<=j) {
  32. data[i][j] = 0;
  33. logger.info(data[i][j]);
  34. }
  35. logger.info("Матрица преобразована.");
  36. }
  37. public static Logger logger = LogManager.getLogger(JavaApplication1.class.getName());
  38. public static void main(String[] args) {
  39. DOMConfigurator.configure("log4j2.xml");
  40. logger.info("Запуск приложения.");
  41. Window window = new Window();
  42. window.setVisible(true);
  43. }
  44. }

Решение задачи: «Вывод значений матрицы в визуальную форму»

textual
Листинг программы
  1. package javaapplication1;
  2.  
  3. /*
  4.  * To change this license header, choose License Headers in Project Properties.
  5.  * To change this template file, choose Tools | Templates
  6.  * and open the template in the editor.
  7.  */
  8.  
  9. public class Window extends javax.swing.JFrame {
  10.  
  11.     /**
  12.      * Creates new form Window
  13.      */
  14.     private JavaApplication1 variable;
  15.     public Window() {
  16.         initComponents();
  17.     }
  18.  
  19.     /**
  20.      * This method is called from within the constructor to initialize the form.
  21.      * WARNING: Do NOT modify this code. The content of this method is always
  22.      * regenerated by the Form Editor.
  23.      */
  24.     @SuppressWarnings("unchecked")
  25.     // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  26.     private void initComponents() {
  27.  
  28.         jGreeting = new javax.swing.JLabel();
  29.         jDescription = new javax.swing.JTextArea();
  30.         jRandomizeButton = new javax.swing.JButton();
  31.         jDoThingsButton = new javax.swing.JButton();
  32.         jExitButton = new javax.swing.JButton();
  33.         jDisplayButton = new javax.swing.JButton();
  34.         jSeparator1 = new javax.swing.JSeparator();
  35.         jScrollPane1 = new javax.swing.JScrollPane();
  36.         jDisplayArea = new javax.swing.JEditorPane();
  37.  
  38.         setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  39.  
  40.         jGreeting.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
  41.         jGreeting.setText("Welcome to the program!");
  42.  
  43.         jDescription.setEditable(false);
  44.         jDescription.setColumns(20);
  45.         jDescription.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
  46.         jDescription.setRows(5);
  47.         jDescription.setText("This app is very simple. You can randomize your 12x12 matrix by \npressing the \"Randomize\"-Button. \"DoThings\"-Button makes all the \ndiagonal and upper elements of the matrix zero's. \"Exit\"-Button will \nexit from the application.");
  48.  
  49.         jRandomizeButton.setText("Randomize");
  50.         jRandomizeButton.addActionListener(new java.awt.event.ActionListener() {
  51.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  52.                 jRandomizeButtonActionPerformed(evt);
  53.             }
  54.         });
  55.  
  56.         jDoThingsButton.setText("Do Things");
  57.         jDoThingsButton.addActionListener(new java.awt.event.ActionListener() {
  58.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  59.                 jDoThingsButtonActionPerformed(evt);
  60.             }
  61.         });
  62.  
  63.         jExitButton.setText("Exit");
  64.         jExitButton.addActionListener(new java.awt.event.ActionListener() {
  65.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  66.                 jExitButtonActionPerformed(evt);
  67.             }
  68.         });
  69.  
  70.         jDisplayButton.setText("Display");
  71.         jDisplayButton.addActionListener(new java.awt.event.ActionListener() {
  72.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  73.                 jDisplayButtonActionPerformed(evt);
  74.             }
  75.         });
  76.  
  77.         jDisplayArea.setEditable(false);
  78.         jScrollPane1.setViewportView(jDisplayArea);
  79.  
  80.         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  81.         getContentPane().setLayout(layout);
  82.         layout.setHorizontalGroup(
  83.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  84.             .addGroup(layout.createSequentialGroup()
  85.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  86.                     .addGroup(layout.createSequentialGroup()
  87.                         .addGap(106, 106, 106)
  88.                         .addComponent(jGreeting))
  89.                     .addGroup(layout.createSequentialGroup()
  90.                         .addGap(18, 18, 18)
  91.                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
  92.                             .addComponent(jDescription, javax.swing.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)
  93.                             .addGroup(layout.createSequentialGroup()
  94.                                 .addComponent(jRandomizeButton)
  95.                                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  96.                                 .addComponent(jDoThingsButton)
  97.                                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  98.                                 .addComponent(jDisplayButton)
  99.                                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  100.                                 .addComponent(jExitButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
  101.                             .addComponent(jSeparator1)
  102.                             .addComponent(jScrollPane1))))
  103.                 .addContainerGap(16, Short.MAX_VALUE))
  104.         );
  105.         layout.setVerticalGroup(
  106.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  107.             .addGroup(layout.createSequentialGroup()
  108.                 .addContainerGap()
  109.                 .addComponent(jGreeting)
  110.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  111.                 .addComponent(jDescription, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
  112.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  113.                 .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
  114.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  115.                 .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE)
  116.                 .addGap(18, 18, 18)
  117.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  118.                     .addComponent(jRandomizeButton)
  119.                     .addComponent(jDoThingsButton)
  120.                     .addComponent(jDisplayButton)
  121.                     .addComponent(jExitButton))
  122.                 .addContainerGap())
  123.         );
  124.  
  125.         pack();
  126.     }// </editor-fold>                        
  127.  
  128.     private void jRandomizeButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                
  129.         variable.logger.info("jRandomizeButton нажата.");
  130.         variable = new JavaApplication1();
  131.         System.out.println("Первоначальная матрица: ");
  132.         variable.Show_Matrix();
  133.         System.out.println(' ');
  134.     }                                                
  135.  
  136.     private void jDoThingsButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                
  137.         variable.logger.info("jDoThingsButton нажата.");
  138.         variable.DoStuff();
  139.         System.out.println("Результирующая матрица: ");
  140.         variable.Show_Matrix();
  141.         System.out.println(' ');
  142.     }                                              
  143.  
  144.     private void jExitButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
  145.         variable.logger.info("jExitButton нажата.");
  146.         variable.logger.info("Выход из приложения.");
  147.         dispose();
  148.        
  149.     }                                          
  150.  
  151.     private void jDisplayButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              
  152.         variable.logger.info("jDisplayButton нажата.");
  153.     }                                              
  154.  
  155.     /**
  156.      * @param args the command line arguments
  157.      */
  158.     public static void main(String args[]) {
  159.         /* Set the Nimbus look and feel */
  160.         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  161.         /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  162.          * For details see [url]http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html[/url]
  163.          */
  164.         try {
  165.             for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  166.                 if ("Nimbus".equals(info.getName())) {
  167.                     javax.swing.UIManager.setLookAndFeel(info.getClassName());
  168.                     break;
  169.                 }
  170.             }
  171.         } catch (ClassNotFoundException ex) {
  172.             java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  173.         } catch (InstantiationException ex) {
  174.             java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  175.         } catch (IllegalAccessException ex) {
  176.             java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  177.         } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  178.             java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  179.         }
  180.         //</editor-fold>
  181.  
  182.         /* Create and display the form */
  183.         java.awt.EventQueue.invokeLater(new Runnable() {
  184.             public void run() {
  185.                 new Window().setVisible(true);
  186.             }
  187.         });
  188.     }
  189.  
  190.     // Variables declaration - do not modify                    
  191.     private javax.swing.JTextArea jDescription;
  192.     private javax.swing.JEditorPane jDisplayArea;
  193.     private javax.swing.JButton jDisplayButton;
  194.     private javax.swing.JButton jDoThingsButton;
  195.     private javax.swing.JButton jExitButton;
  196.     private javax.swing.JLabel jGreeting;
  197.     private javax.swing.JButton jRandomizeButton;
  198.     private javax.swing.JScrollPane jScrollPane1;
  199.     private javax.swing.JSeparator jSeparator1;
  200.     // End of variables declaration                  
  201. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

14   голосов , оценка 3.929 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы