我正在使用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中显示它,但是由于某种原因它根本不会显示。

最佳答案

GraphPanelJPanel,可以像其他任何组件一样添加。
做一些小的改动:
public java.awt.Panel graphPanel;更改为public javax.swing.JPanel graphPanel;-没有理由使用AWT组件。使用Swing JPanel

graphPanel = new java.awt.Panel();更改为graphPanel = new GraphPanel();-您不想构造空白面板。您要构造一个GraphPanel

删除displayBarChart()方法-不再使用。
这样就完成了:

java - 如何获取自定义绘画组件以在Swing GUI JPanel中显示?-LMLPHP

09-25 16:30