Add JLabel Array to JPanel - java

I created a JPanel Grid and now I want add Array of image Slices to Grid with loop
in last line I have error.
public static final int WIDTH = 1024;
public static final int HEIGHT = 640;
private static final int GRID_ROWS = 20;
private static final int GRID_COLS = 20;
private static final int GAP = 1;
private static final Dimension LAYERED_PANE_SIZE = new Dimension(WIDTH, HEIGHT);
private static final Dimension LABEL_SIZE = new Dimension(60, 40);
private GridLayout gridlayout = new GridLayout(GRID_ROWS, GRID_COLS, GAP, GAP);
private JPanel backingPanel = new JPanel(gridlayout);
private JPanel[][] panelGrid = new JPanel[GRID_ROWS][GRID_COLS];
private JLabel redLabel = new JLabel("Red", SwingConstants.CENTER);
private JLabel blueLabel = new JLabel("Blue", SwingConstants.CENTER);
// code in constructor
backingPanel.setSize(LAYERED_PANE_SIZE);
backingPanel.setLocation(2 * GAP, 2 * GAP);
backingPanel.setBackground(Color.black);
for (int row = 0; row < GRID_ROWS; row++) {
for (int col = 0; col < GRID_COLS; col++) {
panelGrid[row][col] = new JPanel(new GridBagLayout());
backingPanel.add(panelGrid[row][col]);
}
}
setLayout(new GridLayout(GRID_ROWS, GRID_COLS));
BufferedImage bi = null;
try {
bi = ImageIO.read(new File("assets/image.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
for (int r = 0; r < GRID_ROWS; r++) {
for (int c = 0; c < GRID_COLS; c++) {
int w = bi.getWidth() / GRID_ROWS;
int h = bi.getHeight() / GRID_COLS;
BufferedImage b = bi.getSubimage(c * w, r * h, w, h);
list.add(new JLabel(new ImageIcon(b)));
panelGrid[r][c] = new JPanel(new GridBagLayout());
backingPanel.add(panelGrid[r][c]);
panelGrid[r][c].add(list.get(r));
}
}

Since list is an instance of List, and Java is not C++, you cant specify methods like operator[]. You need to use list.get(), like this:
panelGrid[r][c].add(list.get(r));
Also, you should use a GridBagLayout with GridBagConstraints. Therefore, call
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
And change the lines where you add the panel to this:
panelGrid[r][c] = new JPanel(new GridBagLayout());
panelGrid[r][c].add(list.get(r));
gbc.gridx = r; gbc.gridy = c;
backingPanel.add(panelGrid[r][c], gbc);

Related

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "null"

package Unit2Exam;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Unit2Exam {
static int r;
static int g;
static int b;
static int rb;
static int rg;
static int on;
static int rr;
static int i;
public static JTextField field1;
public static JTextField field2;
public static JTextField field3;
public static void main(String[] args) {
//This is my constructor for the Math class, it allows me to import methods from that class
//final Math a = new Math();
final Unit2Exam Calculator = new Unit2Exam();
//Makes a font
Font font = new Font("Verdana", Font.PLAIN, 12);
GridBagConstraints grid = new GridBagConstraints();
//This creates the JFRAMES
JFrame frame = new JFrame("Free Fall Application");
//This sets the title
JPanel panel = new JPanel(new GridBagLayout());
//makes and adds the panel
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
grid.fill = GridBagConstraints.BOTH;
JFrame colors = new JFrame("Colors");
JPanel colorPanel = new JPanel(new GridBagLayout());
colors.add(colorPanel);
colors.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
grid.fill = GridBagConstraints.BOTH;
//causes the jbuttons to fill the borders (to make it look better)
grid.weightx = 1;
grid.weighty = 1;
// frame.setSize(new Dimension(200, 200));
frame.setResizable(false);
colors.setResizable(false);
colors.setVisible(true);
colorPanel.setVisible(true);
frame.setVisible(true);
panel.setVisible(true);
//This is where I implement all of the J stuff (i.e. Buttons, Textfields, and JLabels)
JLabel title = new JLabel("Jonathan Kipper");
JLabel label1 = new JLabel("Initial Velocity (m/s):");
JLabel label2 = new JLabel("Time (Seconds):");
JLabel label3 = new JLabel("Distance (meters):");
JTextField field1 = new JTextField(6);
JTextField field2 = new JTextField(6);
JTextField field3 = new JTextField(6);
JButton button1 = new JButton("Calculate");
JButton button2 = new JButton("Clear");
JButton colorButton = new JButton();
grid.gridx = 0;
grid.gridy = 0;
panel.add(title, grid);
title.setVisible(true);
title.setFont(font);
grid.gridx = 0;
grid.gridy = 1;
panel.add(label1, grid);
label1.setVisible(true);
label1.setFont(font);
grid.gridx = 0;
grid.gridy = 2;
panel.add(label2, grid);
label2.setVisible(true);
label2.setFont(font);
grid.gridx = 0;
grid.gridy = 3;
panel.add(label3, grid);
label3.setVisible(true);
label3.setFont(font);
grid.gridx = 1;
grid.gridy = 1;
panel.add(field1, grid);
field1.setVisible(true);
grid.gridx = 1;
grid.gridy = 2;
panel.add(field2, grid);
field2.setVisible(true);
grid.gridx = 1;
grid.gridy = 3;
panel.add(field3, grid);
field3.setText("");
field3.setVisible(true);
grid.gridx = 0;
grid.gridy = 4;
panel.add(button1, grid);
button1.setVisible(true);
grid.gridx = 1;
grid.gridy = 4;
panel.add(button2, grid);
button2.setVisible(true);
button2.setFont(font);
frame.pack();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width / 2 - frame.getSize().width / 2, dim.height / 2 - frame.getSize().height / 2);
frame.setSize(250, 150);
grid.gridx=0;
grid.gridy=0;
colorPanel.add(colorButton, grid);
colorButton.setText("Click to stop colors");
colorButton.setVisible(true);
colors.pack();
Dimension dimz = Toolkit.getDefaultToolkit().getScreenSize();
colors.setLocation(dimz.width / 3 - frame.getSize().width / 3, dimz.height / 2 - frame.getSize().height / 2);
colors.setSize(200, 150);
i=1;
//Infinite for loop
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
double zzz = Calculator.distance();
String za = String.valueOf(zzz);
field3.setText(za);
}
});
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
field1.setText("");
field2.setText("");
field3.setText("");
}
});
colorButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (i == 1) {
colorButton.setText("Click here to start");
i = 0;
} else if (i == 0) {
colorButton.setText("Click here to stop");
i = 1;
}
}
});
on = 0;
r = 0;
g = 0;
b = 0;
rr = 255;
rg = 255;
rb = 255;
//This is the loop for the color changing
while (i != 0) {
//Colors
Color color = new Color(r, g, b);
Color rcolor = new Color(rr, rg, rb);
//Panels
panel.setBackground(color);
frame.setBackground(color);
//Buttons
button1.setBackground(rcolor);
button2.setBackground(rcolor);
colorButton.setBackground(rcolor);
//Labels
label1.setForeground(rcolor);
label2.setForeground(rcolor);
label3.setForeground(rcolor);
title.setForeground(rcolor);
//Text fields
field1.setForeground(rcolor);
field2.setForeground(rcolor);
field3.setForeground(rcolor);
field1.setBackground(color);
field2.setBackground(color);
field3.setBackground(color);
//Sets a slight delay to avoid seizures
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Goes through the different colors
if (on == 0) {
if (r == 255) {
on = 1;
} else {
r++;
rr--;
}
} else if (on == 1) {
if (g == 255) {
on = 2;
} else {
g++;
rg--;
}
} else if (on == 2) {
if (b == 255) {
on = 3;
} else {
b++;
rb--;
}
} else if (on == 3) {
if (r == 0) {
on = 4;
} else {
r--;
rr++;
}
} else if (on == 4) {
if (g == 0) {
on = 5;
} else {
g--;
rg++;
}
} else if (on == 5) {
if (b == 0) {
on = 0;
} else {
b--;
rb++;
}
}
}
}
public static double distance(){
String d = field1.getText();
double velocity = Double.parseDouble(d);
String dd = field2.getText();
double time = Double.valueOf(dd);
double totalDistance = (velocity * time) + (4.9 * (time * time));
return totalDistance;
}
}
UPDATE: I can't leave the method as a public static void because it errors out when trying to call it to return a value. I've changed the strings to field.getText(); instead of the String.valueOf(field); It keeps giving me nullpoint errors in the method and when I call the method earlier in the program.
Uhm, you are trying to get the String by
String.valueOf(JTextField)
Thats doing something waaay different from what you want. You can get the Text of the Field by:
e.g. String d = field1.getText();
Edit:
I dont think, Unit2Exam has a purpose, but on your button, you are still using it. First of all, declare distance as static Method:
public static void distance()
Then, replace in your ActionListener
aa.distance()
with
Calculator.distance()
Edit 2:
So, another answer.
First of all, your code is quite messed up, i assume you are new to java. Let me tell you your mistakes:
First of all:
final Unit2Exam Calculator = new Unit2Exam();
Since you have no constructor, you dont need this. Cut it out.
Second:
The reason, why youre field returns null, is because:
JTextField field1 = new JTextField(6);
JTextField field2 = new JTextField(6);
JTextField field3 = new JTextField(6);
creates a local Textfield called field1, which has nothing to do with your global JTextField field1, which stays empty for the rest of its life.
Just remove the "JTextField" before each declaration and it should work:
field1 = new JTextField(6);
field2 = new JTextField(6);
field3 = new JTextField(6);
Final result:
package Unit2Exam;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Unit2Exam {
static int r;
static int g;
static int b;
static int rb;
static int rg;
static int on;
static int rr;
static int i;
public static JTextField field1;
public static JTextField field2;
public static JTextField field3;
public static void main(String[] args) {
//Makes a font
Font font = new Font("Verdana", Font.PLAIN, 12);
GridBagConstraints grid = new GridBagConstraints();
//This creates the JFRAMES
JFrame frame = new JFrame("Free Fall Application");
//This sets the title
JPanel panel = new JPanel(new GridBagLayout());
//makes and adds the panel
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
grid.fill = GridBagConstraints.BOTH;
JFrame colors = new JFrame("Colors");
JPanel colorPanel = new JPanel(new GridBagLayout());
colors.add(colorPanel);
colors.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
grid.fill = GridBagConstraints.BOTH;
//causes the jbuttons to fill the borders (to make it look better)
grid.weightx = 1;
grid.weighty = 1;
// frame.setSize(new Dimension(200, 200));
frame.setResizable(false);
colors.setResizable(false);
colors.setVisible(true);
colorPanel.setVisible(true);
frame.setVisible(true);
panel.setVisible(true);
//This is where I implement all of the J stuff (i.e. Buttons, Textfields, and JLabels)
JLabel title = new JLabel("Jonathan Kipper");
JLabel label1 = new JLabel("Initial Velocity (m/s):");
JLabel label2 = new JLabel("Time (Seconds):");
JLabel label3 = new JLabel("Distance (meters):");
field1 = new JTextField(6);
field2 = new JTextField(6);
field3 = new JTextField(6);
JButton button1 = new JButton("Calculate");
JButton button2 = new JButton("Clear");
JButton colorButton = new JButton();
grid.gridx = 0;
grid.gridy = 0;
panel.add(title, grid);
title.setVisible(true);
title.setFont(font);
grid.gridx = 0;
grid.gridy = 1;
panel.add(label1, grid);
label1.setVisible(true);
label1.setFont(font);
grid.gridx = 0;
grid.gridy = 2;
panel.add(label2, grid);
label2.setVisible(true);
label2.setFont(font);
grid.gridx = 0;
grid.gridy = 3;
panel.add(label3, grid);
label3.setVisible(true);
label3.setFont(font);
grid.gridx = 1;
grid.gridy = 1;
panel.add(field1, grid);
field1.setVisible(true);
grid.gridx = 1;
grid.gridy = 2;
panel.add(field2, grid);
field2.setVisible(true);
grid.gridx = 1;
grid.gridy = 3;
panel.add(field3, grid);
field3.setText("");
field3.setVisible(true);
grid.gridx = 0;
grid.gridy = 4;
panel.add(button1, grid);
button1.setVisible(true);
grid.gridx = 1;
grid.gridy = 4;
panel.add(button2, grid);
button2.setVisible(true);
button2.setFont(font);
frame.pack();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width / 2 - frame.getSize().width / 2, dim.height / 2 - frame.getSize().height / 2);
frame.setSize(250, 150);
grid.gridx=0;
grid.gridy=0;
colorPanel.add(colorButton, grid);
colorButton.setText("Click to stop colors");
colorButton.setVisible(true);
colors.pack();
Dimension dimz = Toolkit.getDefaultToolkit().getScreenSize();
colors.setLocation(dimz.width / 3 - frame.getSize().width / 3, dimz.height / 2 - frame.getSize().height / 2);
colors.setSize(200, 150);
i=1;
//Infinite for loop
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
double zzz = Unit2Exam.distance();
String za = String.valueOf(zzz);
field3.setText(za);
}
});
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
field1.setText("");
field2.setText("");
field3.setText("");
}
});
colorButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (i == 1) {
colorButton.setText("Click here to start");
i = 0;
} else if (i == 0) {
colorButton.setText("Click here to stop");
i = 1;
}
}
});
on = 0;
r = 0;
g = 0;
b = 0;
rr = 255;
rg = 255;
rb = 255;
//This is the loop for the color changing
while (i != 0) {
//Colors
Color color = new Color(r, g, b);
Color rcolor = new Color(rr, rg, rb);
//Panels
panel.setBackground(color);
frame.setBackground(color);
//Buttons
button1.setBackground(rcolor);
button2.setBackground(rcolor);
colorButton.setBackground(rcolor);
//Labels
label1.setForeground(rcolor);
label2.setForeground(rcolor);
label3.setForeground(rcolor);
title.setForeground(rcolor);
//Text fields
field1.setForeground(rcolor);
field2.setForeground(rcolor);
field3.setForeground(rcolor);
field1.setBackground(color);
field2.setBackground(color);
field3.setBackground(color);
//Sets a slight delay to avoid seizures
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Goes through the different colors
if (on == 0) {
if (r == 255) {
on = 1;
} else {
r++;
rr--;
}
} else if (on == 1) {
if (g == 255) {
on = 2;
} else {
g++;
rg--;
}
} else if (on == 2) {
if (b == 255) {
on = 3;
} else {
b++;
rb--;
}
} else if (on == 3) {
if (r == 0) {
on = 4;
} else {
r--;
rr++;
}
} else if (on == 4) {
if (g == 0) {
on = 5;
} else {
g--;
rg++;
}
} else if (on == 5) {
if (b == 0) {
on = 0;
} else {
b--;
rb++;
}
}
}
}
public static double distance(){
String d = field1.getText();
double velocity = Double.parseDouble(d);
String dd = field2.getText();
double time = Double.valueOf(dd);
double totalDistance = (velocity * time) + (4.9 * (time * time));
return totalDistance;
}
I change it to
public double distance() {
String d = field1.getText();
double velocity = Double.parseDouble(d);
String dd = field2.getText();
double time = Double.valueOf(dd);
double totalDistance = (velocity * time) + (4.9 * (time * time));
return totalDistance;
}
However I'm still getting a null pointer exception. It changed the error slightly however. It's saying on line 273, which is the:
String d = field1.getText();
is an issue.

Java out of bounds error but I am sure it's declared properly

This GUI is made from javax.swing. I'm wondering why it throws Array Index Out of Bounds exception but I'm sure that it's declared properly. I also tried running tests inside the for loops of the instantiation of the cells and the resetting of the cells but it still won't work. When I tried printing the i and j of the loop in the resetFields actionEvent it doesn't really go out of bounds but it says it goes out of bounds.
I found out that col adds one to itself when it goes to the actionPerformed function which is kinda weird.
NOTE: I get the row and col from the main class in another Java file.
Here's the full code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExperimentalFrame extends JFrame implements ActionListener
{
private int row, col;
private JTextField cells[][];
private JPanel matrix;
private JButton compute1;
private JButton reset;
private JButton showSolution1;
private JButton resetFields;
private JPanel matrixPanel;
private JPanel mainPanel;
private JPanel buttonPanel;
private JLabel theory;
private JPanel theoryPanel;
private JLabel header[];
public ExperimentalFrame(int row, int col)
{
this.row = row; this.col = col;
theoryPanel = new JPanel();
theory = new JLabel("Theory here");
mainPanel = new JPanel();
matrix = new JPanel();
matrixPanel = new JPanel();
buttonPanel = new JPanel();
cells = new JTextField[row][col];
header = new JLabel[col];
compute1 = new JButton("Compute");
reset = new JButton("Reset");
showSolution1 = new JButton("Show Solution");
resetFields = new JButton("Reset Fields");
GridBagConstraints gbc = new GridBagConstraints();
GridBagConstraints gbc2 = new GridBagConstraints();
GridBagConstraints gbc1 = new GridBagConstraints();
matrixPanel.setLayout(new GridBagLayout());
matrix.setLayout(new GridBagLayout());
mainPanel.setLayout(new GridBagLayout());
theoryPanel.setLayout(new GridBagLayout());
buttonPanel.setLayout(new GridBagLayout());
compute1.addActionListener(this);
reset.addActionListener(this);
showSolution1.addActionListener(this);
resetFields.addActionListener(this);
gbc1.gridx = 1;
gbc1.gridy = 1;
gbc1.insets = new Insets(10,10,10,10);
theoryPanel.add(theory);
mainPanel.add(theoryPanel, gbc1);
for (int j = 0; j < col; j++)
{
gbc.gridy = 1;
gbc.gridx = j + 2;
if (j != (col - 1))
header[j] = new JLabel("I" + (j + 1));
else
header[j] = new JLabel("x");
matrix.add(header[j], gbc);
}
gbc.insets = new Insets(5, 5, 5, 5);
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
gbc.gridx = j + 2;
gbc.gridy = i + 3;
cells[i][j] = new JTextField(3);
System.out.println(i + " " + j);
matrix.add(cells[i][j], gbc);
}
}
for (int i = 0; i < row; i++)
{
gbc.gridx = 1;
gbc.gridy = i + 3;
matrix.add(new JLabel("Equation " + (i + 1) + ": "), gbc);
}
gbc2.insets = new Insets(10, 10, 10, 10);
gbc1.gridx = 1;
gbc1.gridy = 1;
gbc1.insets = new Insets(10,10,10,10);
matrixPanel.add(matrix, gbc1);
gbc1.gridy = 2;
gbc1.insets = new Insets(0, 10, 10, 10);
matrixPanel.add(compute1, gbc1);
matrixPanel.setBorder(BorderFactory.createLineBorder(Color.gray));
gbc1.gridx = 1;
gbc1.gridy = 2;
mainPanel.add(matrixPanel, gbc1);
//gbc1.gridy = 3;
gbc1.anchor = GridBagConstraints.LINE_END;
gbc1.gridx = 1; gbc1.gridy = 1;
gbc1.insets = new Insets(0, 5, 0, 0);
buttonPanel.add(reset, gbc1);
gbc1.gridx = 2; gbc1.gridy = 1;
buttonPanel.add(resetFields, gbc1);
gbc1.gridx = 1; gbc1.gridy = 3;
gbc1.insets = new Insets(0, 10, 10, 10);
mainPanel.add(buttonPanel, gbc1);
add(mainPanel);
pack();
setTitle("Experimental");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent ae)
{
Object o = ae.getSource();
JButton jb = (JButton) o;
if (jb == reset)
{
this.setVisible(false);
this.dispose();
new Experiment10();
}
else if (jb == resetFields)
{
System.out.println(row + " " + col);
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
{
System.out.println(i + " " + j);
cells[i][j].setText(""); //here
}
}
}
}
Here's the error:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException:6
at ExperimentalFrame.actionPerformed(ExperimentalFrame.java:140)
It's because, when you declare cells = new JTextField[row][col]; col is not equal to this.col (this.col = col + 1)
So when you go for for(int j = 0; j < col; j++) in actionPerformed j is out of bound for this.cells
For example, when you instantiate your class with col = 5, the cells will be created with a 5 width, however, this.col will be equal to 6, and j will go the 5 value in you for loop.
To correct you issue, do that
public ExperimentalFrame(int row, int col){
this.row = row; this.col = col;
or, if you really need col to be increased by one, which I personnaly think is odd,
public ExperimentalFrame(int row, int col){
col++;
this.row = row; this.col = col;
Ditch the class variables (row, col) and iterate based on the array size. There is no need to maintain row and column variables once the array is created.
for (int i = 0; i < cells.length; i++)
for (int j = 0; j < cells[i].length; j++) {
System.out.println(i + " " + j);
cells[i][j].setText("");
}
Works as expected.

JTable sizing issue

I am having an issue with JTables
I know my code is a little hard to follow, it's also a little jumbled around because it's coming from a fairly big program. And yes I just learned about the java naming convention in which you don't start a variable with an uppercase letter.
final JFrame Menu = new JFrame("Crime Database 2013");
Dimension screenSize0 = Menu.getToolkit().getScreenSize();
Menu.setBounds(screenSize0.width / 4, screenSize0.height / 4,
screenSize0.width / 2, screenSize0.height / 2);
Menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Menu.setVisible(true);
JPanel options = new JPanel(new GridBagLayout());
GridBagConstraints a = new GridBagConstraints();
Menu.add(options);
JButton show = new JButton("Show all records");
a.gridx = 0;
a.gridy = 1;
options.add(show, a);
final JFrame Show = new JFrame("Crime Database 2013 - Show Records");
Dimension screenSize3 = Show.getToolkit().getScreenSize();
Show.setBounds(screenSize3.width/3 - 250, screenSize3.height/7,
screenSize3.width - 150, screenSize3.height-200);
Show.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Show.setLayout(new GridBagLayout());
GridBagConstraints g = new GridBagConstraints();
final JPanel data = new JPanel(new FlowLayout());
JPanel sortselect = new JPanel(new GridBagLayout());
GridBagConstraints h = new GridBagConstraints();
g.gridx = 0;
g.gridy = 2;
Show.add(sortselect, g);
g.gridx = 0;
g.gridy = 0;
g.gridheight = 2;
g.gridwidth = 5;
Show.add(data, g);
JLabel label = new JLabel("Sort options");
JRadioButton none = new JRadioButton("No Sort",true);
JLabel frname = new JLabel("By First Name");
JRadioButton frnameup = new JRadioButton("First name - Alphabetical");
JRadioButton frnamedn = new JRadioButton("First name - Reverse-Alphabetical");
JLabel lsname = new JLabel("By Last Name");
JRadioButton lsnameup = new JRadioButton("Last name - Alphabetical");
JRadioButton lsnamedn = new JRadioButton("Last name - Reverse-Alphabetical");
JLabel byage = new JLabel("By Age");
JRadioButton ageup = new JRadioButton("Age - Increasing");
JRadioButton agedn = new JRadioButton("Age - Decreasing");
JLabel bycrime = new JLabel("By Crime");
JRadioButton crimeup = new JRadioButton("Crime - Alhabetically");
JRadioButton crimedn = new JRadioButton("Crime - Reverse-Alphabetical");
JLabel year = new JLabel("By Year of release");
JRadioButton yearup = new JRadioButton("Expected Year of Release - First");
JRadioButton yeardn = new JRadioButton("Expected Year of Release - Last");
ButtonGroup sortgroup = new ButtonGroup();
sortgroup.add(none);
sortgroup.add(frnameup);
sortgroup.add(frnamedn);
sortgroup.add(lsnameup);
sortgroup.add(lsnamedn);
sortgroup.add(ageup);
sortgroup.add(agedn);
sortgroup.add(crimeup);
sortgroup.add(crimedn);
sortgroup.add(yearup);
sortgroup.add(yeardn);
h.insets = new Insets(10,10,10,10);
h.gridx = 0;
h.gridy = 2;
sortselect.add(frname, h);
h.gridx = 0;
h.gridy = 3;
sortselect.add(frnameup, h);
h.gridx = 0;
h.gridy = 4;
sortselect.add(frnamedn, h);
h.gridx = 1;
h.gridy = 2;
sortselect.add(lsname, h);
h.gridx = 1;
h.gridy = 3;
sortselect.add(lsnameup, h);
h.gridx = 1;
h.gridy = 4;
sortselect.add(lsnamedn, h);
h.gridx = 2;
h.gridy = 2;
sortselect.add(byage, h);
h.gridx = 2;
h.gridy = 3;
sortselect.add(ageup, h);
h.gridx = 2;
h.gridy = 4;
sortselect.add(agedn, h);
h.gridx = 3;
h.gridy = 2;
sortselect.add(bycrime, h);
h.gridx = 3;
h.gridy = 3;
sortselect.add(crimeup, h);
h.gridx = 3;
h.gridy = 4;
sortselect.add(crimedn, h);
h.gridx = 4;
h.gridy = 2;
sortselect.add(year, h);
h.gridx = 4;
h.gridy = 3;
sortselect.add(yearup, h);
h.gridx = 4;
h.gridy = 4;
sortselect.add(yeardn, h);
h.gridwidth = 5;
h.gridheight = 1;
h.gridx = 0;
h.gridy =0;
sortselect.add(label, h);
h.gridx = 0;
h.gridy = 1;
sortselect.add(none, h);
show.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e1) {
Menu.setVisible(false);
int entries = 0;
BufferedReader lines = null;
try {
lines = new BufferedReader(new FileReader("L:\\workspace\\new java\\sources\\c-database.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
while (lines.readLine() != null) {
entries++;
}
} catch (IOException e2) {
e2.printStackTrace();
}
BufferedReader crimeinfo = null;
try {
crimeinfo = new BufferedReader(new FileReader("L:\\workspace\\new java\\sources\\c-database.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String namelist[] = new String[entries];
String agelist[] = new String[entries] ;
String crimelist[] = new String[entries];
String release[] = new String[entries];
for (int i = 0; i < entries; i++) {
String full = null;
try {
full = crimeinfo.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String split[] = full.split(",");
namelist[i] = split[0];
agelist[i] = split[1];
crimelist[i] = split[2];
release[i] = split[3];
}
String firstnamelist[] = new String[entries];
String lastnamelist[] = new String[entries];
for (int i = 0; i < entries; i++) {
String namesplit[] = namelist[i].split(" ");
firstnamelist[i] = namesplit[0];
lastnamelist[i] = namesplit[1];
}
final String[] headers = {"First Name",
"Last Name",
"Age",
"Crime committed",
"Expected Year of Release"
};
final String[][] crimedata = new String[entries][5];
for (int i = 0; i < entries; i++) {
crimedata[i][0] = firstnamelist[i];
crimedata[i][1] = lastnamelist[i];
crimedata[i][2] = agelist[i];
crimedata[i][3] = crimelist[i];
crimedata[i][4] = release[i];
};
for (int i = 0; i < entries; i++) {
for (int j = 0; j < 5; j++) {
System.out.println(headers[j]);
System.out.println(crimedata[i][j]);
}
}
final JTable crimetable = new JTable(crimedata, headers);
JScrollPane scrollpane = new JScrollPane(crimetable);
crimetable.setAutoCreateRowSorter(true);
data.add(scrollpane);
Show.setVisible(true);
}
}
);
I did just put this code here into eclipse and then took out all the radio buttons, and it sorta worked. Although I am not sure why
JTable can't returns proper Dimension or PreferredSize, there are three ways
table.setPreferredScrollableViewportSize(table.getPreferredSize()); but notice for small JTables with a few Rows and Columns too
to calculate desired size for (part) of Columns and (part) Rows too, then pass this Dimension in form table.setPreferredScrollableViewportSize(new Dimension(x, y));
override getPreferredSize for JScrollPane
then JFrame.pack(before JFrame.setVisible(true)) to calculate desired Size on the screen
JPanel has FlowLayout implemented in API, I'd to suggest to change to BorderLayout, then JScrollPane in CENTER area can fill whole (available) area and will be resizable with JFrame, not possible to resize JComponent (together with its container) layed by FlowLayout
have to call data.revalidate(), data.repaint() and Show.pack() as last code lines instead of (remove this code line) Show.setVisible(true);
rename Show to myFrame and show to myButton
What exactly does the setPreferredScrollableViewportSize do? Does it just force the table to always be that size? What is the whole pack thing?
The getPreferredScrollableViewportSize() method is defined in the Scrollable interface, discussed in Implementing a Scrolling-Savvy Client. Rather than setting the preferred size, you can override getPreferredScrollableViewportSize() to change the default. Making the height a multiple of getRowHeight() is illustrated here. More on preferred size may be found here. Conveniently, the pack() method "Causes this Window to be sized to fit the preferred size and layouts of its subcomponents."

JTable splitting cells. How to

I'm new to Swing and I want to create a table having this form:
So How to split a cell like the table shows?
Have you any useful links or tutorials or an idea?
This looks like a bowling score card to me. Based on that assumption, the number of columns is fixed, and the number of entries tends to be 6 or less. Since you likely won't need scrolling, I would recommend a fixed grid of components instead of a JTable.
This could easily be acheived using GridBagLayout. For the name, I'd use a JTextArea. For the 2 scoring cells for each frame, I'd use JTextFields. For the bottom 2-column-span component that holds the frame's score I'd probably use a JLabel.
Put all of this on a JPanel, and recreate the panel for each bowler.
EDIT:
Here's a quick mock-up just to show the concept. Not necessarily visually pretty, but I'll leave that as an exercise for the reader:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BowlingScoreCard implements Runnable
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new BowlingScoreCard());
}
public void run()
{
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(createScorecard(4), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
private JPanel createScorecard(int numPlayers)
{
JPanel p = new JPanel(new GridBagLayout());
p.add(new JLabel("Player"), gbc(0, 0, 1, 1));
for (int x = 1; x <= 10; x++)
{
p.add(new JLabel(Integer.toString(x)), gbc(x, 0, 1, 1));
}
for (int y = 1; y <= numPlayers; y++)
{
JTextArea textArea = new JTextArea(2, 10);
p.add(textArea, gbc(0, y, 1, 1));
for (int i = 1; i <= 9; i++)
{
p.add(createFrame(2), gbc(i, y, 1, 1));
}
p.add(createFrame(3), gbc(10, y, 1, 1));
}
return p;
}
private JPanel createFrame(int entries)
{
JLabel label = new JLabel(" ");
label.setBackground(Color.GRAY);
JPanel p = new JPanel(new GridBagLayout());
p.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));
for (int i = 0; i < entries; i++)
{
p.add(new JTextField(3), gbc(i, 0, 1, 1));
}
p.add(label, gbc(0, 1, 2, 1));
return p;
}
private GridBagConstraints gbc(int x, int y, int colspan, int rowspan)
{
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = colspan;
gbc.gridheight = rowspan;
gbc.weightx = 0;
gbc.weighty = 0;
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.NONE;
return gbc;
}
}

Gap between JPanels in GridLayout

The code below produces nine individual JPanels in which are 9 buttons. The nine JPanels are arranged onto a base JPanel using GridLayout. This base JPanel is then placed onto the ContentPane using Border Layout. I'm using borders for the JButtons and each individual JPanel to clearly define their separation. The JButtons inside each JPanel look fine but there is a gap between the JPanels which is causing the appearance of a double line which is bugging the hell out of me. I've tried adding each individual JPanel onto the ContentPane directly but this does nothing. Totally stumped and wondering if anyone has any suggestions?
P.S. I know the mass of duplicate code needs re-factoring in a bad way and it will, this is just for mock-up purposes.
Thanks,
import java.awt.*;
import javax.swing.*;
import javax.swing.UIManager.*;
public class View1 extends JFrame
{
private JPanel basePanel;
private JPanel childPanel1;
private JPanel childPanel2;
private JPanel childPanel3;
private JPanel childPanel4;
private JPanel childPanel5;
private JPanel childPanel6;
private JPanel childPanel7;
private JPanel childPanel8;
private JPanel childPanel9;
private int row = 3;
private int column = 3;
private JButton[][] squares1;
private JButton[][] squares2;
private JButton[][] squares3;
private JButton[][] squares4;
private JButton[][] squares5;
private JButton[][] squares6;
private JButton[][] squares7;
private JButton[][] squares8;
private JButton[][] squares9;
private Font numberFont;
public View1()
{
setSize(400,400);
setTitle("2013");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
basePanel = new JPanel();
basePanel.setLayout(new GridLayout(row, column, 0, 0));
numberFont = new Font("sansserif", Font.BOLD, 32);
childPanel1Setup();
childPanel2Setup();
childPanel3Setup();
childPanel4Setup();
childPanel5Setup();
childPanel6Setup();
childPanel7Setup();
childPanel8Setup();
childPanel9Setup();
basePanel.add(childPanel1);
basePanel.add(childPanel2);
basePanel.add(childPanel3);
basePanel.add(childPanel4);
basePanel.add(childPanel5);
basePanel.add(childPanel6);
basePanel.add(childPanel7);
basePanel.add(childPanel8);
basePanel.add(childPanel9);
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
cp.add(basePanel, BorderLayout.CENTER);
}
public void childPanel1Setup()
{
childPanel1 = new JPanel();
childPanel1.setLayout(new GridLayout(row, column, 0, 0));
childPanel1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares1 = new JButton[row][column];
for(int rows = 0; rows < this.row; rows++)
{
for(int cols = 0; cols < this.column; cols++)
{
squares1[rows][cols] = new JButton();
squares1[rows][cols].setSize(32, 32);
squares1[rows][cols].setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares1[rows][cols].setBackground(Color.WHITE);
childPanel1.add(squares1[rows][cols]);
}
}
}
public void childPanel2Setup()
{
childPanel2 = new JPanel();
childPanel2.setLayout(new GridLayout(row, column, 0, 0));
childPanel2.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares2 = new JButton[row][column];
for(int rows = 0; rows < this.row; rows++)
{
for(int cols = 0; cols < this.column; cols++)
{
squares2[rows][cols] = new JButton();
squares2[rows][cols].setSize(32, 32);
squares2[rows][cols].setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares2[rows][cols].setBackground(Color.WHITE);
childPanel2.add(squares2[rows][cols]);
}
}
}
public void childPanel3Setup()
{
childPanel3 = new JPanel();
childPanel3.setLayout(new GridLayout(row, column, 0, 0));
childPanel3.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares3 = new JButton[row][column];
for(int rows = 0; rows < this.row; rows++)
{
for(int cols = 0; cols < this.column; cols++)
{
squares3[rows][cols] = new JButton();
squares3[rows][cols].setSize(32, 32);
squares3[rows][cols].setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares3[rows][cols].setBackground(Color.WHITE);
childPanel3.add(squares3[rows][cols]);
}
}
}
public void childPanel4Setup()
{
childPanel4 = new JPanel();
childPanel4.setLayout(new GridLayout(row, column, 0, 0));
childPanel4.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares4 = new JButton[row][column];
for(int rows = 0; rows < this.row; rows++)
{
for(int cols = 0; cols < this.column; cols++)
{
squares4[rows][cols] = new JButton();
squares4[rows][cols].setSize(32, 32);
squares4[rows][cols].setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares4[rows][cols].setBackground(Color.WHITE);
childPanel4.add(squares4[rows][cols]);
}
}
}
public void childPanel5Setup()
{
childPanel5 = new JPanel();
childPanel5.setLayout(new GridLayout(row, column, 0, 0));
childPanel5.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares5 = new JButton[row][column];
for(int rows = 0; rows < this.row; rows++)
{
for(int cols = 0; cols < this.column; cols++)
{
squares5[rows][cols] = new JButton();
squares5[rows][cols].setSize(32, 32);
squares5[rows][cols].setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares5[rows][cols].setBackground(Color.WHITE);
childPanel5.add(squares5[rows][cols]);
}
}
}
public void childPanel6Setup()
{
childPanel6 = new JPanel();
childPanel6.setLayout(new GridLayout(row, column, 0, 0));
childPanel6.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares6 = new JButton[row][column];
for(int rows = 0; rows < this.row; rows++)
{
for(int cols = 0; cols < this.column; cols++)
{
squares6[rows][cols] = new JButton();
squares6[rows][cols].setSize(32, 32);
squares6[rows][cols].setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares6[rows][cols].setBackground(Color.WHITE);
childPanel6.add(squares6[rows][cols]);
}
}
}
public void childPanel7Setup()
{
childPanel7 = new JPanel();
childPanel7.setLayout(new GridLayout(row, column, 0, 0));
childPanel7.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares7 = new JButton[row][column];
for(int rows = 0; rows < this.row; rows++)
{
for(int cols = 0; cols < this.column; cols++)
{
squares7[rows][cols] = new JButton();
squares7[rows][cols].setSize(32, 32);
squares7[rows][cols].setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares7[rows][cols].setBackground(Color.WHITE);
childPanel7.add(squares7[rows][cols]);
}
}
}
public void childPanel8Setup()
{
childPanel8 = new JPanel();
childPanel8.setLayout(new GridLayout(row, column, 0, 0));
childPanel8.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares8 = new JButton[row][column];
for(int rows = 0; rows < this.row; rows++)
{
for(int cols = 0; cols < this.column; cols++)
{
squares8[rows][cols] = new JButton();
squares8[rows][cols].setSize(32, 32);
squares8[rows][cols].setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares8[rows][cols].setBackground(Color.WHITE);
childPanel8.add(squares8[rows][cols]);
}
}
}
public void childPanel9Setup()
{
childPanel9 = new JPanel();
childPanel9.setLayout(new GridLayout(row, column, 0, 0));
childPanel9.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares9 = new JButton[row][column];
for(int rows = 0; rows < this.row; rows++)
{
for(int cols = 0; cols < this.column; cols++)
{
squares9[rows][cols] = new JButton();
squares9[rows][cols].setSize(32, 32);
squares9[rows][cols].setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares9[rows][cols].setBackground(Color.WHITE);
childPanel9.add(squares9[rows][cols]);
}
}
}
}
I believe it's because the Layout Manager for JPanels is FlowLayout which includes a margin. When you create the panels, set their layout to GridLayout which will give you 0 margin.
Also have you done setVgap(0); and setHgap(0); for the GridLayout?
GridLayout makes all component to be of the same size. If it needs to layout matrix of 3x3 components inside JPanel that it 100x100 pixels, each component will be 33x33 pixels and there will be on extra pixel at the right and at the bottom because 100 is not factor of 3. If JPanel is 101x101 pixels, there will be extra pixels at all four edges.
Consider using GridBagLayout or Box or some other layout that is smarter than GridLayout.

Categories