Adding a JPanel Array to a Container - java

Look at the Last line of code, that Is where I specifically would like to add my JPanel array to a container. Thanks alot Guys or Gals!
Code:
private JFrame b = new JFrame("Lotus");
private JLabel currentP = new JLabel();
private int currentS;
private Container pieces = new Container();
private JButton exitt = new JButton("EXIT");
private ImageIcon B1=new ImageIcon("C:\\Users\\Brusty\\Downloads\\p1.jpg");
private ImageIcon B2=new ImageIcon("C:\\Users\\Brusty\\Downloads\\p2.jpg");
LinkedList<Stack<Integer>> spotList = new LinkedList<Stack<Integer>>();
//Creation of Gamepiece labels
public void Labels(){
JLabel[] labelsP1 = new JLabel[10];
JLabel[] labelsP2 = new JLabel[10];
for(int i = 0 ; i < labelsP1.length ; i++){
labelsP1[i] = new JLabel(B1);
for(int j = 0 ; j < labelsP2.length ; j++){
labelsP2[j] = new JLabel(B2);
}
Container c = b.getContentPane();
c.setLayout(new GridLayout(13,3));
c.add(pieces);
pieces.add(labelsP1);

Not sure I really see your problem. You just need to loop through the labelsP1 array and add the labels...
for (JLabel label : labelsP1) {
pieces.add(label);
}

Related

Simple Java GUI Interface - Centering

So I was coding a Punnett square applet to automize a few simple biology calculations and output a simple Punnett square visual. For those of you who don't know, a Punnett square is just a device used in Biology to find ratios of a certain genotype in all the possible children. It's relatively simple;and example would be parents Aa and aa would create offspring of Aa, Aa, aa, and aa ( just crossed them). I have implemented this for single and double genes (Aa+Aa; AaBb+AaBb), with single genes being in a 2x2 table and double being in a 4x4 table.
The issue I am having is with my display- What I want is for each item in the 4x4 table to be centered ( they are currently all located to the left of each cell). Additionally, I wanted to find a way to put the parent's genes on the side of the table (so to the left and to the top to indicate each parent).
I am somewhat a novice at GUI, and was struggling to find any help online in regards to this kind of situation, so was wondering whether you could help.
Here is the code for the GUI class:
//Imports
public class GeneticsGUI
{
public static void main(String[] args)
{
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.setSize(600, 600);
JTextField parent1 = new JTextField();
JTextField parent2 = new JTextField();
JPanel top = new JPanel(new GridLayout(3,2));
top.add(new JLabel("Parent 1:"));
top.add(parent1);
top.add(new JLabel("Parent 2:"));
top.add(parent2);
JButton submit = new JButton("Calculate");
submit.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==submit)
{
String p1 = parent1.getText();
String p2 = parent2.getText();
if(p1!=null&&p2!=null&&p1.length()==2&&p2.length()==2)
{
JPanel c2 = new JPanel();
JFrame window = new JFrame("Genetics");
window.add(c2);
window.setContentPane(c2);
window.setSize(600, 400);
window.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
window.setVisible(true);
String[][] mono = Genetics.monohybridPunett(p1, p2);
for(int row = 0; row<2 ; row++)
{
for(int col = 0; col<2; col++)
{
mono[row][col] = " "+ mono[row][col];
}
}
JTable table = new JTable(mono.length,mono.length);
table.setShowGrid(true);
for(int i = 0; i<mono.length; i++)
for(int j = 0; j<mono.length; j++)
table.setValueAt(mono[i][j], i, j);
DefaultTableCellRenderer t = new DefaultTableCellRenderer();
t.setHorizontalTextPosition(DefaultTableCellRenderer.CENTER);
t.setVerticalTextPosition(DefaultTableCellRenderer.CENTER);
table.setSize(300, 300);
table.isCellEditable(0,0);
table.setRowHeight(100);
c2.add(table,BorderLayout.EAST);;
c2.revalidate();
}
else if(p1!=null&&p2!=null&&p1.length()==4&&p2.length()==4)
{
JPanel c2 = new JPanel();
JFrame window = new JFrame("Genetics");
window.add(c2);
window.setContentPane(c2);
window.setSize(600, 500);
window.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
window.setVisible(true);
String[][] di = Genetics.dihybridPunett(p1, p2);
JTable table = new JTable(di.length,di.length);
table.setShowGrid(true);
DefaultTableModel model = new DefaultTableModel(di,new Object[]{"AaBb","AaBb","",""});
table.isCellEditable(0, 0);
table.setModel(model);
table.setRowHeight(100);
table.getColumnModel().getColumn(0).setPreferredWidth(100);
table.getColumnModel().getColumn(1).setPreferredWidth(100);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
c2.add(table,BorderLayout.CENTER);
c2.revalidate();
}
}
}
});
top.add(submit);
content.add(top, BorderLayout.NORTH);
JFrame window = new JFrame("Genetics");
window.add(content);
window.setContentPane(content);
window.setSize(600,150);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
}

Generate JFrames in a loop, naming issue

Beginner Java programmer here. I'm trying to create a card game to learn more about Java. I have an array of names I pulled out a database. For each String in the array I want to create a JPanel and inside JLabels where I will set the name, power, health, etc.
The problem is when I create these in a loop they all have the same name and overwrite each other. Since I read Java doesn't have dynamic Variable names, how do I solve this?
public void loadDatabaseCardElements(ArrayList cards) {
ArrayList<String> buildCards = cards;
int i;
for(i = 0; i != buildCards.size();) {
String var = buildCards.get(0);
//create the Panel etc
JPanel mainHolder = new JPanel();
mainHolder.setLayout(new BoxLayout(mainHolder, BoxLayout.PAGE_AXIS));
JLabel name = new JLabel("Name: " + var);
JLabel powerLabel = new JLabel("Power: ");
JLabel healthLabel = new JLabel("Health: ");
JLabel armorLabel = new JLabel("Armor: ");
JLabel type1Label = new JLabel("Type1");
JLabel type2Label = new JLabel("Type2: ");
JLabel ability1Label = new JLabel("Ability1: ");
JLabel ability2Label = new JLabel("Ability2: ");
JLabel ability3Label = new JLabel("Ability3: ");
JButton card1 = new JButton("Add to deck");
mainHolder.add(name);
mainHolder.add(powerLabel);
mainHolder.add(healthLabel);
mainHolder.add(armorLabel);
mainHolder.add(type1Label);
mainHolder.add(type2Label);
mainHolder.add(ability1Label);
mainHolder.add(ability2Label);
mainHolder.add(ability3Label);
mainHolder.add(card1);
mainHolder.setBorder(BorderFactory.createLineBorder(Color.black));
mainHolder.setPreferredSize( new Dimension( 130, 200 ) );
frame1.add(mainHolder, BorderLayout.WEST);
SwingUtilities.updateComponentTreeUI(frame1);
card1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
preDeck.add(var); //add to another array when clicked
}
});
if (buildCards.size() != 0) {
buildCards.remove(0);
} else {
}
}
}
The reason for overwriting all the panels with same name is due to this part of your code:
int i;
for(i = 0; i != buildCards.size();) {
String var = buildCards.get(0);
You are assigning the first element of your list to each JLabel. This could help you achieve what you need:
for(int i = 0; i < buildCards.size(); i++){
String var = buildCards.get(i);
// Followed by your code
}
set a growable layout for a standard jpanel in the frame and then add a new jpanel to the standard jpanel every time. this should solve the naming problem. if u need access to each panel, you can store them in an array

How to add my Arraylist of Tile objects to a JPanel?

I am having some trouble figuring out how to do this. I have created a tile class to associate with my tile objects, but I'm unsure of how to add my ArrayList of tile objects to my JPanel.
Here is what I have so far:
public class First implements Runnable{
public void run() {
// TODO Auto-generated method stub
JFrame fr = new JFrame("Frame");
fr.setVisible(true);
fr.setSize(300,700);
JPanel p = new JPanel(new GridLayout(0,1));
p.setVisible(true);
fr.add(p);
JLabel blue = new JLabel("a");
//blue.setOpaque(true);
//blue.setBackground( Color.BLUE );
p.add(blue);
JLabel red = new JLabel("b");
//red.setOpaque(true);
//red.setBackground( Color.RED);
p.add(red);
JLabel green = new JLabel("c");
//green.setOpaque(true);
//green.setBackground( Color.GREEN);
p.add(green);
JLabel orange = new JLabel("d");
orange.setOpaque(true);
orange.setBackground( Color.ORANGE);
p.add(orange);
char a = 0;
char b = 0;
char c = 0;
char d = 0;
Tile ta = new Tile(a);
Tile tb = new Tile(b);
Tile tc = new Tile(c);
Tile td = new Tile(d);
//p.(ta);
ArrayList<Tile>tile = new ArrayList<Tile>();
tile.add(ta);
tile.add(tb);
tile.add(tc);
tile.add(td);
for(Tile s: tile){
System.out.println("Printed:"+s);
}
}
}
I'm not clear if this is what you are asking. But if you want to display the contents of an ArrayList on a JPanel, you can just iterate through it.
for (Tile t:tile) p.add(t);
This assumes that Tile is an extension of Component.

Use array elements from another method

I have a questions about using array
I have a method that creates JButton for a JPanel. I used JButton[] to store 7 buttons in it.
The problem is those buttons must be setEnable(false) initially. they are only enabled when openButton is clicked.
I would like to create another method that just take all elements from JButton[] and set them Enable. How can I do that?
private JButton filterButtons() {
//set layout for buttons
setLayout(new BorderLayout());
//Array to store description of buttons
final String[] filterNames = {myEdgeDetect.getDescription(),
myEdgeHighlight.getDescription(),
myFlipHorizontal.getDescription(),
myFlipVeritcal.getDescription(),
myGrayscale.getDescription(),
mySharpen.getDescription(),
mySoften.getDescription()};
final JButton[] filterButtons = new JButton[filterNames.length];
//This panel store buttons on north
final JPanel buttonPanel = new JPanel();
//Start to print buttons
for (int i = 0; i < filterNames.length; i++) {
filterButtons[i] = new JButton(filterNames[i]);
filterButtons[i].setEnabled(false);
filterButtons[i].addActionListener(null);
filterButtons[i].setActionCommand(" " + i);
buttonPanel.add(filterButtons[i]);
}
If, rather than defining filterNames and filterButtons inside the method you made them fields of the class, then it would be easy to write a second method that iterates through the filterButtons and enables them.
Class Whatever {
String[] filterNames;
JButton[] filterButtons;
private JButton filterButtons() {
//set layout for buttons
setLayout(new BorderLayout());
//Array to store description of buttons
filterNames = {myEdgeDetect.getDescription(),
myEdgeHighlight.getDescription(),
myFlipHorizontal.getDescription(),
myFlipVeritcal.getDescription(),
myGrayscale.getDescription(),
mySharpen.getDescription(),
mySoften.getDescription()};
filterButtons = new JButton[filterNames.length];
//This panel store buttons on north
final JPanel buttonPanel = new JPanel();
//Start to print buttons
for (int i = 0; i < filterNames.length; i++) {
filterButtons[i] = new JButton(filterNames[i]);
filterButtons[i].setEnabled(false);
filterButtons[i].addActionListener(null);
filterButtons[i].setActionCommand(" " + i);
buttonPanel.add(filterButtons[i]);
}
}
void enableButtons() {
for (int i = 0; i < filterButtons.length; i++) {
filterButtons[i].setEnabled(true);
}
}
}

add array to JTextField

I am trying to add the contents of two arrays to two TextFields. When you run the program the problem is the current TextFields that I try to display (lines 70 - 83) when the window is redrawn, they only show the last item in their array. Is there any way to add all the items in a stacked list (one ontop of another.)
This is my first class ClassNameSorting
Code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class ClassNameSorting extends JFrame {
JTextField studentNameInputFirst, studentNameInputLast, studentNamesEneteredLast, studentNamesEnteredFirst;
JButton nextName, sort, backToStart;
JLabel firstName, lastName, classList;
String disp = "";
ArrayList<String> studentNameFirst = new ArrayList<String>();
ArrayList<String> studentNameLast = new ArrayList<String>();
ArrayList<String> sortedStudentNameFirst = new ArrayList<String>();
ArrayList<String> savedUnsortedStudentNameLast = new ArrayList<String>();
Container container = getContentPane();
public ClassNameSorting() {
container.setLayout(new FlowLayout());
studentNameInputFirst = new JTextField(15);
studentNameInputLast = new JTextField(15);
nextName = new JButton("Save");
sort = new JButton("Sort");
firstName = new JLabel("First Name: ");
lastName = new JLabel("Last Name: ");
nextName.setPreferredSize(new Dimension(110, 20));
sort.setPreferredSize(new Dimension(110, 20));
container.add(firstName);
container.add(studentNameInputFirst);
container.add(lastName);
container.add(studentNameInputLast);
container.add(nextName);
container.add(sort);
nextName.addActionListener(new nextNameListener());
sort.addActionListener(new sortListener());
setSize(262, 120);
setVisible(true);
}
private class nextNameListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
studentNameFirst.add(studentNameInputFirst.getText());
studentNameLast.add(studentNameInputLast.getText());
studentNameInputLast.setText(null);
studentNameInputFirst.setText(null);
}
}
private class sortListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
savedUnsortedStudentNameLast = new ArrayList<String>(studentNameLast);
Collections.sort(studentNameLast);
int totalSizeOfArray = studentNameLast.size();
for(int i = 0; i < totalSizeOfArray; i++){
boolean containsYorN = false;
String tempElementForContains = studentNameLast.get(i);
String tempElementFromStudentNameLast = savedUnsortedStudentNameLast.get(i);
containsYorN = savedUnsortedStudentNameLast.contains(tempElementForContains);
if(containsYorN == true){
int tempIndexPos = savedUnsortedStudentNameLast.indexOf(tempElementForContains);
String tempIndexElement = studentNameFirst.get(tempIndexPos);
sortedStudentNameFirst.add(i, tempIndexElement);
}
}
studentNamesEneteredLast = new JTextField();
studentNamesEnteredFirst = new JTextField();
for(int i = 0; i < totalSizeOfArray; i++){
studentNamesEneteredLast.setText(studentNameLast.get(i));
}
for(int i = 0; i < totalSizeOfArray; i++){
studentNamesEnteredFirst.setText(sortedStudentNameFirst.get(i));
}
studentNamesEneteredLast.setEditable(false);
studentNamesEnteredFirst.setEditable(false);
container.add(studentNamesEneteredLast);
container.add(studentNamesEnteredFirst);
setSize(262, 500);
revalidate();
}
}
}
My second class is: (DrawMainWindow)
import javax.swing.JFrame;
public class DrawMainWindow {
public static void main(String[] args) {
ClassNameSorting drawGui = new ClassNameSorting();
drawGui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawGui.setLocationRelativeTo(null);
}
}
The first array is studentNameLast. I am trying to add that to studentNamesEnteredLast text field. The second is sortedStudentNameFirst being added to studentNamesEnteredFirst.
Thanks for the help!
for(int i = 0; i < totalSizeOfArray; i++){
studentNamesEneteredLast.setText(studentNameLast.get(i));
}
The text in the JTextField will only reflect the last item of the List. If you wish to append the entire list, create a String from the List and set the text of the JTextField with that String (you might wish to have them separated by some character - below uses a comma)
StringBuilder sb = new StringBuilder();
for(int i = 0; i < totalSizeOfArray; i++){
sb.append(studentNameLast.get(i)).append(",");//comma delim
}
studentNamesEneteredLast.setText(sb.toString());
Not entirely sure what you are after, but a JList or JTable might be more appropriate to display List information
Was able to switch to a GridLayout and then added each last name and then first name together.
Code:
container.setLayout(new GridLayout(totalSizeOfArray+3,2));
for(int i = 0; i < totalSizeOfArray; i++){
studentNamesEnteredLast = new JTextField();
studentNamesEnteredFirst = new JTextField();
studentNamesEnteredFirst.setEditable(false);
studentNamesEnteredLast.setEditable(false);
studentNamesEnteredLast.setText(studentNameLast.get(i));
studentNamesEnteredFirst.setText(sortedStudentNameFirst.get(i));
container.add(studentNamesEnteredLast);
container.add(studentNamesEnteredFirst);
}
Example:

Categories