I need to display BufferedImage on a JPanel with Netbeans. I add the panel using Netbeans' drag and drop. Then I added code to display the image on the panel. Here is my code:
BufferedImage img = null;
try {
img = ImageHelper.loadImage(path);
} catch (IOException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
}
ImageIcon icon = new ImageIcon(img);
JLabel picLabel = new JLabel(icon);
//imagePlace is JPanel
imagePlace.add(picLabel);
imagePlace.repaint();
But it didn't paint the image on the panel. I have followed some tutorials but not working at all. Can you give an example the correct way to display BufferedImage on JPanel?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tubes;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import static jdk.nashorn.tools.ShellFunctions.input;
/**
*
* #author ivan
*/
public class MainGUI extends javax.swing.JFrame {
/**
* Creates new form MainGUI
*/
public MainGUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
openImageBtn = new javax.swing.JButton();
imagePlace = new javax.swing.JPanel();
canvas1 = new java.awt.Canvas();
jPanel2 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setPreferredSize(new java.awt.Dimension(512, 512));
openImageBtn.setText("Open Image");
openImageBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openImageBtnActionPerformed(evt);
}
});
imagePlace.setBackground(new java.awt.Color(254, 254, 254));
javax.swing.GroupLayout imagePlaceLayout = new javax.swing.GroupLayout(imagePlace);
imagePlace.setLayout(imagePlaceLayout);
imagePlaceLayout.setHorizontalGroup(
imagePlaceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 178, Short.MAX_VALUE)
);
imagePlaceLayout.setVerticalGroup(
imagePlaceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 194, Short.MAX_VALUE)
);
canvas1.setBackground(new java.awt.Color(255, 0, 0));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(openImageBtn)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(imagePlace, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 253, Short.MAX_VALUE)
.addComponent(canvas1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(80, 80, 80))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(openImageBtn)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(imagePlace, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(96, 96, 96)
.addComponent(canvas1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(144, Short.MAX_VALUE))
);
jTabbedPane1.addTab("tab1", jPanel1);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 523, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 387, Short.MAX_VALUE)
);
jTabbedPane1.addTab("tab2", jPanel2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 535, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(108, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(25, Short.MAX_VALUE)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 430, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void openImageBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
String path = selectedFile.getAbsolutePath();
System.out.println(path);
BufferedImage img = null;
try {
img = ImageHelper.loadImage(path);
} catch (IOException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
}
ImageIcon icon = new ImageIcon(img);
JLabel label = new JLabel("", icon, JLabel.CENTER);
JLabel picLabel = new JLabel(icon);
imagePlace.add(picLabel);
imagePlace.repaint();
}
}
/**
* #param args the command line arguments
*/
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(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainGUI.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 MainGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private java.awt.Canvas canvas1;
private javax.swing.JPanel imagePlace;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JButton openImageBtn;
// End of variables declaration
}
When you add a component to a visible GUI the basic code is:
imagePlace.add(imgpnl);
imagePlace.revalidate(); //added
imagePlace.repaint();
You need the revalidate to invoke the layout manager, otherwise the component may have a size of (0, 0) so there is nothing to paint.
javax.swing.GroupLayout imagePlaceLayout = new javax.swing.GroupLayout(imagePlace);
imagePlace.setLayout(imagePlaceLayout);
However, the bigger problem is that you are using a GroupLayout and you didn't specify any constraints for the GroupLayout. Read the Swing tutorial on How to Use GroupLayout for information on the constraints and working examples.
Personally, I suggest you get rid of the code generator (and the GroupLayout) and create the GUI layout yourself if you want to dynamically add components to the frame. Start by just using a FlowLayout on your "imagePlace" panel. The code will be much simpler since you don't need any constraints.
Related
I have made two JScrollPane components. The left one shows the directories in USB and right shows the directories of a local drive. For I am able to display the complete file path as shown in first pic. But I want to display it with icons just like the way directories are displayed in any local drive on PC. This is my designed GUI, here is the example of what I want example
public class MainForm extends javax.swing.JFrame {
iRecordCopy obj = new iRecordCopy();
public MainForm() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jScrollPane2 = new javax.swing.JScrollPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Main From");
setLocation(new java.awt.Point(0, 0));
setName("mainframe"); // NOI18N
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jLabel1.setText("iRecordCopy");
jLabel2.setText("jLabel2");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addGap(48, 48, 48)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(25, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(30, 30, 30))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)
.addComponent(jScrollPane2))
.addContainerGap())
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public 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(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainForm.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 MainForm().setVisible(true);
}
});
}
public void showusb()
{
File[] usb;
int count = 0;
String str;
usb = obj.detectUSB();
if(usb == null)
{
//USB_window.setText("No USB attached\n");
return;
}
for (File filename : usb) {
str = filename.toString().substring(3);
str = str.substring(0, str.length() - 3);
System.out.println(str);
if(str.equalsIgnoreCase("vehicle"))
{
System.out.print(filename.toString());
//USB_window.append(filename.getPath()+"\n");
count++;
}
}
if(count == 0)
{
System.out.println("No recordings found in usb");
}
else
System.out.println("Number of directries :" + count);
//File currentDir = new File(System.getProperty("user.home"));
JList<File> jlist=new JList<File>(obj.path.listFiles());
jScrollPane1 = new JScrollPane(jlist);
jScrollPane1.setPreferredSize(new Dimension(400, 800));
setContentPane(jScrollPane1);
final JLabel label=new JLabel();
jlist.setCellRenderer(new ListCellRenderer<File>() {
#Override
public Component getListCellRendererComponent(JList<? extends File> list, File value, int index,
boolean isSelected, boolean cellHasFocus) {
label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(value));
label.setText(value.getName());
return label;
}
});
}
public void showPc(File f)
{
JList<File> jlist=new JList<File>(f.listFiles());
jScrollPane2 = new JScrollPane(jlist);
//jScrollPane2.setPreferredSize(new Dimension(400, 800));
setContentPane(jScrollPane2);
final JLabel label=new JLabel();
jlist.setCellRenderer(new ListCellRenderer<File>() {
#Override
public Component getListCellRendererComponent(JList<? extends File> list, File value, int index,
boolean isSelected, boolean cellHasFocus) {
label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(value));
label.setText(value.getName());
return label;
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
// End of variables declaration
}
Here a short example to create a minimal JList with file icons, it displays the content of the user's home directory using the system file icons.
package test;
import java.awt.Component;
import java.awt.Dimension;
import java.io.File;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.filechooser.FileSystemView;
public class Test {
public static void main(String[] args) {
JFrame frame=new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
File currentDir=new File(System.getProperty("user.home"));
JList<File> jlist=new JList<File>(currentDir.listFiles());
JScrollPane scrollPane=new JScrollPane(jlist);
scrollPane.setPreferredSize(new Dimension(400, 800));
frame.setContentPane(scrollPane);
final JLabel label=new JLabel();
jlist.setCellRenderer(new ListCellRenderer<File>() {
#Override
public Component getListCellRendererComponent(JList<? extends File> list, File value, int index,
boolean isSelected, boolean cellHasFocus) {
label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(value));
label.setText(value.getName());
return label;
}
});
frame.pack();
frame.setVisible(true);
}
}
I am using Netbeans. I set up a graphics program to do graphing. I overrode 3 JPanel paintComponent methods just to get started but these methods are not being called.
I have programs that work. My new override code looks the same. I've tried a plethora of things and have run out of ideas. I am using Borderlayout for the first time but that shouldn't cause a problem.
import java.awt.Graphics;
import java.awt.Graphics2D;
/*
* To change this license header, choose License Headers in Project
*Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
public class MainForm extends javax.swing.JFrame
{
/**
* Creates new form NewJFrame
*/
public MainForm()
{
initComponents();
initProgram();
}
private void initProgram()
{
System.out.println("InitProgram");
}
/**
* This method is called from within the constructor to initialize the
* form. WARNING: Do NOT modify this code. The content of this method
* is always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents()
{
pnlPrintPanel = new javax.swing.JPanel();
pnlGraphForm = new javax.swing.JPanel();
pnlGraph = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
pnlInputPanel = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation
(javax.swing.WindowConstants.EXIT_ON_CLOSE);
pnlGraphForm.setBorder
(javax.swing.BorderFactory.createBevelBorder(
javax.swing.border.BevelBorder.RAISED));
pnlGraph.setBorder
(javax.swing.BorderFactory.createBevelBorder(
javax.swing.border.BevelBorder.RAISED));
jLabel2.setText("jLabel2");
javax.swing.GroupLayout pnlGraphLayout =
new javax.swing.GroupLayout(pnlGraph);
pnlGraph.setLayout(pnlGraphLayout);
pnlGraphLayout.setHorizontalGroup(
pnlGraphLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
pnlGraphLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(jLabel2)
.addGap(277, 277, 277))
);
pnlGraphLayout.setVerticalGroup(
pnlGraphLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlGraphLayout.createSequentialGroup()
.addGap(101, 101, 101)
.addComponent(jLabel2)
.addContainerGap(204, Short.MAX_VALUE))
);
jLabel1.setText("jLabel1");
javax.swing.GroupLayout pnlGraphFormLayout =
new javax.swing.GroupLayout(pnlGraphForm);
pnlGraphForm.setLayout(pnlGraphFormLayout);
pnlGraphFormLayout.setHorizontalGroup(
pnlGraphFormLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlGraphFormLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(pnlGraph, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(pnlGraphFormLayout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE,
59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pnlGraphFormLayout.setVerticalGroup(
pnlGraphFormLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlGraphFormLayout.createSequentialGroup()
.addContainerGap()
.addComponent(pnlGraph, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addContainerGap())
);
pnlGraph = new javax.swing.JPanel()
{
//#Override
//public void paint(Graphics g)
#Override
public void paintComponent(Graphics g)
{
System.out.println("In pnlGraph.paintComponent");
//super.paint(g);
/*
if (grapher == null)
{
return;
}
*/
super.paintComponent(g);
// grapher.drawSlate((Graphics2D)g);
pack();
}
};
pnlInputPanel.setBorder(
javax.swing.BorderFactory.createBevelBorder(
javax.swing.border.BevelBorder.RAISED));
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout pnlInputPanelLayout =
new javax.swing.GroupLayout(pnlInputPanel);
pnlInputPanel.setLayout(pnlInputPanelLayout);
pnlInputPanelLayout.setHorizontalGroup(
pnlInputPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlInputPanelLayout.createSequentialGroup()
.addGap(271, 271, 271)
.addComponent(jButton1)
.addContainerGap(297, Short.MAX_VALUE))
);
pnlInputPanelLayout.setVerticalGroup(
pnlInputPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlInputPanelLayout.createSequentialGroup()
.addGap(59, 59, 59)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
javax.swing.GroupLayout pnlPrintPanelLayout =
new javax.swing.GroupLayout(pnlPrintPanel);
pnlPrintPanel.setLayout(pnlPrintPanelLayout);
pnlPrintPanelLayout.setHorizontalGroup(
pnlPrintPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlPrintPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlPrintPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlPrintPanelLayout.createSequentialGroup()
.addComponent(pnlInputPanel,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addComponent(pnlGraphForm,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
pnlPrintPanelLayout.setVerticalGroup(
pnlPrintPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlPrintPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(pnlGraphForm,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pnlInputPanel,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
);
pnlGraphForm = new javax.swing.JPanel()
{
//#Override
//public void paint(Graphics g)
#Override
public void paintComponent(Graphics g)
{
System.out.println("In pnlGraphForm.paintComponent");
//super.paint(g);
/*
if (grapher == null)
{
return;
}
*/
super.paintComponent(g);
// grapher.drawSlate((Graphics2D)g);
pack();
}
};
getContentPane().add(pnlPrintPanel, java.awt.BorderLayout.CENTER);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
System.out.println("BUTTON");
pnlGraphForm.paintComponents((Graphics2D)
pnlGraphForm.getGraphics());
}
/**
* #param args the command line arguments
*/
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(MainForm.class.getName())
.log(java.util.logging.Level.SEVERE, null, ex);
}
catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(
MainForm.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(
MainForm.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
}
catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(
MainForm.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new MainForm().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel pnlGraph;
private javax.swing.JPanel pnlGraphForm;
private javax.swing.JPanel pnlInputPanel;
private javax.swing.JPanel pnlPrintPanel;
// End of variables declaration
}
At this stage, I expected to see the panel/method names printed but it isn't happening
I've built a Higher/Lower game, using the Swing library. When I run the code I don't get any errors or warnings. The problem appears when I try running the code, the window is empty, not the way it should be.
I use NetBeans to program.There are 2 different files in my project, here is the code...
HiLoGUI.java:
import java.awt.Dimension;
import javax.swing.*;
public class HiLoGUI extends JFrame {
private JTextField txtGuess;
private JLabel outputLabel;
private int theNumber;
public void newGame() {
theNumber = (int)(Math.random() * 100 + 1);
}
public void checkGuess() {
String guessText = txtGuess.getText();
String message = "";
int guess = Integer.parseInt(guessText);
if (guess < theNumber) {
message = guess + " is too low. Try again.";
}
else if (guess > theNumber) {
message = guess + " is too high. Try again.";
}
else {
message = guess + " is correct. You win!";
}
outputLabel.setText(message);
}
public static void main(String[] args) {
HiLoGUI theGame = new HiLoGUI();
theGame.newGame();
theGame.setSize(new Dimension(450,300));
theGame.setVisible(true);
}
}
The window should look like this:
NetBeans screenshot
EDIT:
The other files code:
public class HiLoJFrame extends javax.swing.JFrame {
/**
* Creates new form HiLoJFrame
*/
public HiLoJFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
titleLabel = new javax.swing.JLabel();
chooseLabel = new javax.swing.JLabel();
txtGuess = new javax.swing.JTextField();
guessButton = new javax.swing.JButton();
outputLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setName("HiLoGame"); // NOI18N
titleLabel.setFont(new java.awt.Font("SansSerif", 1, 24)); // NOI18N
titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
titleLabel.setText("High/Lower Game");
titleLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
chooseLabel.setFont(new java.awt.Font("SansSerif", 0, 15)); // NOI18N
chooseLabel.setText("Guess a name between 1 to 100");
txtGuess.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtGuessActionPerformed(evt);
}
});
guessButton.setFont(new java.awt.Font("Ubuntu", 0, 18)); // NOI18N
guessButton.setText("Guess");
guessButton.setCursor(new java.awt.Cursor(java.awt.Cursor.MOVE_CURSOR));
guessButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
guessButtonActionPerformed(evt);
}
});
outputLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
outputLabel.setText("Enter a number and press Guess");
outputLabel.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(50, Short.MAX_VALUE)
.addComponent(chooseLabel)
.addGap(18, 18, 18)
.addComponent(txtGuess, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(136, 136, 136)
.addComponent(guessButton, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(78, 78, 78)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(titleLabel)
.addComponent(outputLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(titleLabel)
.addGap(75, 75, 75)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtGuess, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chooseLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
.addComponent(guessButton, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(53, 53, 53)
.addComponent(outputLabel)
.addGap(35, 35, 35))
);
titleLabel.getAccessibleContext().setAccessibleDescription("");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 422, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 346, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))
);
getAccessibleContext().setAccessibleName("HiLoGame");
pack();
}// </editor-fold>
private void txtGuessActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void guessButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
HiLoGUI hilogui = new HiLoGUI();
hilogui.checkGuess();
}
/**
* #param args the command line arguments
*/
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(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
new HiLoJFrame().setVisible(true);
});
}
// Variables declaration - do not modify
private javax.swing.JLabel chooseLabel;
private javax.swing.JButton guessButton;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel outputLabel;
private javax.swing.JLabel titleLabel;
private javax.swing.JTextField txtGuess;
// End of variables declaration
}
EDIT2:
I've changed the main class of HiLoGUI.java
I was creating a wrong object.
New main:
public static void main(String[] args) {
HiLoJFrame theGame = new HiLoJFrame();
theGame.newGame();
theGame.setSize(new Dimension(450,300));
theGame.setVisible(true);
}
Now it claims that I need to create that method (newGame) in the JFrame file.
You are calling a method from the wrong class, according to the Swing docs, it is not needed to create a new JFrame object, so setting its visibility is enough. Check this out: How To Call JFrame from another Java class
I want to draw a simple line on my existing jPanel called mypanel. I want to do it like this:
mypanel.drawLine(0,0, 20, 35);
The numbers are the X and Y Position of Point 1 and the others are X and Y Position of Point 2, between Point 1 and Point 2 there should be my line. Is there a easy way without adding an additional jPanel on my jFrame? Thank you in advance.
Edit:
My GUI Code:
import java.awt.Graphics;
import javax.swing.JPanel;
public class main_panel extends javax.swing.JFrame {
public main_panel() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
panel = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
panel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
panel.setLayout(panelLayout);
panelLayout.setHorizontalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
panelLayout.setVerticalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 163, Short.MAX_VALUE)
);
jButton1.setText("Set Values");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 280, Short.MAX_VALUE)
.addComponent(jButton1)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(0, 0, 20, 35);
}
};
}
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(main_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(main_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(main_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(main_panel.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 main_panel().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPanel panel;
// End of variables declaration
}
Something like this
myPanel = new JPanel() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(0,0, 20, 35);
};
But your suggestion with two panels is better.
Here is the full GUI code (each click on "Set Values" will toggle the line).
import java.awt.Graphics;
import javax.swing.JPanel;
public class main_panel extends javax.swing.JFrame {
private boolean drawLine;
public main_panel() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
panel = new javax.swing.JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (drawLine) {
g.drawLine(0, 0, 20, 35);
}
}
};
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
panel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
panel.setLayout(panelLayout);
panelLayout.setHorizontalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
panelLayout.setVerticalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 163, Short.MAX_VALUE)
);
jButton1.setText("Set Values");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 280, Short.MAX_VALUE)
.addComponent(jButton1)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
drawLine = !drawLine;
panel.repaint();
}
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(main_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(main_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(main_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(main_panel.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 main_panel().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPanel panel;
// End of variables declaration
}
Is there a easy way without adding an additional jPanel on my jFrame?
This statement is hard to interpret by itself and out of context. What you must do is override paintComponent as is noted above for the component that you want to display the line it, nothing more, and nothing less. How you do this will depend on the structure of your program, something we know little about at present.
Please look at this link for more details.
You also state:
I added exactly the code from #Sergiy Medvynskyy into my application, there are no errors the line just doesn't appear on the panel. With the solution with two panels I want to add another jPanel on my existing jPanel with the line on it, maybe it's easier to implement.
That's possible as long as your original JPanel is set up to receive a 2nd JPanel, in other words has a layout manager that will allow easy addition of the 2nd JPanel, and a location on it where the added JPanel won't cover anything else of importance. For instance if the first JPanel uses BorderLayout, then the second with the drawing code could be added BorderLayout.CENTER to display its drawing in the middle of the first.
But again, details are key. If you need more direct help, then show your GUI code, preferably an mcve.
In your posted code, you create a 2nd JPanel but you add it to nothing, so of course it's not displayed. Just because you use the same panel variable has no effect, and in order for the 2nd JPanel to be seen, it must be added. You need to learn layout managers and learn to use the human-usable managers such as BorderLayout for this to work.
I want to zoom a Jpanel using a slider.
I have some circles drown into my jpanel (I will code them to move later)
the problem I have is the zoom button, I already used the answer here : https://stackoverflow.com/q/15962432/3080016
but it's not exactly what I want.
I'm using netbeans gui builder please help me and thanks :)
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication13;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jSlider1 = new javax.swing.JSlider();
jScrollPane1 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel(){
protected void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g.create();
super.paintComponent(g);
int w =getWidth(); // real width of canvas
int h =getHeight(); // real height of canvas
// Translate used to make sure scale is centered
g2.translate(w/2, h/2);
g2.scale((double)jSlider1.getValue(),(double)jSlider1.getValue());
g2.translate(-w/2, -h/2);
g2.fillOval(200, 200, 25, 25);
g2.fillOval(200, 223, 25, 25);
g2.fillOval(150, 223, 25, 25);
g2.fillOval(100, 200, 25, 25);
//repaint(); too much cpu use.
}
};
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jSlider1.setMinimum(1);
jSlider1.setValue(1);
jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jSlider1StateChanged(evt);
}
});
jScrollPane1.setPreferredSize(new Dimension((jSlider1.getValue()*5),(jSlider1.getValue()*10)));
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jScrollPane1.setViewportView(jPanel1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSlider1, javax.swing.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 317, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {
jPanel1.repaint();
}
/**
* #param args the command line arguments
*/
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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSlider jSlider1;
// End of variables declaration
}
Just add this in... it's not refreshing cause you haven't asked it to.
jSlider1.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
jPanel1.repaint();
}
});