Position JPanel on JFrame - java

I have a problem with JPanel location. I started the creating a small game... I created 2 panels in design (on a JFrame). All worked good and the panels were on the correct places. In my game I have to use 2 graphic tables so I use 2 panels and I add every one of them panel set layout (new Grid Layout(10,10)).
After that I run the project to see how it works and I discover my panels in other places and with another size. I found the way that helps my to change back the size but I cannot found the way to change back the location or a way to give my own location...
I tried to add pictures that can show you what I see but the site blocked the pictures...
The code is:
public class GameFrame extends javax.swing.JFrame {
int [][]p1;
int [][]p1Attac;
int [][]p2;
int [][]p2Attac;
static int size=10;
int player;
JPanel [][]b1;
JPanel [][]b2;
int w=1100,h=900;
/**
* Creates new form GameFrame
* #param player1
* #param player2
*/
public GameFrame(int [][]player1, int [][]player2) {
initComponents();
// setSize(w, h);
setVisible(true);
// size=10;
p1=new int[size][size];
p1Attac=new int[size][size];
p2=new int[size][size];
p2Attac=new int[size][size];
b1=new JPanel[size][size];
b2=new JPanel[size][size];
init(player1, player2);
leftBoard.setBackground(Color.red);
rightBoard.setBackground(Color.blue);
GridLayout gl=new GridLayout(size, size);
leftBoard.setLayout(gl);
rightBoard.setLayout(gl);
for(int i=0;i<size;i++){
for(int j=0;j<size;j++){
b1[i][j]=new JPanel();
b1[i][j].setBorder(BorderFactory.createLineBorder(Color.black));
b1[i][j].setBackground(Color.red);
b2[i][j]=new JPanel();
b2[i][j].setBorder(BorderFactory.createLineBorder(Color.black));
b2[i][j].setBackground(Color.blue);
leftBoard.add(b1[i][j]);
rightBoard.add(b2[i][j]);
}
}
leftBoard.setPreferredSize(new Dimension(w/2-50, h/2));
rightBoard.setPreferredSize(new Dimension(w/2-50, h/2));
// leftBoard.setIgnoreRepaint(true);
// leftBoard.setLocation(0, h/5);
}
public void init(int [][]player1,int [][]player2){
for(int i=0;i<size;i++){
for(int j=0;j<size;j++){
p1[i][j]=player1[i][j];
p2[i][j]=player2[i][j];
p1Attac[i][j]=0;
p2Attac[i][j]=0;
}
}
}
/**
* 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() {
leftBoard = new javax.swing.JPanel();
rightBoard = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout leftBoardLayout = new javax.swing.GroupLayout(leftBoard);
leftBoard.setLayout(leftBoardLayout);
leftBoardLayout.setHorizontalGroup(
leftBoardLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 523, Short.MAX_VALUE)
);
leftBoardLayout.setVerticalGroup(
leftBoardLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 498, Short.MAX_VALUE)
);
javax.swing.GroupLayout rightBoardLayout = new javax.swing.GroupLayout(rightBoard);
rightBoard.setLayout(rightBoardLayout);
rightBoardLayout.setHorizontalGroup(
rightBoardLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 547, Short.MAX_VALUE)
);
rightBoardLayout.setVerticalGroup(
rightBoardLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 498, Short.MAX_VALUE)
);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
jLabel1.setText("Enemy Attacs:");
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
jLabel2.setText("Your Attacs:");
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(57, 57, 57)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(leftBoard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(118, 118, 118)
.addComponent(rightBoard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(193, 193, 193)
.addComponent(jLabel2)))
.addContainerGap(43, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(15, 15, 15)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3)
.addComponent(leftBoard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(rightBoard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(65, 65, 65))
);
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(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*int [][]p1=new int[size][size];
int [][]p2=new int[size][size];
for(int i=0;i<size;i++)
for(int j=0;j<size;j++){
p1[i][j]=0;
p2[i][j]=0;
}
p1[0][0]=p1[1][0]=p1[2][0]=p1[3][0]=4;
p1[0][3]=p1[1][3]=p1[2][3]=3;
p1[5][3]=p1[6][3]=p1[7][3]=3;
p1[0][3]=p1[1][3]=2;*/
int [][]p1={
{4,4,4,4,0,1,0,0,0,0},
{0,0,0,0,0,0,0,1,0,0},
{3,3,3,0,3,0,0,0,0,0},
{0,0,0,0,3,0,0,0,0,0},
{2,2,0,0,3,0,0,1,0,0},
{0,0,0,0,0,1,0,0,0,0},
{0,0,0,0,0,0,0,2,2,0},
{0,0,0,5,0,0,0,0,0,0},
{0,0,0,0,0,0,5,0,2,2},
{0,0,0,0,0,0,0,0,0,0}
};
int [][]p2={
{0,1,0,0,1,0,0,2,2,0},
{0,0,0,0,0,0,0,0,0,0},
{0,0,1,0,1,0,2,2,0,0},
{0,0,0,0,0,0,0,0,0,0},
{0,5,0,0,3,0,0,2,0,0},
{0,0,0,0,3,0,0,2,0,0},
{0,0,0,0,3,0,0,0,0,0},
{0,0,0,0,0,0,4,4,4,4},
{0,3,3,3,0,0,0,0,0,0},
{0,0,0,0,0,0,5,0,0,0}
};
new GameFrame(p1, p2);
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
// new GameFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel leftBoard;
private javax.swing.JPanel rightBoard;
// End of variables declaration
}

Thanks to #AndrewThompson for giving important ideas for this problem (GridLayout, Titled Borders). I've waited about 30 minutes to see if he'd post his own answer. He didn't, so I decided to post my own - I hope no-one is mad at me.
Don't use Grouplayout for this, IMO it just makes things complicated and user-unfriendly (at least in this case). Instead you can achieve everything with simple GridLayouts. (with much less code, resizeable) I've created an example that shows you how:
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class GameFrame {
JPanel[][] arrayL = new JPanel[10][10];
JPanel[][] arrayR = new JPanel[10][10];
public GameFrame() {
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new GridLayout(1, 2));
JPanel left = new JPanel(new GridLayout(10, 10, 1, 1));
left.setBorder(BorderFactory.createTitledBorder(new EmptyBorder(0, 0,
0, 0), "Enemy"));
((TitledBorder) left.getBorder()).setTitleFont(new Font("Arial", Font.BOLD, 20));
addCells(left, arrayL, Color.RED);
JPanel right = new JPanel(new GridLayout(10, 10, 1, 1));
right.setBorder(BorderFactory.createTitledBorder(new EmptyBorder(0, 0,
0, 0), "You"));
((TitledBorder) right.getBorder()).setTitleFont(new Font("Arial", Font.BOLD, 20));
addCells(right, arrayR, Color.BLUE);
JPanel leftPanel = new JPanel();
leftPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
leftPanel.setLayout(new GridLayout(1, 1));
leftPanel.add(left);
JPanel rightPanel = new JPanel();
rightPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
rightPanel.setLayout(new GridLayout(1, 1));
rightPanel.add(right);
frame.getContentPane().add(leftPanel);
frame.getContentPane().add(rightPanel);
frame.setSize(500, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void addCells(JPanel panel, JPanel[][] array, Color color) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
JPanel p = new JPanel();
p.setBackground(color);
p.setBorder(BorderFactory.createLineBorder(Color.BLACK));
array[j][i] = p;
panel.add(p);
}
}
}
public static void main(String[] args) {
new GameFrame();
}
}

One issue is that the initComponents() generated by the Netbeans GUI builder has layout which is being messed up by the code run later in the constructor.
The way to fix this is using the Customize Code .. right-click menu option in the designer. Putting your code there will allow you to keep the outer design set by the Gui Builder and add internal custom components. After that you can comment out all the code in the constructor.

Related

Basically what i want is to display the usb directoires and a local drive directoires in two jscrollpane side by side

I have made two JScrollPane components. The left one shows the directories in USB and right shows the directories of a local drive. For I am able to display the complete file path as shown in first pic. But I want to display it with icons just like the way directories are displayed in any local drive on PC. This is my designed GUI, here is the example of what I want example
public class MainForm extends javax.swing.JFrame {
iRecordCopy obj = new iRecordCopy();
public MainForm() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jScrollPane2 = new javax.swing.JScrollPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Main From");
setLocation(new java.awt.Point(0, 0));
setName("mainframe"); // NOI18N
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jLabel1.setText("iRecordCopy");
jLabel2.setText("jLabel2");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addGap(48, 48, 48)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(25, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(30, 30, 30))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)
.addComponent(jScrollPane2))
.addContainerGap())
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainForm().setVisible(true);
}
});
}
public void showusb()
{
File[] usb;
int count = 0;
String str;
usb = obj.detectUSB();
if(usb == null)
{
//USB_window.setText("No USB attached\n");
return;
}
for (File filename : usb) {
str = filename.toString().substring(3);
str = str.substring(0, str.length() - 3);
System.out.println(str);
if(str.equalsIgnoreCase("vehicle"))
{
System.out.print(filename.toString());
//USB_window.append(filename.getPath()+"\n");
count++;
}
}
if(count == 0)
{
System.out.println("No recordings found in usb");
}
else
System.out.println("Number of directries :" + count);
//File currentDir = new File(System.getProperty("user.home"));
JList<File> jlist=new JList<File>(obj.path.listFiles());
jScrollPane1 = new JScrollPane(jlist);
jScrollPane1.setPreferredSize(new Dimension(400, 800));
setContentPane(jScrollPane1);
final JLabel label=new JLabel();
jlist.setCellRenderer(new ListCellRenderer<File>() {
#Override
public Component getListCellRendererComponent(JList<? extends File> list, File value, int index,
boolean isSelected, boolean cellHasFocus) {
label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(value));
label.setText(value.getName());
return label;
}
});
}
public void showPc(File f)
{
JList<File> jlist=new JList<File>(f.listFiles());
jScrollPane2 = new JScrollPane(jlist);
//jScrollPane2.setPreferredSize(new Dimension(400, 800));
setContentPane(jScrollPane2);
final JLabel label=new JLabel();
jlist.setCellRenderer(new ListCellRenderer<File>() {
#Override
public Component getListCellRendererComponent(JList<? extends File> list, File value, int index,
boolean isSelected, boolean cellHasFocus) {
label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(value));
label.setText(value.getName());
return label;
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
// End of variables declaration
}
Here a short example to create a minimal JList with file icons, it displays the content of the user's home directory using the system file icons.
package test;
import java.awt.Component;
import java.awt.Dimension;
import java.io.File;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.filechooser.FileSystemView;
public class Test {
public static void main(String[] args) {
JFrame frame=new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
File currentDir=new File(System.getProperty("user.home"));
JList<File> jlist=new JList<File>(currentDir.listFiles());
JScrollPane scrollPane=new JScrollPane(jlist);
scrollPane.setPreferredSize(new Dimension(400, 800));
frame.setContentPane(scrollPane);
final JLabel label=new JLabel();
jlist.setCellRenderer(new ListCellRenderer<File>() {
#Override
public Component getListCellRendererComponent(JList<? extends File> list, File value, int index,
boolean isSelected, boolean cellHasFocus) {
label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(value));
label.setText(value.getName());
return label;
}
});
frame.pack();
frame.setVisible(true);
}
}

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.

JPanel not showing Components

So let's start with some background this is for a first year collage project. the GUI is built so one class, the interface-handler calls all the JPanels and puts them in the right place. This is for structure and so it's easy to maintain.
the problem is the panel holding the menu does't show it's components after it's added. i'll include some image's so it's easier to understand.
The panel in question is called MenuPanel.
so here is the login button which currently only clears the contentpanel and then adds the menupanel.
Login page where the button is located
and here is the menu panel empty
here is the menu panel all empty
the code
The interface handler
you can see me messing around with the .repaint() method in the menu method already.
public class InterfaceHandler {
private static InterfaceHandler singleton;
/**
* Checks if there is already a instance running of InterfaceHandler if so
* return the instance if not create a instance.
*
* #return Instance
*/
public static InterfaceHandler instance() {
if (singleton == null) {
singleton = new InterfaceHandler();
}
return singleton;
}
private ContentPanel contentPanel;
private LoginPanel loginPanel;
private MainFrame mainFrame;
private MainPanel mainPanel;
private MenuPanel menuPanel;
/**
* Initializes default Interface
*/
public InterfaceHandler() {
initComponents();
}
/**
* Initializes GUI Components that will be needed now or in the future.
*/
public void initComponents() {
mainFrame = new MainFrame();
mainPanel = new MainPanel();
contentPanel = new ContentPanel();
loginPanel = new LoginPanel();
menuPanel = new MenuPanel();
contentPanel.setBounds(100, 100, 860, 700);
menuPanel.setBounds(10, 10, 80, 400);
loginPanel.setBounds(280, 250, 300, 200);
mainFrame.add(mainPanel);
mainPanel.add(contentPanel);
mainFrame.setVisible(true);
contentPanel.add(loginPanel);
}
/**
* Clears the ContentPanel of all components
*/
public void clear() {
System.out.println("Clear Ran");
contentPanel.removeAll();
contentPanel.repaint();
}
/**
* Adds the Login Screen.
*/
public void login() {
System.out.println("Login Ran");
contentPanel.add(loginPanel);
contentPanel.repaint();
}
/**
* Adds the menu.
*/
public void menu() {
System.out.println("Menu Ran");
mainPanel.sidePanel.add(menuPanel);
menuPanel.repaint();
mainPanel.repaint();
mainPanel.sidePanel.repaint();
}
}
And here is the code for the panel, Most of it is autogenerated by the netbeans design editor.
so it's ugly (i'm sorry)
public class MenuPanel extends javax.swing.JPanel {
/**
* Creates new form MenuPanel
*/
public MenuPanel() {
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() {
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jLabel2 = new javax.swing.JLabel();
baggageButton = new javax.swing.JLabel();
jLabel1.setBackground(new java.awt.Color(204, 204, 204));
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Menu");
jSeparator1.setBackground(new java.awt.Color(204, 204, 204));
baggageButton.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
baggageButton.setText("Baggage");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(baggageButton, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, 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(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 4, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(baggageButton, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JLabel baggageButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JSeparator jSeparator1;
// End of variables declaration
}
just to clarify, the method menu is called from a different class.
If you are adding components to an already visible panel, you need to call validate().
public void menu() {
System.out.println("Menu Ran");
mainPanel.sidePanel.add(menuPanel);
mainPanel.sidePanel.validate(); // try this
menuPanel.repaint();
mainPanel.repaint();
mainPanel.sidePanel.repaint();
}
(This answer is wrong but the ensuing comments do help understand why #whiskeyspider's answer is right)
In this code:
mainFrame.add(mainPanel);
mainPanel.add(contentPanel);
mainFrame.setVisible(true);
contentPanel.add(loginPanel);
You're not adding menuPanel anywhere. It is added (too late) in the menu() method, but that's not being called.

Sliding any JPanel

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)

NetBeans IDE issue adding grid layout

I have created a design of my application with net beans programme . I would like to add a 30*30 grid layout something similar to sudoku .Actually I am trying to draw a 30*30 of squares for map. However , I am not able to add that view to my code .I have searched lots of places but I am not able to find an answer .I am open to your ideas. Could anyone help me in this subject please ? Thank you !
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.JTextField;
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() {
getDirectionButton = new javax.swing.JButton();
questionTitle = new java.awt.Label();
questionText = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
directionDescriptionArea = new javax.swing.JTextArea();
walkingManButton = new javax.swing.JButton();
java.awt.Panel mapPanel = new java.awt.Panel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("DSL For Streets\n");
setPreferredSize(new java.awt.Dimension(1365, 730));
getDirectionButton.setText("Get Direction");
questionTitle.setFont(new java.awt.Font("Dialog", 3, 12)); // NOI18N
questionTitle.setText("Please enter your question");
directionDescriptionArea.setColumns(20);
directionDescriptionArea.setRows(5);
jScrollPane1.setViewportView(directionDescriptionArea);
walkingManButton.setFont(new java.awt.Font("Tahoma", 3, 11)); // NOI18N
walkingManButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("walk.png"))); // NOI18N
walkingManButton.setText("Get Suggested Route");
walkingManButton.setFocusable(false);
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("map.png"))); // NOI18N
cells = new int[ROWS][COLS];
tfCells = new JTextField[ROWS][COLS]; // allocate JTextField array
// Container cp = getContentPane();
//cp.setLayout(new GridLayout(ROWS, COLS));
mapPanel.setLayout(new GridLayout(ROWS, COLS));
// Create 9x9 JTextFields and place on the GridLayout
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
tfCells[row][col] = new JTextField(); // allocate element of array
mapPanel. add(tfCells[row][col]); // ContentPane adds JTextField
int number = puzzle[row][col];
tfCells[row][col].setText(""); // empty
tfCells[row][col].setHorizontalAlignment(JTextField.CENTER);
tfCells[row][col].setFont(new Font("Monospaced", Font.BOLD, 20));
}
}
javax.swing.GroupLayout mapPanelLayout = new javax.swing.GroupLayout(mapPanel);
mapPanel.setLayout(mapPanelLayout);
mapPanelLayout.setHorizontalGroup(
mapPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mapPanelLayout.createSequentialGroup()
.addGap(181, 181, 181)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(239, Short.MAX_VALUE))
.addGroup(mapPanelLayout.createSequentialGroup()
.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()
.addGap(36, 36, 36)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(getDirectionButton, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(questionTitle, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(questionText, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addComponent(walkingManButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 451, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(mapPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(46, 46, 46))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(questionTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(questionText, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(getDirectionButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25)
.addComponent(walkingManButton, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE))
.addComponent(mapPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
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(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.JTextArea directionDescriptionArea;
private javax.swing.JButton getDirectionButton;
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField questionText;
private java.awt.Label questionTitle;
private javax.swing.JButton walkingManButton;
private javax.swing.JTextField a[]=new JTextField[30];
// End of variables declaration
public static final int ROWS = 9; // ROWS by COLS cells
public static final int COLS = 9;
public static final int CELL_SIZE = 10; // Cell width/height
public static final int CANVAS_WIDTH = CELL_SIZE * COLS;
public static final int CANVAS_HEIGHT = CELL_SIZE * ROWS;
private int[][] cells;
private JTextField[][] tfCells;
private int[][] puzzle =new int[9][9];
}
If you're using Netbeans, you can do that with the GUI Builder. Simply go to the Design View, right click on the underlying container you're going to use for this (some JPanel), go to "Set Layout" option in the context menu and pick "Grid Layout". To edit its properties, go to the Navigator window (usually on the left), browse your components until you see the container in question, collapse it and select the GridLayout. You can now change some properties, like the rows and columns, on the properties window (usually on the right). Then, you drag other components on top of that container.
Though, by your description, I wonder if what you're really looking for is a JTable, which is a component that lets you display your data in a grid.

Categories

Resources