Sliding any JPanel - java

Im trying to make a universal class for sliding two any-samesized JPanels but when I use it, the one to get slid just disappears. What I also noticed is that the JPanel "innerPanel"'s width is being reset (when transisting a 200,200 panel) from 400,200 that the size gets reset to 200,200 after the Thread is started
package org.chimeras1684.ui.panels;
import java.awt.Point;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JViewport;
/**
*
* #author Arhowk
*/
public final class Transistor extends javax.swing.JFrame {
/**
* Creates new form test
*/
public enum TDirection{
MOVING_TO_LEFT,
MOVING_TO_RIGHT,
MOVING_TO_TOP,
MOVING_TO_BOTTOM;
}
private static Transistor instance;
static{
instance = new Transistor();
}
public static Transistor getInstance(){
return instance;
}
private Transistor() {
initComponents();
setVisible(true);
slide(TDirection.MOVING_TO_TOP, this, jPanel2, jPanel1);
}
public void slide(final TDirection dir, final JFrame root, final JPanel in, final JPanel out){
if(in.getSize().height != out.getSize().height || out.getSize().width != in.getSize().width ){
throw new IllegalArgumentException("Dimension in is not equal to dimension of out");
}
panelTL.removeAll();
panelBL.removeAll();
panelBR.removeAll();
panelTR.validate();
panelTR.repaint();
panelTL.validate();
panelTL.repaint();
panelBR.validate();
panelBR.repaint();
panelBL.validate();
panelBL.repaint();
final double width = in.getSize().width;
final double height = in.getSize().height;
int x = out.getLocation().x;
int y = out.getLocation().y;
final double speedWidthModifier = (dir == TDirection.MOVING_TO_LEFT) ? -1 : (dir == TDirection.MOVING_TO_RIGHT) ? 1 : 0;
final double speedHeightModifier = (dir == TDirection.MOVING_TO_BOTTOM) ? -1 : (dir == TDirection.MOVING_TO_TOP) ? 1 : 0;
final double xAtEnd = (dir == TDirection.MOVING_TO_RIGHT) ? width : 0;
final double yAtEnd = (dir == TDirection.MOVING_TO_BOTTOM) ? height : 0;
if(dir == TDirection.MOVING_TO_LEFT){
panelTR.setSize(200,200);
panelTL.setSize(200,200);
panelTL.add(in);
panelTR.add(out);
}
if(dir == TDirection.MOVING_TO_RIGHT){
panelTR.setSize(200,200);
panelTL.setSize(200,200);
panelTL.add(out);
panelTR.add(in);
}
if(dir == TDirection.MOVING_TO_BOTTOM){
panelBL.setSize(200,200);
panelTL.setSize(200,200);
panelBL.add(in);
panelTL.add(out);
}
if(dir == TDirection.MOVING_TO_TOP){
panelBL.setSize(200,200);
panelTL.setSize(200,200);
panelBL.add(out);
panelTL.add(in);
}
root.remove(out);
scrollPanel.setSize(in.getSize());
innerPanel.setSize(in.getSize().width * 2, in.getSize().height);
root.add(scrollPanel);
scrollPanel.setLocation(x, y);
if(speedWidthModifier == 0 && speedHeightModifier == 0){
throw new NullPointerException("TDirection dir");
}
System.out.println(new Date());
System.out.println("tlsize1: " + panelTL.getSize());
(new Timer()).schedule(new TimerTask(){
#Override
public void run() {
System.out.println("tlsize1: " + panelTL.getSize());
System.out.println(new Date());
Point viewport = scrollPanel.getViewport().getViewPosition();
JViewport newViewport = scrollPanel.getViewport();
double currentX = viewport.x;
double currentY = viewport.y;
double speed = 50;
double newX = currentX + (speed * speedWidthModifier);
double newY = currentY + (speed * speedHeightModifier);
newViewport.getViewPosition().x = (int)newX;
newViewport.getViewPosition().y = (int)newY;
if((xAtEnd != 0 && newX > xAtEnd) || (yAtEnd != 0 && newY > yAtEnd)){
this.cancel();
}
root.repaint();
System.out.println("tlsize2: " + panelTL.getSize());
}
}, 0,25);
}
/**
* 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() {
java.awt.GridBagConstraints gridBagConstraints;
scrollPanel = new javax.swing.JScrollPane();
innerPanel = new javax.swing.JPanel();
panelTL = new javax.swing.JPanel();
panelTR = new javax.swing.JPanel();
panelBL = new javax.swing.JPanel();
panelBR = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
scrollPanel.setBorder(null);
scrollPanel.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPanel.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
innerPanel.setBackground(new java.awt.Color(255, 0, 153));
innerPanel.setLayout(new java.awt.GridBagLayout());
panelTL.setAutoscrolls(true);
panelTL.setPreferredSize(new java.awt.Dimension(0, 0));
javax.swing.GroupLayout panelTLLayout = new javax.swing.GroupLayout(panelTL);
panelTL.setLayout(panelTLLayout);
panelTLLayout.setHorizontalGroup(
panelTLLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
panelTLLayout.setVerticalGroup(
panelTLLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
innerPanel.add(panelTL, gridBagConstraints);
panelTR.setPreferredSize(new java.awt.Dimension(0, 0));
javax.swing.GroupLayout panelTRLayout = new javax.swing.GroupLayout(panelTR);
panelTR.setLayout(panelTRLayout);
panelTRLayout.setHorizontalGroup(
panelTRLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
panelTRLayout.setVerticalGroup(
panelTRLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
innerPanel.add(panelTR, gridBagConstraints);
panelBL.setPreferredSize(new java.awt.Dimension(0, 0));
javax.swing.GroupLayout panelBLLayout = new javax.swing.GroupLayout(panelBL);
panelBL.setLayout(panelBLLayout);
panelBLLayout.setHorizontalGroup(
panelBLLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
panelBLLayout.setVerticalGroup(
panelBLLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
innerPanel.add(panelBL, gridBagConstraints);
panelBR.setBackground(new java.awt.Color(204, 0, 51));
panelBR.setPreferredSize(new java.awt.Dimension(0, 0));
javax.swing.GroupLayout panelBRLayout = new javax.swing.GroupLayout(panelBR);
panelBR.setLayout(panelBRLayout);
panelBRLayout.setHorizontalGroup(
panelBRLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
panelBRLayout.setVerticalGroup(
panelBRLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
innerPanel.add(panelBR, gridBagConstraints);
scrollPanel.setViewportView(innerPanel);
jPanel1.setBackground(new java.awt.Color(204, 153, 0));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 200, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 200, Short.MAX_VALUE)
);
jPanel2.setBackground(new java.awt.Color(255, 255, 0));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 200, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 200, 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()
.addComponent(scrollPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(109, 109, 109)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 90, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(78, 78, 78))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(scrollPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35))
);
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(Transistor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Transistor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Transistor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Transistor.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 Transistor().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel innerPanel;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel panelBL;
private javax.swing.JPanel panelBR;
private javax.swing.JPanel panelTL;
private javax.swing.JPanel panelTR;
private javax.swing.JScrollPane scrollPanel;
// End of variables declaration
}
Yes, I know the class extends JFrame, I'm just using that for testing purposes. (I'm also not sure how to fix the indenting on this page)

Components in Swing are generally under the control of a layout manager. To achieve what you are trying to do, you would actually be better of creating an animated layout manager.
I suggest you take a look at...
The Universal Tween Engine
Sliding layout
You could also take a look at Animations when using Gridbag Layout. (shameless plug)

Related

Need to get repaint() to stop overwriting my previous graphics [duplicate]

This question already has answers here:
Repaint() doesn't clear the frame
(3 answers)
Closed 3 years ago.
My paint code won't stop overwriting the previous graphics I draw. Whenever I drag my mouse, it's supposed to create a dot and leave it there as it draws a new one in a new location. That doesn't seem to be happening here because when paint() is called, it clears the previous dots. I'll be posting the full code first then the paint() section and then the Mouse Dragged listener. I'm using NetBeans IDE with its prebuilt JForm
1) Full Code
/*
* 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.
*/
/**
*
* #author User-Pc
*/
import DrawCanvas.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.Map;
import javax.swing.JColorChooser;
import javax.swing.JPanel;
public class Paint extends javax.swing.JFrame {
/**
* Creates new form Paint
*/
public Color penColor = Color.BLACK, bgColor = Color.WHITE;
public boolean touchState = false, penState = false, eraseState = false;
public int penSize = 5;
public Point mousePoint = new Point();
public Map map;
public class DrawCanvas extends JPanel{
#Override
public void paint(Graphics g)
{
penSize = jSlider1.getValue();
penState = jToggleButton1.isSelected();
eraseState = jToggleButton2.isSelected();
setBackground(bgColor);
g.setColor(penColor);
this.paintComponent(g);
if(touchState){
g.fillOval(mousePoint.x, mousePoint.y, penSize, penSize);
}
}
public void DrawCanvas()
{
addMouseMotionListener(
new MouseMotionAdapter()
{
public void mouseMoved(MouseEvent evt)
{
mousePoint = evt.getPoint();
System.out.println(mousePoint);
}
}
);
}
}
DrawCanvas canvas = new DrawCanvas();
public Paint() {
initComponents();
jPanel2.add(canvas, BorderLayout.CENTER);
canvas.setBounds(canvas.getX() + 1, canvas.getY() + 1, 0, 0);
canvas.setSize(jPanel2.getSize().width - 2, jPanel2.getSize().height - 2);
}
/**
* 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() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jSlider1 = new javax.swing.JSlider();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jToggleButton1 = new javax.swing.JToggleButton();
jToggleButton2 = new javax.swing.JToggleButton();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Paint [Reyes, Duazo, Bermudo]"));
jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jPanel2.setPreferredSize(new java.awt.Dimension(400, 400));
jPanel2.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
jPanel2MouseDragged(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 396, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Drawing Tools"));
jLabel1.setText("Shapes");
jButton3.setText("Circle");
jButton4.setText("Rectangle");
jLabel2.setText("Custom Parameters");
jLabel3.setText("Pen Thickness");
jSlider1.setMajorTickSpacing(1);
jSlider1.setMaximum(50);
jSlider1.setMinimum(5);
jSlider1.setValue(5);
jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jSlider1StateChanged(evt);
}
});
jButton5.setText("Pen Color");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jButton6.setText("Background Color");
buttonGroup1.add(jToggleButton1);
jToggleButton1.setText("Pen");
buttonGroup1.add(jToggleButton2);
jToggleButton2.setText("Eraser");
jLabel4.setText("5");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSlider1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)
.addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1)
.addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)
.addComponent(jLabel2)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4))
.addComponent(jToggleButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jToggleButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jToggleButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jToggleButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton6)
.addContainerGap(163, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 466, Short.MAX_VALUE))
.addContainerGap())
);
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(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()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
Color color = JColorChooser.showDialog(Paint.this, "Choose a pen color", penColor);
if(color != null)
penColor = color;
}
private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {
jLabel4.setText(Integer.toString(jSlider1.getValue()));
}
private void jPanel2MouseDragged(java.awt.event.MouseEvent evt) {
touchState = true;
mousePoint = evt.getPoint();
System.out.println(mousePoint);
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(Paint.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Paint.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Paint.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Paint.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
new Paint().setVisible(true);
});
}
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JSlider jSlider1;
private javax.swing.JToggleButton jToggleButton1;
private javax.swing.JToggleButton jToggleButton2;
// End of variables declaration
}
2) Relevant to painting:
#Override
public void paint(Graphics g)
{
penSize = jSlider1.getValue();
penState = jToggleButton1.isSelected();
eraseState = jToggleButton2.isSelected();
setBackground(bgColor);
g.setColor(penColor);
this.paintComponent(g);
if(touchState){
g.fillOval(mousePoint.x, mousePoint.y, penSize, penSize);
}
}
3) Mouse Dragged Event
private void jPanel2MouseDragged(java.awt.event.MouseEvent evt) {
touchState = true;
mousePoint = evt.getPoint();
System.out.println(mousePoint);
repaint();
}
I would prefer to not have to use a data structure to store the value of every point and then repaint.
You're not calling the super's painting method within your paint method override, and this prevents component housekeeping painting from being done, including removal of "dirty" pixels. Suggestions:
Override a JPanel's paintComponent method, not its paint method
Call the related super's painting method as the first line of your override. So if you're overriding paintComponent(Graphics g), call super.paintComponent(g) on the first line.
If you need to draw multiple dots, then either draw them to a BufferedImage or create an ArrayList<Point> and place your points into the array list and iterate through them.

GridLayout in panel not showing buttons

I created a class that extends JPanel called GamePane which on creation sets the layout to a GridLayout and then adds buttons one at a time:
public class GamePane extends JPanel {
private JButton[][] buttons;
private final int sizeX, sizeY;
private Partida partida;
public GamePane(int sizeX, int sizeY, Partida p) {
super();
this.sizeX = sizeX;
this.sizeY = sizeY;
this.partida = p;
this.setLayout(new GridLayout(sizeX + 1, sizeY + 1));
buttons = new JButton[sizeX + 1][sizeY + 1];
for (int y = 0; y < sizeY + 1; y++) {
for (int x = 0; x < sizeX + 1; x++) {
JButton button = new JButton();
button.addActionListener(new ListenerGameButton(x, y, this));
this.add(button);
button.setBackground(Color.yellow);
button.setVisible(true);
buttons[x][y] = button;
}
}
The panel initialization is done on the parent JDialog:
gamePane = new GamePane(sizeX, sizeY, parentPartida);
And here's how it looks in the NetBeans editor: (The selected frame being an instance of GamePane)
Then when testing it out it doesn't show the buttons:
This is the class of the parent JDialog where the child GamePane is located, most of the code is autogenerated by Netbeans:
public class gameDialog extends javax.swing.JDialog {
private final int sizeX, sizeY;
private Partida parentPartida;
public gameDialog(java.awt.Frame parent, boolean modal, int sizeX, int sizeY, Partida parentPartida)
{
super(parent, modal);
this.parentPartida = parentPartida;
this.sizeX = sizeX;
this.sizeY = sizeY;
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
logoPane = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
gamePane = new GamePane(sizeX, sizeY, parentPartida);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Partida en curso");
setModal(true);
setResizable(false);
logoPane.setBackground(new java.awt.Color(95, 143, 191));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/logo.png"))); // NOI18N
jLabel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, new java.awt.Color(0, 0, 0), new java.awt.Color(0, 0, 0), new java.awt.Color(0, 0, 0), new java.awt.Color(0, 0, 0)));
jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout logoPaneLayout = new javax.swing.GroupLayout(logoPane);
logoPane.setLayout(logoPaneLayout);
logoPaneLayout.setHorizontalGroup(
logoPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
logoPaneLayout.setVerticalGroup(
logoPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
);
javax.swing.GroupLayout gamePaneLayout = new javax.swing.GroupLayout(gamePane);
gamePane.setLayout(gamePaneLayout);
gamePaneLayout.setHorizontalGroup(
gamePaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 437, Short.MAX_VALUE)
);
gamePaneLayout.setVerticalGroup(
gamePaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 353, 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(gamePane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(logoPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(logoPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(gamePane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
// Variables declaration - do not modify
private GUI.GamePane gamePane;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel logoPane;
// End of variables declaration
}
The initComponents() method is generated by NetBeans and that's where the GamePane is created and later on the frame is packed at the end of initComponents() by calling pack()
So, what am I doing wrong? Thanks in advance!
There is no problem with your code. It is perfectly working fine.
JDialog dialog = new JDialog();
dialog.getContentPane().add(new GamePane(10, 10));
dialog.pack();
dialog.setVisible(true);
And i got the below.

Why does my program freeze/crash when i try to run it?

This is not a complete program but im wondering why it freezez when i press the "JButton". I am Currently working on a dice game and so far its going fine but i cant understand why it wont run at the moment. Thanks for the help in beforehand :)
PS. The problem started after i added the while loop in the method diceLogic.
/*
* 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 dicegame_leonardasp;
/**
*
* #author LeoAsp
*/
import java.awt.Dimension;
import java.awt.Image;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.util.Random;
import javafx.scene.control.Cell;
public class DiceGameGui extends javax.swing.JFrame {
//Instansvariabel
//Skapa instans av Randomklassen
Random rand = new Random();
public DiceGameGui() {
initComponents();
}
public String doMessage() {
String message = "";
return message;
}
public String doReDice() {
String image = "";
int randNum = rand.nextInt(6 - 1) + 1;
if (randNum == 1) {
image = "one.gif";
} else if (randNum == 2) {
image = "two.gif";
} else if (randNum == 3) {
image = "three.gif";
} else if (randNum == 4) {
image = "four.gif";
} else if (randNum == 5) {
image = "five.gif";
} else if (randNum == 6) {
image = "six.gif";
} else {
dispose();
}
return image;
}
public void diceLogic(int players, int dice) {
jDiceResult.removeAll();
jDiceResult.setLayout(new java.awt.GridLayout(6, 5));
JLabel playersArray[][] = new JLabel[players][dice];
int j;
int i;
for (i = 0; i <= players; i++) {
for (j = 0; j < dice; j++) {
playersArray[i][j] = new JLabel();
playersArray[i][j].setIcon(new ImageIcon(doReDice()));
playersArray[i][j].setPreferredSize(new Dimension(60, 50));
// playersArray[i][j].setPreferredSize(new Dimension(20, 20));
//playersArray[i][j].setMinimumSize(new Dimension(20, 20));
//playersArray[i][j].setMaximumSize(new Dimension(20, 20));
jDiceResult.add(playersArray[i][j]);
jDiceResult.revalidate();
jDiceResult.repaint();
}
while (j <= 6) {
jDiceResult.add(javax.swing.Box.createGlue());
}
}
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jBoxPlayers = new javax.swing.JComboBox();
jBoxDice = new javax.swing.JComboBox();
jBtnRoll = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
jDiceResult = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Menlo", 0, 18)); // NOI18N
jLabel1.setText("Players:");
jLabel2.setFont(new java.awt.Font("Menlo", 0, 18)); // NOI18N
jLabel2.setText("Dice:");
jLabel3.setFont(new java.awt.Font("Menlo", 0, 18)); // NOI18N
jBoxPlayers.setFont(new java.awt.Font("Menlo", 1, 14)); // NOI18N
jBoxPlayers.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
"1", "2", "3", "4", "5"
}));
jBoxPlayers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBoxPlayersActionPerformed(evt);
}
});
jBoxDice.setFont(new java.awt.Font("Menlo", 1, 14)); // NOI18N
jBoxDice.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
"1", "2", "3", "4", "5", "6"
}));
jBoxDice.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBoxDiceActionPerformed(evt);
}
});
jBtnRoll.setFont(new java.awt.Font("Menlo", 0, 18)); // NOI18N
jBtnRoll.setText("Roll the Dice");
jBtnRoll.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBtnRollActionPerformed(evt);
}
});
jTextArea1.setEditable(false);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jButton1.setFont(new java.awt.Font("Menlo", 0, 14)); // NOI18N
jButton1.setText("Show Highscore");
jDiceResult.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
jDiceResult.setPreferredSize(new java.awt.Dimension(250, 300));
javax.swing.GroupLayout jDiceResultLayout = new javax.swing.GroupLayout(jDiceResult);
jDiceResult.setLayout(jDiceResultLayout);
jDiceResultLayout.setHorizontalGroup(
jDiceResultLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 246, Short.MAX_VALUE)
);
jDiceResultLayout.setVerticalGroup(
jDiceResultLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 296, 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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jBoxPlayers, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(91, 91, 91)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3))
.addComponent(jBoxDice, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jBtnRoll, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jDiceResult, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jBoxPlayers, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jBoxDice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jBtnRoll, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 347, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jDiceResult, 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 jBoxPlayersActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jBoxDiceActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jBtnRollActionPerformed(java.awt.event.ActionEvent evt) {
int dice = Integer.parseInt(jBoxDice.getSelectedItem().toString());
int players = Integer.parseInt(jBoxPlayers.getSelectedItem().toString());
diceLogic(players, dice);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
//<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(DiceGameGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DiceGameGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DiceGameGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DiceGameGui.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 DiceGameGui().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JComboBox jBoxDice;
private javax.swing.JComboBox jBoxPlayers;
private javax.swing.JButton jBtnRoll;
private javax.swing.JButton jButton1;
private javax.swing.JPanel jDiceResult;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
}
This is the problem:
while (j <= 6) {
jDiceResult.add(javax.swing.Box.createGlue());
}
With this line, you create a infinite loop, because you check whether j<=6 but don't change the value of j, so j<=6 is always true.
I guess you want to change while to if.
I guess:
while (j <= 6) {
jDiceResult.add(javax.swing.Box.createGlue());
}
I think may be it should be:
if (j <= 6) {
jDiceResult.add(javax.swing.Box.createGlue());
}

Adding JCheckBox Array to JPanel in Netbeans

I've been trying to add an array of JCheckBoxes to a JPanel in Netbeans that has been automatically generated by the Netbeans GUI, when I create an array of the JCheckBoxes and then try to add them to the JPanel using JPanel.add(jCheckboxArray[x]) , the program compiles ok but they don't appear.
I've created an array like so:
// custom private member variables
private javax.swing.JCheckBox[] jCheckboxArray;
//
int CheckBoxNumber = 5;
jCheckboxArray = new javax.swing.JCheckBox[CheckBoxNumber];
for(int x = 0; x < CheckBoxNumber ; x++) {
jCheckboxArray[x] = new javax.swing.JCheckBox();
jCheckboxArray[x].setText("CheckBox " + x);
}
I've tried setting viable but no result, and all the examples online appear to make a reference to adding the JPanel to a JFrame however no JFrame exists in the auto-generated code probably because the auto generated class extends javax.swing.JFrame.
Any help greatly appreciated.
Here is the entire code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package my.ArduinoGUI;
/**
*
* #author EEE
*/
public class ArduinoGUI extends javax.swing.JFrame {
/**
* Creates new form ArduinoGUI
*/
public ArduinoGUI() {
initCustomComponents();
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() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
jCheckBox1 = new javax.swing.JCheckBox();
jCheckBox2 = new javax.swing.JCheckBox();
jCheckBox3 = new javax.swing.JCheckBox();
jCheckBox4 = new javax.swing.JCheckBox();
jCheckBox5 = new javax.swing.JCheckBox();
jPanel2 = new javax.swing.JPanel();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jPanel3 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Outputs"));
jPanel1.setName("Outputs"); // NOI18N
jCheckBox1.setText("jCheckBox1");
jCheckBox2.setText("jCheckBox2");
jCheckBox3.setText("jCheckBox3");
jCheckBox4.setText("jCheckBox4");
jCheckBox5.setText("jCheckBox5");
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(jCheckBox1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jCheckBox5))
.addComponent(jCheckBox2)
.addComponent(jCheckBox3)
.addComponent(jCheckBox4))
.addContainerGap(39, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jCheckBox1)
.addComponent(jCheckBox5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jCheckBox2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jCheckBox3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jCheckBox4)
.addGap(0, 14, Short.MAX_VALUE))
);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("PinState"));
buttonGroup1.add(jRadioButton1);
jRadioButton1.setText("Input");
jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton1ActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButton2);
jRadioButton2.setText("Output");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(8, 8, 8)
.addComponent(jRadioButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButton2)
.addContainerGap(67, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(16, 16, 16)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jRadioButton1)
.addComponent(jRadioButton2))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Generated Boxes"));
int CheckBoxNumber = 5;
jCheckboxArray = new javax.swing.JCheckBox[CheckBoxNumber];
for(int x = 0; x < CheckBoxNumber ; x++) {
jCheckboxArray[x] = new javax.swing.JCheckBox();
System.out.print(x);
System.out.print(jCheckboxArray[x].getText());
jCheckboxArray[x].setText("CheckBox " + x);
System.out.print(jCheckboxArray[x].getText());
jPanel3.add(jCheckboxArray[x]);
}
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 175, 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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
pack();
}// </editor-fold>
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #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 ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.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 ArduinoGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JCheckBox jCheckBox2;
private javax.swing.JCheckBox jCheckBox3;
private javax.swing.JCheckBox jCheckBox4;
private javax.swing.JCheckBox jCheckBox5;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
// End of variables declaration
private javax.swing.JCheckBox[] jCheckboxArray;
private javax.swing.JPanel jPanel4;
private javax.swing.JCheckBox jCheckBox6;
private void initCustomComponents() {
//throw new UnsupportedOperationException("Not yet implemented");
// create checkbox array
}
}
I have given the example
public static void main(String args[]) {
String title = (args.length == 0 ? "CheckBox Sample" : args[0]);
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(0, 1));
Border border = BorderFactory.createTitledBorder("Test");
panel.setBorder(border);
javax.swing.JCheckBox[] jCheckboxArray;
//
int CheckBoxNumber = 5;
jCheckboxArray = new javax.swing.JCheckBox[CheckBoxNumber];
for(int x = 0; x < CheckBoxNumber ; x++) {
jCheckboxArray[x] = new javax.swing.JCheckBox();
jCheckboxArray[x].setText("CheckBox " + x);
panel.add(jCheckboxArray[x]);
}
Container contentPane = frame.getContentPane();
contentPane.add(panel, BorderLayout.CENTER);
// contentPane.add(button, BorderLayout.SOUTH);
frame.setSize(300, 200);
frame.setVisible(true);
}

action when component state changed

I have a series of radio buttons generated as an array and displayed in a jPanel.
I want a series of checkboxes in a second panel to be enbled when the radio buttons are in output state but not in the input (input or output are the radio choices).
I want to call the checking state method whenever any of the radiobuttons states change but don't know how to do this as they are created in an array.
Currently the method is called only when the radio button panel is actually clicked.
package my.ArduinoGUI;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
public class ArduinoGUI extends javax.swing.JFrame {
public ArduinoGUI() {
initCustomComponents();
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() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
digitalPinPanel = new javax.swing.JPanel(new GridLayout(0, 3));
jPanel3 = new javax.swing.JPanel(new GridLayout(0, 1));
jPanel2 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Outputs"));
jPanel1.setName("Outputs"); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 209, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 106, Short.MAX_VALUE)
);
digitalPinPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Digital Pin State"));
digitalPinPanel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
digitalPinPanelMouseReleased(evt);
}
});
digitalPinLabelArray = new javax.swing.JLabel[digitalPinTotal];
digitalPinRadioButtonArray = new javax.swing.JRadioButton[digitalPinTotal][2];
digitalPinGroupArray = new javax.swing.ButtonGroup[digitalPinTotal];
for(int x = 0; x < digitalPinTotal ; x++) {
digitalPinGroupArray[x] = new javax.swing.ButtonGroup(); // populate button group
digitalPinLabelArray[x] = new javax.swing.JLabel(); // populate label array
digitalPinLabelArray[x].setText("Pin " + (x +2));
digitalPinPanel.add(digitalPinLabelArray[x]); // add label to panel
for(int y = 0; y < 2; y++){
digitalPinRadioButtonArray[x][y] = new javax.swing.JRadioButton(); // populate radio button array
if (y == 0) {digitalPinRadioButtonArray[x][y].setText("Input");}
if (y == 1) {digitalPinRadioButtonArray[x][y].setText("Output"); digitalPinRadioButtonArray[x][y].setSelected(true);
}
digitalPinGroupArray[x].add(digitalPinRadioButtonArray[x][y]); // assign radio buttons to group
digitalPinPanel.add(digitalPinRadioButtonArray[x][y]); // add buttons to panel
}
}
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Generated Boxes"));
digitalPinOutputArray = new javax.swing.JCheckBox[digitalPinTotal];
for(int x = 0; x < digitalPinTotal ; x++) {
digitalPinOutputArray[x] = new javax.swing.JCheckBox();
digitalPinOutputArray[x].setText("Output Pin " + (x+2));
jPanel3.add(digitalPinOutputArray[x]);
}
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Analog Pin State"));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 126, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, 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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addComponent(digitalPinPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, 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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(digitalPinPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);
digitalPinPanel.getAccessibleContext().setAccessibleName("DigitalPins");
pack();
}// </editor-fold>
private void digitalPinPanelMouseReleased(java.awt.event.MouseEvent evt) {
// if output selected enable checkbox otherwise disable it
for (int x = 0; x < digitalPinTotal; x++) {
if (digitalPinRadioButtonArray[x][0].isSelected() == true) {
digitalPinOutputArray[x].setEnabled(false);
}
if (digitalPinRadioButtonArray[x][1].isSelected() == true) {
digitalPinOutputArray[x].setEnabled(true);
}
}
}
/**
* #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 ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.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 ArduinoGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JPanel digitalPinPanel;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
// End of variables declaration
private int digitalPinTotal = 12;
private int analogPinTotal = 8;
private javax.swing.JCheckBox[] digitalPinOutputArray;
private javax.swing.JRadioButton[][] digitalPinRadioButtonArray;
private javax.swing.ButtonGroup[] digitalPinGroupArray;
private javax.swing.JLabel[] digitalPinLabelArray;
private void initCustomComponents() {
//throw new UnsupportedOperationException("Not yet implemented");
// create checkbox array
}
}
digitalPinRadioButtonArray[x][y].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand().equals("Output"))
{
digitalPinOutputArray[2].setSelected(true);
}
}
});
try this

Categories

Resources