Как получить пользовательский компонент рисования для отображения в графическом интерфейсе JPanel? - PullRequest
1 голос
/ 07 апреля 2019

Я создаю панель отображения в NetBeans с помощью графического интерфейса Java Swing.Мне нужно нарисовать график на JPanel в этом графическом интерфейсе.Чтобы нарисовать график, я создал отдельный класс с именем GraphPanel.

package softwaredevelopmentgroupproject;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class GraphPanel extends JPanel
{
    private int[] graphSource;

    public GraphPanel()
    {
        graphSource = new int[] {2, 4, 9, 8, 13, 3, 8};
        //setUpPanel();
    }

    public void setUpPanel() 
    {
        this.setBackground(Color.LIGHT_GRAY);
    }

    @Override
    protected void paintComponent(Graphics currentGraphics)
    {
        super.paintComponent(currentGraphics);

        Graphics2D mainGraphics = (Graphics2D) currentGraphics;

        for(int i = 0; i < graphSource.length; i++)
        {
            int height = this.getHeight()/graphSource.length;
            int width = graphSource[i];
            int xPosition = 0;
            int yPosition = height * i;

            int red = (int)(Math.random() * 256);
            int green = (int)(Math.random() * 256);
            int blue = (int)(Math.random() * 256);
            int alpha = (int)(Math.random() * 255);

            mainGraphics.setColor(new Color(red, green, blue, alpha));
            mainGraphics.fill(new Rectangle(xPosition, yPosition, width, height));
        }
    }
}

Проблема в том, что я могу отображать этот график только в отдельном JFrame, если я включу приведенный ниже код в свой класс GraphPanel.

public static void main(String[] args)
    {
        JFrame jp1 = new JFrame();
        GraphPanel graph = new GraphPanel();
        jp1.add(graph, BorderLayout.CENTER);
        jp1.setSize(new Dimension(200,200));
        jp1.setVisible(true);
    }

Вот код для моего свингаGUI.

package softwaredevelopmentgroupproject;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class AppGUI extends javax.swing.JFrame {

    public AppGUI() 
    {
        initComponents();
        displayProperties();
        //displayBarChart();
    }

    public ArrayList<String> getProperties()
    {
        ArrayList<String> propertiesList = new ArrayList<>();

        try
        {
            String propertyName = "3 bedroom house overlooking seafront";
            String propertyAddress = "139 Archard Street, N69 7GG";
            double price = 957.90;
            String displayPrice = "£" + price + " per month";
            String value = propertyName + System.lineSeparator() + propertyAddress + System.lineSeparator() + displayPrice + System.lineSeparator();
            propertiesList.add(propertyName);
            propertiesList.add(propertyAddress);
            propertiesList.add(displayPrice);
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null, e);
        }
        return propertiesList;
    }

    public void displayProperties()
    {
        ArrayList<String> list = getProperties();
        //propertyListings.setModel(new PropertyTableModel(td, col));
        DefaultTableModel model = (DefaultTableModel) propertyListings.getModel();
        //propertyListings.setDefaultRenderer(AppGUI.class, model);
        //propertyListings.getColumnModel().getColumn(0).setCellRenderer(model);
        Object[] row = new Object[1]; //list.size()

        for(int i = 0; i < list.size(); i++)
        {
            row[0] = list.get(i);
            model.addRow(row);
        }
    }

    public void displayBarChart()
    {
        GraphPanel graph = new GraphPanel();
        Graphics graphics = graph.getGraphics();
        graphPanel.paint(graphics);
        graphPanel.repaint();
        //graphPanel.add(graph, FlowLayout.CENTER);
        //graphPanel.setSize(new Dimension(200,200));
        //graphPanel.setVisible(true);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        topPanel = new javax.swing.JPanel();
        dateTimeDisplay = new javax.swing.JLabel();
        welcomeMessage = new javax.swing.JLabel();
        searchPanel = new javax.swing.JPanel();
        enterPrice1 = new javax.swing.JTextField();
        toLabel = new javax.swing.JLabel();
        enterPrice2 = new javax.swing.JTextField();
        searchPropertiesButton = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        propertyListings = new javax.swing.JTable();
        graphPanel = new java.awt.Panel();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        topPanel.setBackground(new java.awt.Color(67, 38, 126));
        topPanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        dateTimeDisplay.setText("Date/Time");

        welcomeMessage.setText("Welcome back, blah");

        javax.swing.GroupLayout topPanelLayout = new javax.swing.GroupLayout(topPanel);
        topPanel.setLayout(topPanelLayout);
        topPanelLayout.setHorizontalGroup(
            topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(topPanelLayout.createSequentialGroup()
                .addGap(65, 65, 65)
                .addComponent(dateTimeDisplay)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(welcomeMessage)
                .addGap(182, 182, 182))
        );
        topPanelLayout.setVerticalGroup(
            topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(topPanelLayout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dateTimeDisplay)
                    .addComponent(welcomeMessage))
                .addGap(0, 16, Short.MAX_VALUE))
        );

        enterPrice1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                enterPrice1ActionPerformed(evt);
            }
        });

        toLabel.setText("to");

        enterPrice2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                enterPrice2ActionPerformed(evt);
            }
        });

        searchPropertiesButton.setBackground(new java.awt.Color(67, 38, 126));
        searchPropertiesButton.setText("Search for a property");
        searchPropertiesButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchPropertiesButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout searchPanelLayout = new javax.swing.GroupLayout(searchPanel);
        searchPanel.setLayout(searchPanelLayout);
        searchPanelLayout.setHorizontalGroup(
            searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(searchPanelLayout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addComponent(enterPrice1, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(toLabel)
                .addGap(18, 18, 18)
                .addComponent(enterPrice2, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(47, 47, 47)
                .addComponent(searchPropertiesButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        searchPanelLayout.setVerticalGroup(
            searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(searchPanelLayout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(enterPrice1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(toLabel)
                    .addComponent(enterPrice2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchPropertiesButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 467, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 7, Short.MAX_VALUE)
        );

        propertyListings.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Property Listings in Oslo"
            }
        ));
        jScrollPane2.setViewportView(propertyListings);

        graphPanel.addContainerListener(new java.awt.event.ContainerAdapter() {
            public void componentAdded(java.awt.event.ContainerEvent evt) {
                graphPanelComponentAdded(evt);
            }
        });
        graphPanel.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                graphPanelComponentShown(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(topPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(searchPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 444, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(graphPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 410, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(38, 38, 38))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(topPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(1, 1, 1)
                .addComponent(searchPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(graphPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 391, Short.MAX_VALUE))
                .addGap(28, 28, 28)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void enterPrice1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void searchPropertiesButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                       
        // TODO add your handling code here:
    }                                                      

    private void enterPrice2ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void graphPanelComponentShown(java.awt.event.ComponentEvent evt) {                                          

    }                                         

    private void graphPanelComponentAdded(java.awt.event.ContainerEvent evt) {                                          
        // TODO add your handling code here:
    }                                         


    public static void main(String args[]) 
    {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AppGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AppGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AppGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AppGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() 
        {
            public void run() 
            {
                new AppGUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel dateTimeDisplay;
    private javax.swing.JTextField enterPrice1;
    private javax.swing.JTextField enterPrice2;
    public java.awt.Panel graphPanel;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable propertyListings;
    private javax.swing.JPanel searchPanel;
    private javax.swing.JButton searchPropertiesButton;
    private javax.swing.JLabel toLabel;
    private javax.swing.JPanel topPanel;
    private javax.swing.JLabel welcomeMessage;
    // End of variables declaration                   

}

Код довольно грязный, так как я тестировал разные методы отображения графика, так что, надеюсь, он читабелен.Мой метод displayBarChart - это моя попытка отобразить его в графическом интерфейсе, однако по какой-то причине он вообще не будет отображаться.

1 Ответ

2 голосов
/ 07 апреля 2019

GraphPanel является JPanel и может быть добавлен как любой другой компонент.
Сделайте небольшие изменения:
измените public java.awt.Panel graphPanel; на public javax.swing.JPanel graphPanel; - нет причин использовать компоненты AWT. Используйте Swing JPanel.

изменить graphPanel = new java.awt.Panel(); на graphPanel = new GraphPanel(); - вы не хотите создавать пустую панель. Вы хотите построить GraphPanel

метод удаления displayBarChart() - он больше не используется.
И все готово:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...