java - 如何让自定义绘制组件显示在 swing GUI JPanel 中?

标签 java swing user-interface netbeans

我正在使用 java swing GUI 在 NetBeans 中创建显示面板。我需要在此 GUI 中的 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));
        }
    }
}

问题是,如果我在 GraphPanel 类中包含以下代码,我只能在单独的 JFrame 中显示该图。

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);
    }

这是我的 swing 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 方法是我尝试在 GUI 中显示它,但是由于某种原因它根本不会显示。

最佳答案

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

关于java - 如何让自定义绘制组件显示在 swing GUI JPanel 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55559714/

相关文章:

java - synchronized statements java——它们相对于非同步代码究竟做了什么?

java - gu 没有这样的文件或目录

java - 更改 JComboboxBox 上的 JScrollPane

java - 如何从 Swing 组件中检索唯一的字符串?

java - 如果添加了太多按钮,JToolBar 会显示箭头

asp.net - 在重用和逻辑封装方面使用 ASP.NET 构建 JavaScript UI 代码的最佳方式?

java - java中的多个服务器TCP

java - Swing 今天还在使用吗?

java - JTextField 中的异常处理

java - 三星盖乐世 S8+ : Device Metrics Gives wrong device screen pixel density