How to draw a line on a existing jPanel in Swing (Java)? - java

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.

Related

JFrame.setExtendedState() not working properly on Macs

I am using a javax.swing.JFrame with java 1.8.0_211 and I want to have my JFrame maximized over the whole screen.
I am using the following code:
public class MitarbeiterUI extends javax.swing.JFrame {
/**
* Creates new form MitarbeiterUI
*/
public MitarbeiterUI(Mitarbeiter mitarbt) {
initComponents();
this.setExtendedState(MAXIMIZED_BOTH);
this.setSize((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(), (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight());
this.setVisible(true);
}
[...]
}
This however only causes the window to align to the screen horizontally, but not vertically. It does work with both Windows And Linux systems, so it has to be a Mac specific issue. Is there any way around this mighty annoying bug?
Edit: Executable code sample
import java.awt.Toolkit;
public class SecondFrame extends javax.swing.JFrame {
/**
* Creates new form SecondFrame
*/
public SecondFrame() {
initComponents();
this.setExtendedState(MAXIMIZED_BOTH);
this.setSize((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(), (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight());
this.setVisible(true);
}
/**
* 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();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 563, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 877, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(134, 134, 134)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)))
.addContainerGap(25, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(19, 19, 19)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(241, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void formComponentResized(java.awt.event.ComponentEvent evt) {
jLabel1.setText("W: " + this.getWidth() + ", H: " + this.getHeight());
}
/**
* #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(SecondFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SecondFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SecondFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SecondFrame.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 SecondFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
Edit2: It seems the issue lies with the screen sizes the Macs we used have. They both sport a resolution greater than fullHD, but both are automatically scaling down to 1440 to 900p, which makes the JPanel we use in our class bigger than the resized screen and in turn has it cut off at the bottom. So I guess the question is now how can I either tell those Macs to not resize their screens, or how to add scrollbars to the JFrame without having to redo the whole class.
this.setExtendedState(MAXIMIZED_BOTH);
this.setSize((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(), (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight());
this.setVisible(true);
The point of using setExtendedState(...) is that you don't need to use the setSize(...) method.
So the code should simply be:
this.setExtendedState(MAXIMIZED_BOTH);
this.setVisible(true);
The setSize() statement is overriding the size calculated by the setExtendedState(...) method.

Display BufferedImage on JPanel

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.

Adding a shape to a JPanel

I have a simple JFrame and I have added a JPanel inside of this frame. How do I go about adding a shape: I.E. a colored square to that panel which I have given a variable name of gamePanel?
Here is the code. Literally nothing in there yet however I want to add squares in the panel. Creating a block collapsing game.
package blockmanagertest;
import java.awt.Color;
import java.awt.Graphics;
public class BlockGUI extends javax.swing.JFrame {
/**
* Creates new form BlockGUI
*/
public BlockGUI() {
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() {
gamePanel = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
gamePanel.setBackground(new java.awt.Color(38, 38, 38));
javax.swing.GroupLayout gamePanelLayout = new javax.swing.GroupLayout(gamePanel);
gamePanel.setLayout(gamePanelLayout);
gamePanelLayout.setHorizontalGroup(
gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 562, Short.MAX_VALUE)
);
gamePanelLayout.setVerticalGroup(
gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 738, Short.MAX_VALUE)
);
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()
.addComponent(gamePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(175, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(gamePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
/**
* #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(BlockGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(BlockGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(BlockGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(BlockGUI.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 BlockGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel gamePanel;
// End of variables declaration
public void paintComponent(Graphics g) {
super.paintComponents(g);
g.setColor(Color.red);
g.fillRect(150, 150, 150, 150);
}
}

Repaint doesn't work and the value of my private fields won't change?

I am making a graphical interface in Netbeans where you can put a series of numbers (example: 7 8 5 4 10 13) in the textfield "punten" and when you press the button "ververs" a graphical linechart of all the numbers should appear (in my panel). I made a class "Gui" that extends JFrame with the Textfield, the button and a panel in it. I also made a class "Grafiek" that extends JPanel and that is linked with the panel in my "Gui".
The problems that I experience are: the repaint(); command won't go to the paintComponent(Graphics g)-method and my private variables won't change (the length of punt and punti stays 0).
Can somebody please help me, I've been working on this project for days.
My Gui-class:
import java.awt.Graphics;
public class Gui extends javax.swing.JFrame {
public Gui() {
initComponents();
panel = new javax.swing.JPanel();
}
/**
* 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() {
punten = new javax.swing.JTextField();
fout = new javax.swing.JLabel();
javax.swing.JButton ververs = new javax.swing.JButton();
panel = new Grafiek();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
fout.setText("j");
ververs.setText("Ververs");
ververs.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
verversActionPerformed(evt);
}
});
panel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));
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, 195, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(punten, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(ververs)
.addGap(6, 6, 6)
.addComponent(fout)
.addGap(0, 302, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(punten, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(fout)
.addComponent(ververs))
.addContainerGap())
);
pack();
}// </editor-fold>
private void verversActionPerformed(java.awt.event.ActionEvent evt) {
Grafiek graf = new Grafiek();
graf.verwerkData(punten.getText());
}
/**
* #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(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Gui.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 Gui().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel fout;
private javax.swing.JPanel panel;
private javax.swing.JTextField punten;
// End of variables declaration
}
And my "Grafiek"-class:
import java.awt.Graphics;
public class Grafiek extends javax.swing.JPanel {
private String[] punt;
private int[] punti;
private int afstandX, afstandY, puntX1=0, puntY1=0, puntX2=0, puntY2=0;
private int max=1;
/**
* Creates new form Grafiek
*/
public Grafiek() {
initComponents();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
try{
for(int i=0; i<punti.length; i++) {
if(max <= punti[i]) {
max = punti[i];
}
}
afstandX = getWidth()/punt.length;
afstandY = getHeight()/max;
for(int i=0; i<punti.length; i++) {
puntX1 = puntX2;
if(i == 0) {
puntY1 = getHeight();
}
else puntY1 = puntY2;
puntX2 += afstandX;
puntY2 = getHeight() - punti[i]*afstandY;
g.drawLine(puntX1, puntY1, puntX2, puntY2);
}
puntX2 = 0;
puntY2 = 0;
}catch(java.lang.NullPointerException npe) {
super.paintComponent(g);
}
}
public void verwerkData(String s) {
punt = s.split(" ");
punti = new int[punt.length];
for(int i=0; i<punt.length; i++) {
punti[i] = Integer.parseInt(punt[i]);
}
repaint();
}
/**
* 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() {
setBackground(new java.awt.Color(255, 255, 255));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>
}
The code does not work because you add your points to the wrong object.
First of all, your panel object is not of type Grafiek, second of all it is first initialized in the method initComponents() and then overwritten again in the constructor.
Second problem, in the method verversActionPerformed called by the action listener, you create a new instance of Grafiek that is obviously not the one you have created/added before.
Thus, to make it work alter the code as follows:
The constructor should look the following:
public Gui() {
initComponents();
//panel = new javax.swing.JPanel();
}
The method like this:
private void verversActionPerformed(java.awt.event.ActionEvent evt) {
Grafiek graf = (Grafiek)panel;
graf.verwerkData(punten.getText());
}
Thus, it works as you expected.
However, this is far away from good code. You should set the type of variable panel to the correct type Grafiek.

Zoom jPanel using JSlider in netbeans

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

Categories

Resources