Issue
I am creating a display panel in NetBeans using a java swing GUI. I need to draw a graph on a JPanel in this GUI. To draw the graph I created a separate class called 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));
}
}
}
The issue is that I can only display this graph in a separate JFrame if I include the code below in my GraphPanel class.
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);
}
Here is the code for my 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
}
The code is rather messy as I was testing different methods to display the graph, so hopefully it is readable. My displayBarChart method is my attempt to display it in the GUI, however it won't display at all for some reason.
Solution
GraphPanel
is a JPanel
and can be added like any other component.
Do some minor changes :
change public java.awt.Panel graphPanel;
to public javax.swing.JPanel graphPanel;
- there is no reason to use AWT components. Use Swing JPanel
.
change graphPanel = new java.awt.Panel();
to graphPanel = new GraphPanel();
- you do not want to construct a blank Panel. You want to construct a GraphPanel
remove displayBarChart()
method - it is not used anymore.
And you are done:
Answered By - c0der