JLabel.setText("__") will not print multiple times while in for loop - java

I have placed my JLabel.setText("__") inside a for loop so it can print the length of a word replacing each letter with a 'space' . It is for a hangman game to display the length of the word using blank spaces. However it is only printing once. Any tips on why? Also, if you have any tips on better organizing my code that would be appreciated. Thanks in advance.
/*PACKAGE DECLARATION*/
package Game;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/************************
* GAME MECHANICS CLASS *
* **********************/
public class GameStructure {
/* INSTANCE DECLARATIONS */
private String []wordList = {"computer","java","activity","alaska","appearance","article",
"automobile","basket","birthday","canada","central","character","chicken","chosen",
"cutting","daily","darkness","diagram","disappear","driving","effort","establish","exact",
"establishment","fifteen","football","foreign","frequently","frighten","function","gradually",
"hurried","identity","importance","impossible","invented","italian","journey","lincoln",
"london","massage","minerals","outer","paint","particles","personal","physical","progress",
"quarter","recognise","replace","rhythm","situation","slightly","steady","stepped",
"strike","successful","sudden","terrible","traffic","unusual","volume","yesterday"};
private int []length = new int [64];
private JTextField tf;//text field instance variable (used)
private JLabel jl2;//label instance variable (used)
private JLabel jl3;//label instance (working on)
private String letter;
/*****************
* LENGTH METHOD *
* ***************/
public void length(){
jl3 = new JLabel();
int j = 0;
for(j = 0; j<64; j++) {
length[j] = wordList[j].length();//gets length of words in wordList
}//end for
int l = 0;
for(int m = 0; m<length[l]; m++) {//supposed to print length of word with '__' as each letter
jl3.setText("__ ");//instead only printing once
l++;
}//end for
}//end length method
/*****************
* WINDOW METHOD *
* ***************/
public void window() {
LoadImageApp i = new LoadImageApp();//calling image class
JFrame gameFrame = new JFrame();//declaration
JPanel jp = new JPanel();
JPanel jp2 = new JPanel();//jpanel for blanks
JLabel jl = new JLabel("Enter a Letter:");//prompt with label
tf = new JTextField(1);//length of text field by character
jl2 = new JLabel("Letters Used: ");
jp2.add(jl3);
jp.add(jl);//add label to panel
jp.add(tf);//add text field to panel
jp.add(jl2);//add letters used
gameFrame.add(i); //adds background image to window
i.add(jp); // adds panel containing label to background image panel
i.add(jp2);
gameFrame.setTitle("Hangman");//title of frame window
gameFrame.setSize(850, 600);//sets size of frame
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit when 'x' button pressed
gameFrame.setIconImage(new ImageIcon("Hangman-Game-grey.png").getImage());//set the frame icon to an image loaded from a file
gameFrame.setLocationRelativeTo(null);//window centered
gameFrame.setResizable(false);//user can not resize window
gameFrame.setVisible(true);//display frame
}//end window method
/*********************
* USER INPUT METHOD *
* *******************/
public void userInput() {
tf.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {//when enter key pressed
JTextField tf = (JTextField)e.getSource();
letter = tf.getText();
jl2.setText(jl2.getText() + letter + " ");//sets jlabel text to users entered letter
}//end actionPerformed method
});
}//end userInput method
}//end GameMechanics class

"However it is only printing once. Any tips on why?"
setText will only set the text once. So all you're doing in the loop is setting the text over and over. Here is a suggestion. Concatenate the Strings in the loop, then set the text. Like this:
String line = "";
for(int m = 0; m<length[l]; m++) {
line += "__ ";
l++;
}
jl3.setText(line);
" Also, if you have any tips on better organizing my code that would be appreciated. "
Try Code Review for this.

Related

Looping letter input

I'm making a hangman game for school and I've run into a problem that I simply can't solve, maybe I'm overthinking, maybe I'm not. Anyways, I need to let the user input a letter, and if that letter is in the word used for the game (pikachu. I know, stupid choice but it's pretty basic and easy so I used that) then the letter is revealed, the problem is that after inputting a letter, the user can't guess any more letters. I need a way to loop through the letter input and revealing so that I can actually play the game.
I'm sorry if the solution is so simple but I just can't figure out what needs to change in my code in order to fix my problem because I'm very new to java.
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.*;
import java.awt.event.KeyListener;
import javax.swing.*;
public class PanDisp extends JPanel {
JLabel lblOutput;
JLabel lblGuess;
JButton btnUpdateLabel;
Image imgPkmn;
FraImg fraImg;
String sSecret;
public PanDisp() {//Constructor
KeyInput keyInput = new KeyInput();
KeyInput.LabelChangeListener labelChange = keyInput.new LabelChangeListener();
sSecret = "*******";
lblGuess = new JLabel("Type will go here");
lblOutput = new JLabel(sSecret);
btnUpdateLabel = new JButton("Enter");
add(lblOutput);
add(btnUpdateLabel);
addKeyListener(new KeyInput());
setFocusable(true);
btnUpdateLabel.addActionListener(labelChange);
fraImg = new FraImg(imgPkmn);
}
public void GameOver() {
}
class KeyInput implements KeyListener {
String sInput;
String sWord = "pikachu";
String sSecret = "*******";
char chInput;
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
chInput = (char) e.getKeyChar();
sInput = String.valueOf(chInput);
lblOutput.setText(sInput);
}
#Override
public void keyReleased(KeyEvent e) {
}
class LabelChangeListener implements ActionListener {
char cWord;
int nCorrect, nIncorrect, nNum;
public void actionPerformed(ActionEvent event) {
if (sWord.contains(sInput)) {
for (int i = 0; i < sWord.length(); i++) {
sSecret.replace(sSecret.charAt(i), sWord.charAt(i));
}
nCorrect += 1;
}
else {
nIncorrect += 1;
if (nIncorrect == 7) {
GameOver();
}
}
}
}
}
}
Your problem is that your mindset is off and has to be changed. Don't think "loop", and in fact get "loop" out of the equation. You're programming in an event-driven programming environment, and the loop you're thinking of belongs in the linear console programming environment. Instead think "state of object" and "behavioral changes to state changes", and you'll move much further in this quest. So change the state of your class -- number of guesses, number of correct guesses, and then change the response to the user's input based on this state
For instance, if you wanted to create a console program that allowed a user to enter 5 Strings, and then displayed those Strings back to the user, it would be pretty straight forward, in that you'd create your String array, and then use a for loop to prompt the user 5 times to enter text, grabbing each entered String within the loop. Here "loops" like the one you're requesting work.
Linear Console Program
import java.util.Scanner;
public class Enter5Numbers1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter 5 sentences:");
String[] sentences = new String[5];
for (int i = 0; i < sentences.length; i++) {
System.out.printf("Enter sentence #%d: ", (i + 1));
sentences[i] = scanner.nextLine();
}
System.out.println("You entered the following sentences:");
for (String sentence : sentences) {
System.out.println(sentence);
}
scanner.close();
}
}
If on the other hand you wanted to create a GUI that did something similar, that prompted the user for 5 Strings and accepted those Strings into an array, you couldn't use the same type of for loop. Instead you would need to give your class an int String counter, perhaps called enteredSentenceCount, and in a JButton's ActionListener (or Action -- which is something very similar), you would accept an entered String (perhaps typed into a JTextField called entryField), only if the enteredSentenceCount is less than 5, less than the maximum number of Strings allowed. You would of course increment the enteredSentenceCount variable each time a String is entered. And this combination of increase a counter variable and checking its value will need to substutite for the concept of a "loop". So here the "state" of the class is held in the enteredSentenceCount, and the behavioral change we want is to alter what the button's Action does depending on the enteredSentenceCount's value -- if less than 5, accept a String, and if it is equal to or greater than 5, display the entered Strings.
Event Driven GUI Program
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Enter5Numbers2 extends JPanel {
private static final int MAX_SENTENCE_COUNT = 5; // number of Strings to enter
private static final String PROMPT_TEMPLATE = "Please enter sentence number %d:";
private String[] sentences = new String[MAX_SENTENCE_COUNT]; // array to hold entered Strings
private int enteredSentenceCount = 0; // count of number of Strings entered
private JTextField entryField = new JTextField(20); // field to accept text input frm user.
// JLabel to display prompts to user:
private JLabel promptLabel = new JLabel(String.format(PROMPT_TEMPLATE, (enteredSentenceCount + 1)));
public Enter5Numbers2() {
// create GUI
// First create Action / ActionListener for button
EntryAction entryAction = new EntryAction("Enter");
JButton entryButton = new JButton(entryAction); // pass it into the button
entryField.setAction(entryAction); // but give it also to JTextField so that the enter key will trigger it
// JPanel to accept user data entry
JPanel entryPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
entryPanel.add(entryField);
entryPanel.add(entryButton);
// allow main JPanel to display prompt
setBorder(BorderFactory.createTitledBorder("Please Enter 5 Sentences"));
setLayout(new GridLayout(2, 1));
add(promptLabel);
add(entryPanel);
}
// Action class, similar to an ActionListener
private class EntryAction extends AbstractAction {
public EntryAction(String name) {
super(name);
putValue(MNEMONIC_KEY, (int) name.charAt(0));
}
#Override
public void actionPerformed(ActionEvent e) {
// check that we haven't entered more than the max number of sentences
if (enteredSentenceCount < MAX_SENTENCE_COUNT) {
// if OK, get the entered text
String sentence = entryField.getText();
// put it in our array
sentences[enteredSentenceCount] = sentence;
entryField.setText(""); // clear the text field
entryField.requestFocusInWindow(); // set the cursor back into the textfield
enteredSentenceCount++; // increment our entered sentence count variable
promptLabel.setText(String.format(PROMPT_TEMPLATE, (enteredSentenceCount + 1))); // change prompt
}
// if the number of sentences added equals the number we want, display it
if (enteredSentenceCount == MAX_SENTENCE_COUNT) {
JTextArea textArea = new JTextArea(6, 30);
for (String sentence : sentences) {
textArea.append(sentence + "\n");
}
JScrollPane scrollPane = new JScrollPane(textArea);
JOptionPane.showMessageDialog(Enter5Numbers2.this, scrollPane, "Five Sentences Entered",
JOptionPane.PLAIN_MESSAGE);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Enter 5 Numbers");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(new Enter5Numbers2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}

Program freezing(not responding) after button click no a Java app

Ok so I'm building to show students how a loop goes through an array, I have added 2 images to help explain and the code, the first is the result I get after I click go then it freezes . The Second image is what I'd like it to do after you put in the values of 1 in start, 15 in stop, 3 in step and click the Go Button. And then to be cleared on the click of Clear button. I think they probably related. Can anyone see the problem? Thanks in advanced!
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import javax.swing.JOptionPane;
public class Checkerboard extends Frame implements ActionListener
{
int[] blocksTextField = new int[15];
Panel blocksPanel = new Panel();
TextArea blocksDisplay[] = new TextArea[16];
TextField start = new TextField (3);
TextField stop = new TextField (3);
TextField step = new TextField (3);
//Colors
Color Red = new Color(255, 90, 90);
Color Green = new Color(140, 215, 40);
Color white = new Color(255,255,255);
//textField ints
int inputStart;
int inputStop;
int inputStep;
//Lables
Label custStartLabel = new Label ("Start : ");
Label custStopLabel = new Label ("Stop : ");
Label custStepLabel = new Label ("Step : ");
//Buttons
Button goButton = new Button("Go");
Button clearButton = new Button("Clear");
//panel for input textFields and lables
Panel textInputPanel = new Panel();
//Panel for buttons
Panel buttonPanel = new Panel();
public Checkerboard()
{//constructor method
//set the 3 input textFields to 0
inputStart = 0;
inputStop = 0;
inputStep = 0;
//set Layouts for frame and three panels
this.setLayout(new BorderLayout());
//grid layout (row,col,horgap,vertgap)
blocksPanel.setLayout(new GridLayout(4,4,10,10));
textInputPanel.setLayout(new GridLayout(2,3,20,10));
buttonPanel.setLayout(new FlowLayout());
//setEditable()
//setText()
//add components to blocks panel
for (int i = 0; i<16; i++)
{
blocksDisplay[i] = new TextArea(null,3,5,3);
if(i<6)
blocksDisplay[i].setText(" " +i);
else
blocksDisplay[i].setText(" " +i);
blocksDisplay[i].setEditable(false);
// blocksDisplay[i].setBackground(Red);
blocksPanel.add(blocksDisplay[i]);
}//end for
//add componets to panels
//add text fields
textInputPanel.add(start);
textInputPanel.add(stop);
textInputPanel.add(step);
//add lables
textInputPanel.add(custStartLabel);
textInputPanel.add(custStopLabel);
textInputPanel.add(custStepLabel);
//add button to panel
buttonPanel.add(goButton);
buttonPanel.add(clearButton);
//ADD ACTION LISTENRS TO BUTTONS (!IMPORTANT)
goButton.addActionListener(this);
clearButton.addActionListener(this);
add(blocksPanel, BorderLayout.NORTH);
add(textInputPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
//overridding the windowcClosing() method will allow the user to clisk the Close button
addWindowListener(
new WindowAdapter()
{
public void windowCloseing(WindowEvent e)
{
System.exit(0);
}
}
);
}//end of constructor method
public void actionPerformed(ActionEvent e)
{
//if & else if to see what button clicked and pull user input
if(e.getSource() == goButton) //if go clicked ...
{
System.out.println("go clicked");
try{
String inputStart = start.getText();
int varStart = Integer.parseInt(inputStart);
if (varStart<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("start = " + varStart);
// roomDisplay[available].setBackground(lightRed);
String inputStop = stop.getText();
int varStop = Integer.parseInt(inputStop);
if (varStop<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("stop = " + varStop);
String inputStep = step.getText();
int varStep = Integer.parseInt(inputStep);
if (varStep<=0 || varStep>=15 )throw new NumberFormatException();
System.out.println("step = " + varStep);
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
}
catch (NumberFormatException ex)
{
JOptionPane.showMessageDialog(null, "You must enter a Start, Stop and Step value greater than 0 and less than 15",
"Error",JOptionPane.ERROR_MESSAGE);
}
}
else if(e.getSource() == clearButton ) //else if clear clicked ...
{
System.out.println("clear clicked");
}
//int available = room.bookRoom(smoking.getState());
//if (available > 0)//Rooms is available
}//end action performed method
public static void main(String[]args)
{
Checkerboard frame = new Checkerboard ();
frame.setBounds(50, 100, 300, 410);//changed size to make text feilds full charater size
frame.setTitle("Checkerboarder Array");
frame.setVisible(true);
}//end of main method
}
The problem is your loop: your loop variable name is i but you change the varStep variable instead of i so basically the loop variable never changes and thus the exit condition will never be true.
I believe you want to step i with varStep, so change your loop to:
for (int i = varStart; i<varStop; i += varStep)
// stuff inside loop
Take a look at this loop.
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
It ends when i >= varStop, but neither i nor varStop change as a consequence of its execution, so it can never stop. You only increment varStep.
I think you want to increment i by varStep on each iteration instead, i.e. i += varStep
You use varStep++ in your for loop. I think you meant to do i+varStep.
The application freezes because you're never increasing i, resulting in an endless loop.

Java GUI, organizing a dialog box to get data from the user

I am designing a GUI for my research project. I want to create a dialog box that gets information from the user. Here is the screenshot:
Here is the code for the screenshot above:
JTextField projnameField = new JTextField(10);
JTextField nField = new JTextField(5);
JTextField mField = new JTextField(5);
JTextField alphaField = new JTextField(5);
JTextField kField = new JTextField(5);
JFileChooser inputfile = new JFileChooser();
inputfile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
File file = inputfile.getSelectedFile();
String fullpath = file.getAbsolutePath();
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("Project Name:"));
myPanel.add(projnameField);
myPanel.add(new JLabel("Number of instances:"));
myPanel.add(nField);
myPanel.add(new JLabel("Number of attributes:"));
myPanel.add(mField);
myPanel.add(new JLabel("Alpha:"));
myPanel.add(alphaField);
myPanel.add(new JLabel("Number of patterns:"));
myPanel.add(kField);
myPanel.add(new JLabel("Please select your datset:"));
myPanel.add(inputfile);
myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS));
int result = JOptionPane.showConfirmDialog(
null, myPanel, "CPM Program", JOptionPane.OK_CANCEL_OPTION);
double alpha = Double.parseDouble(alphaField.getText());
int numpat = Integer.parseInt(kField.getText());
int num_inst = Integer.parseInt(nField.getText());
int num_attr = Integer.parseInt(mField.getText());
String projname = (projnameField.getText());
In reference to the above image I have two questions:
Notice the labels are centered. How can I put those in the left side like this:
Project name: --textbox--
Number of instances: --textbox--
In the label, "Please select you dataset", I want to browse the file, select it and copy the full path in a blank box in the front of "Please select you dataset" label, but I do not know how I should do it.
1- The first problem is that all of the labels such as project name or number of instances are centered (it seems!). How can I put those in the left side?
JLabel has a constructor that takes an int as one of the parameters, and you can use it to position your text held in the JLabel.
2- The second problem is that text fields are not in the front of labels and are below of them. I want to have each text field in the front of the label such as:
Layouts are the key here. Consider using GridBagLayout (which can be somewhat difficult to use initially) or MigLayout (easier to use but you have to download it first) to allow use of a more tabular structure for your GUI.
For example, please have a look at my code in this answer for an example of tabular structure using GridBagLayout.
You might use a GroupLayout for that first section. E.G.
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
class TwoColumnLayout {
/**
* Provides a JPanel with two columns (labels & fields) laid out using
* GroupLayout. The arrays must be of equal size.
*
* Typical fields would be single line textual/input components such as
* JTextField, JPasswordField, JFormattedTextField, JSpinner, JComboBox,
* JCheckBox.. & the multi-line components wrapped in a JScrollPane -
* JTextArea or (at a stretch) JList or JTable.
*
* #param labels The first column contains labels.
* #param fields The last column contains fields.
* #param addMnemonics Add mnemonic by next available letter in label text.
* #return JComponent A JPanel with two columns of the components provided.
*/
public static JComponent getTwoColumnLayout(
JLabel[] labels,
JComponent[] fields,
boolean addMnemonics) {
if (labels.length != fields.length) {
String s = labels.length + " labels supplied for "
+ fields.length + " fields!";
throw new IllegalArgumentException(s);
}
JComponent panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
// Turn on automatically adding gaps between components
layout.setAutoCreateGaps(true);
// Create a sequential group for the horizontal axis.
GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
GroupLayout.Group yLabelGroup = layout.createParallelGroup(GroupLayout.Alignment.TRAILING);
hGroup.addGroup(yLabelGroup);
GroupLayout.Group yFieldGroup = layout.createParallelGroup();
hGroup.addGroup(yFieldGroup);
layout.setHorizontalGroup(hGroup);
// Create a sequential group for the vertical axis.
GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
layout.setVerticalGroup(vGroup);
int p = GroupLayout.PREFERRED_SIZE;
// add the components to the groups
for (JLabel label : labels) {
yLabelGroup.addComponent(label);
}
for (Component field : fields) {
yFieldGroup.addComponent(field, p, p, p);
}
for (int ii = 0; ii < labels.length; ii++) {
vGroup.addGroup(layout.createParallelGroup().
addComponent(labels[ii]).
addComponent(fields[ii], p, p, p));
}
if (addMnemonics) {
addMnemonics(labels, fields);
}
return panel;
}
private final static void addMnemonics(
JLabel[] labels,
JComponent[] fields) {
Map<Character, Object> m = new HashMap<Character, Object>();
for (int ii = 0; ii < labels.length; ii++) {
labels[ii].setLabelFor(fields[ii]);
String lwr = labels[ii].getText().toLowerCase();
for (int jj = 0; jj < lwr.length(); jj++) {
char ch = lwr.charAt(jj);
if (m.get(ch) == null && Character.isLetterOrDigit(ch)) {
m.put(ch, ch);
labels[ii].setDisplayedMnemonic(ch);
break;
}
}
}
}
/**
* Provides a JPanel with two columns (labels & fields) laid out using
* GroupLayout. The arrays must be of equal size.
*
* #param labelStrings Strings that will be used for labels.
* #param fields The corresponding fields.
* #return JComponent A JPanel with two columns of the components provided.
*/
public static JComponent getTwoColumnLayout(
String[] labelStrings,
JComponent[] fields) {
JLabel[] labels = new JLabel[labelStrings.length];
for (int ii = 0; ii < labels.length; ii++) {
labels[ii] = new JLabel(labelStrings[ii]);
}
return getTwoColumnLayout(labels, fields);
}
/**
* Provides a JPanel with two columns (labels & fields) laid out using
* GroupLayout. The arrays must be of equal size.
*
* #param labels The first column contains labels.
* #param fields The last column contains fields.
* #return JComponent A JPanel with two columns of the components provided.
*/
public static JComponent getTwoColumnLayout(
JLabel[] labels,
JComponent[] fields) {
return getTwoColumnLayout(labels, fields, true);
}
public static String getProperty(String name) {
return name + ": \t"
+ System.getProperty(name)
+ System.getProperty("line.separator");
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
JTextField projnameField = new JTextField(10);
JTextField nField = new JTextField(5);
JTextField mField = new JTextField(5);
JTextField alphaField = new JTextField(5);
JTextField kField = new JTextField(5);
JTextField[] components = {
projnameField,
nField,
mField,
alphaField,
kField
};
String[] labels = {
"Project Name:",
"Number of instances:",
"Number of attributes:",
"Alpha:",
"Number of patterns:"
};
JOptionPane.showMessageDialog(null,
getTwoColumnLayout(labels,components));
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}

How to know what component was clicked from a grid?

I have created a grid that contains 10x10 buttons using 2d arrays. i tried x.getSource().getLabel() but compiler says they are not compatible. also i want to get the specific button that was clicked.
I want to get the exact button that was clicked from the grid i made and get its label. what method i need to use?
import javax.swing.JFrame; //imports JFrame library
import javax.swing.JButton; //imports JButton library
import java.awt.GridLayout; //imports GridLayout library
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class ButtonGrid extends JFrame implements ActionListener
{
JFrame frame=new JFrame(); //creates frame
JButton[][] grid; //names the grid of buttons
public int x;
public int y;
public ButtonGrid(int width, int length)
{ //constructor
char temp;
String charput;
frame.setLayout(new GridLayout(width,length)); //set layout
grid = new JButton[width][length]; //allocate the size of grid
for(int y=0; y<length; y++)
{ //start
for(int x=0; x<width; x++)
{
temp=charRand(); //get random character
charput = ""+temp; //converts character to string
grid[x][y]=new JButton(); //creates new button
frame.add(grid[x][y]); //adds button to grid
grid[x][y].addActionListener(this);
grid[x][y].setLabel(charput); //set charput as label
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); //sets appropriate size for frame
frame.setVisible(true); //makes frame visible
}
/* generates randomiz letter for the button of the grid*/
public char charRand()
{
String consonantList = new String("BCDFGHL"); //list 1
String consonantList2 = new String("MNPRSTWY"); //list 2
String consonantList3= new String("JQXZVK"); //list 3
String vowelList = new String("AEIOU"); //list of vowels
int vowelOrConsonant; //holder of random number
int chosen; //selects the chosen random letter
Random randGen = new Random(); //generates random int value
char selected; //gets the random letter chosen by variable chosen
vowelOrConsonant = randGen.nextInt(4);
if (vowelOrConsonant == 0)
{
chosen = randGen.nextInt(5); //list of vowels
selected = vowelList.charAt(chosen); //selects a char from vowels
}
else if(vowelOrConsonant == 1)
{
chosen = randGen.nextInt(7); //list 1
selected = consonantList2.charAt(chosen); //selects a char
}
else if(vowelOrConsonant == 2)
{
chosen = randGen.nextInt(8); //list 2
selected = consonantList2.charAt(chosen); //selects a char
}
else
{
chosen = randGen.nextInt(6); //list 3
selected = consonantList.charAt(chosen);
}
return selected; //returns the random letter
}
public static void main(String[] args)
{
new ButtonGrid(10,10);//makes new ButtonGrid with 2 parameters
}
public void actionPerformed(ActionEvent x)
{
/* i get wrong output on this line.
* i want to get the exact button that was clicked and get its label.
*/
if (x.getSource()==grid[x][y])
JOptionPane.showMessageDialog(null,x.getSource().getLabel);
}
}
getSource() returns an Object, so you need to cast it to JButton, like this:
public void actionPerformed(ActionEvent x) {
JOptionPane.showMessageDialog(null, ((JButton)x.getSource()).getText());
}
Also note that getLabel() and setLabel() are deprecated and should be replaced by getText() and setText().
You can make a class that extends Jbutton. and add two fields to it of type int(X & Y ). The constructor will look like this: public MyButton(int x, y);
And when you are filling your grid, don't use directly the Jbutton class. Use your class and for X & Y supply the i & j parameters of the two for cycles that you are using. Now when you are using Action Listener for your button you can use his X & Y fields as they represent its place on the grid. Hope this helps! It tottaly worked for me and its simple as hell.

Incorporating two Java classes into one

I'm new in object-oriented programming and I use Java. I'm stil finding it hard to manipulate through the classes using generics and stuff. As a practice, I looked for codes in the internet and my colleague suggested me a program that came from this site.
This is the first class:
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class quine extends JFrame implements ActionListener, WindowListener{
/**
*
*/
private static final long serialVersionUID = 1L;
static ArrayList<Term>[][] table=new ArrayList[5][5]; // SERVES AS OUR STORAGE FOR ARRANGING TERMS AND TO OUR RESULTING TERMS THAT ARE BEING COMPARED.
static Vector<String> inputTerm= new Vector <String>(); // STORES OUR ORIGINAL INPUT/NUMBERS
static Vector<String> resultingTerms= new Vector <String>(); // STORES RESULTING TERMS FOR EACH SET OF COMPARISON
static int var=0; //NUMBER OF VARIABLE
static int numbers=0; //NUMBER OF INPUTS
final static int maxTerms=1000; //MAXIMUM NUMBER OF TERMS WITH SAME NUMBER OF 1'S
static TextField result = new TextField(" ",50);
static TextField text;
static TextField text1;
static quine qWindow;
static String finalT = "";
public static void main(String[] args){
qWindow = new quine("Quine-McCluskey Simulator"); //creates a window
qWindow.setSize(400,250); //sets the size of the window
qWindow.setVisible(true); //makes the window visible
qWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); //CLOSES THE WINDOW WHEN CLOSING OR CLICKING THE X BUTTON
JOptionPane.showMessageDialog(null, "Welcome to my Quine-McCluskey Simulator!"); //DISPLAYS MESSAGE
}//end main
public static int count_one(String temp){ //COUNT 1'S FROM EACH TERM
int count=0;
char[] tempArray=temp.toCharArray();
int i=0;
while(i<temp.length()){
if(tempArray[i]=='1'){
count++;
}
i++;
}//end while
return count;
}//end one
public static void getPrimeImplicants(){ // PAIRS TERMS UNTIL NOTHING TO PAIR, END TERMS ARE OUR PRIME IMPLICANTS
table=createTermTable(inputTerm);
printTermTable();
createPairing();
}
public static ArrayList<Term>[][] createTermTable(Vector <String> input){ // CREATE TABLE, ARRANGES TERMS BASED ON THE NUMBER OF 1'S IN
//EACH TERM USING count_one,therefore, row 1 contains terms with 1 1 bit.
Term temp;
int one=0;
int element=0;
ArrayList[][] arrayLists = new ArrayList[var+1][maxTerms+1]; //CREATES AN ARRAY WITH VAR ROWS CORRESPONDING TO POSSIBLE NUMBER OF
// 1 FOR EACH TERM AND 1000 COLUMNS
ArrayList<Term> [][]tempTable = arrayLists;
for(int x=0;x<=var;x++){ //?
for(int y=0;y<=maxTerms;y++){
tempTable[x][y]= new ArrayList<Term>();
}//end y
}//end for x
for(int i=0;i<input.size();i++){
one=count_one(input.get(i)); //COUNT 1'S FROM EACH TERM
temp=initTerm(input.get(i),false); // INITIALIZE PROPERTIES OF THAT TERM
while(!tempTable[one][element].isEmpty()){
element++;
}//end while
tempTable[one][element].add(temp);
element=0;
} //end for
return tempTable;
}//end createTermTable
public static Term initTerm(String n,boolean u){ //INITIALIZE USED and NUM PROPERTY OF THE TERM
Term term=new Term();
term.used=u; // TO INDICATE IF THE TERM IS ALREADY PAIRED
term.num=n; // THE TERM ITSELF
return term;
}//end initTerm
public static void printTermTable(){ // PRINTS THE COMPUTATION/TABLES
System.out.println("\nCOMPUTING:");
for(int i=0;i<var+1;i++){
System.out.print(i);
System.out.println(" --------------------------------------------");
for(int j=0;!table[i][j].isEmpty();j++){ //PRINTS TERM ON EACH ROW WHILE TERM IS NOT EMPTY
System.out.println(table[i][j].get(0).num);
}//end for j
}//end for i
}
public static void createPairing(){ //PAIRS A TERM TO EACH TERM ON THE NEXT ROW
int finalterms=0;
String term_num="";
int found=0;
Vector<String> preResult= new Vector<String>();
for(int x=0;x<=var-1;x++){ // REPEATS PAIRING OF A TERMS OF THE TABLE VAR TIMES TO MAKE SURE WHAT ARE LEFT ARE PRIME IMPLICANTS
preResult=new Vector<String>(); // STORES THE RESULTING TERMS FOR EACH SET OF PAIRING
for(int i=0;i<=var;i++){ //COMPARES A ROW WITH EACH TERMS ON THE NEXT ROW
//Vector <String> rowResult= new Vector<String>(); //STORES RESULTING TERMS ON THAT PARTICULAR TERM OF THE ROW. THIS IS TO AVOID REPETITIONS
for(int j=0;!table[i][j].isEmpty();j++){ // TERM ON THE ROW BEING COMPARED WITH EACH TERM ON NEXT ROW
if(i+1!=var+1) // MAKES SURE THAT THE PROCESS NOT EXCEEDS THE ARRAYBOUND
for(int k=0;!table[i+1][k].isEmpty();k++){ //TERM ON THE NEXT ROW THAT IS BEING COMPARED WITH TERM ON THE CURRENT ROW.
term_num=pair(table[i][j].get(0).num,table[i+1][k].get(0).num); //ASSIGNS RESULT OF PAIRING TO term_num
if(term_num!=null){ // IF PAIRING IS SUCCESSFUL
table[i+1][k].get(0).used=true; // TERM IS PAIRED/USED
/*if(!rowResult.contains(term_num)){ //MAKES SURE THAT TERM IS NOT REPEATE
rowResult.add(term_num);
found=1;
}
*/
if(!preResult.contains(term_num)){ // MAKES SURE THAT TERM IS NOT REPEATED
preResult.add(term_num);
found=1;
finalterms++; // COUNTS THE FINAL/RESULTING TERMS FOR THIS SET OF PAIRING
}//end if !resultingTerms
found=1;
}//end if term_num!=null
}//end for k
if(found==0){ // IF TERM IS NOT SUCCESSFULLY PAIRED/USED, ADD TO THE RESULTING TERMS FOR THIS SET
if(table[i][j].get(0).used!=true){
preResult.add(table[i][j].get(0).num);
}
}
found=0;
}//end for j
}//end for i
table=createTermTable(preResult); // CREATE ANOTHER TABLE FOR NEXT SET. THE NEW TABLE CONTAINS THE RESULTING TERMS OF THIS SET
if(preResult.size()!=0)
resultingTerms=preResult; //IF THE ARE RESULTING TERMS, THEN PRINT AND ASSIGN TO resultingterms. THE END VALUE OF resultingterms WILL BE SIMPLIFIED
printTermTable();
}//end for x
}//end createPairing
public static String pair(String a,String b){
int difference=-1;
char []array1 = new char[a.length()];
char []array2;
for(int i=0;i<var;i++){
array1=a.toCharArray(); //CONVERTS TERMS OF TYPE STRING TO TERMS OF TYPE CHAR
array2=b.toCharArray();
if(array1[i]!=array2[i]){ // IF NOT EQUAL FOR A PARTICULAR CHARACTER FOR THE FIRST TIME, THEN GET THE INDEX CORRESPONDING TO THAT CHARACTER.
if(difference==-1)
difference=i;
else //IF NOT NOT EQUAL FOR THE FIRST TIME, THEN THE TERMS DIFFER IN MORE THAN 1 PLACE
return null;
}//end if
}//end for
if(difference==-1) //THE TERMS ARE INDENTICAL, RETURN NULL, PAIRING UNSUCCESSFUL
return null;
char[] result= a.toCharArray(); //CHARACTER CORRESPONDING TO THE INDEX WHERE TERMS DIFFER ONLY ONCE WILL BE CHANGED TO '-'
result[difference]='-';
String resulTerm= new String(result);
return resulTerm; //RETURNS THE MODIFIED TERM, PAIRING SUCCESSFUL
}//end pair
public static void simplifymore(){ //SIMPLIFY THE RESULTINGTERMS
int primes=resultingTerms.size(); // RESULTING TERMS CORRESPOND TO OUR PRIME IMPLICANTS
int[][] s_table= new int[primes][numbers]; //CREATES A TABLE WITH ROWS EQUAL TO NUMBER OF PRIME IMPLICANTS AND COLUMNS EQUAL TO THE NUMBER OF THE ORIGINAL INPUT
for(int i=0;i<primes;i++){
for(int j=0;j<numbers;j++){
s_table[i][j]=implies(resultingTerms.get(i),inputTerm.get(j));
}//end for j
}//end for i
Vector <String> finalTerms= new Vector<String>(); // STORES THE FINALTERMS
int finished=0;
int index=0;
while(finished==0){ //UNTIL ALL ELEMENTS ARE NOW TURNED TO 0
index=essentialImplicant(s_table);
if(index!=-1)
finalTerms.add(resultingTerms.get(index)); // IF RESULTING TERM IS THE ONLY ONE IMPLYING THE CURRENT ORIGINAL TERM, THEN ADD TO FINAL TERMS
else{ // THOSE THAT HAVE MORE THAN ONE IMPLICATION FOR A PARTICULAR ORIGINAL TERM
index=largestImplicant(s_table);
if(index!=-1)
finalTerms.add(resultingTerms.get(index)); //ADD TO FINAL TERMS IF LARGEST IMPLICANT(ONE WHICH HAS MORE NUMBER OF 1'S. SEE COMMENTS ON largestImplicant.
else
finished=1; //IF INDEX IS -1 THEN ALL ELEMENTS HAVE ALREADY BEEN DELETED OR HAVE MADE VALUE 0
}//end else
}//end while finished
System.out.println("Final Terms :");
for(int x=0;x<finalTerms.size();x++) //PRINTS THE FINAL TERMS IN BINARY FORMAT
System.out.println(finalTerms.get(x));
printSimplified(finalTerms);
}//end simplifymore
public static void printSimplified(Vector <String> finalTerms){
String temp="";
char[] tempArray;
char variables[]= {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; //basis for our variables to printed
int index=0;
int i=0;
int j=0;
System.out.print("F = ");
while(i<finalTerms.size()){ //until all final terms are printed in algebraic form.
temp=finalTerms.get(i); //assigns current final term to temp
tempArray=temp.toCharArray(); //CONVERTS TEMP TO ARRAY
while(j<var){
if(tempArray[j]=='-'){ //IGNORES -
index++;
}
else if (tempArray[j]=='0'){
finalT+=variables[26-var+index]+"'"; // PRINTS THE CORRESPONDING LETTER.IF CHARACTER IS 0 THEN APPEND ' AFTER THE VARIABLE
index++;
}
else if (tempArray[j]=='1'){
finalT+=variables[26-var+index]; // PRINTS CORRESPONDING LETTER
index++;
}
else{};
j++;
}//end while
if(i<finalTerms.size()-1)
finalT+=" + "; // APPENDS +
i++;
temp="";
j=0;
index=0;
}//end while
System.out.println(finalT);
}//print simplified
public static int essentialImplicant(int[][] s_table){ // CHECKS EACH RESULTING TERM IMPLYING A PARTICULAR ORIGINAL TERM
for(int i=0;i<s_table[0].length;i++){ //
int lastImplFound=-1;
for(int impl=0;impl<s_table.length;impl++){
if(s_table[impl][i]==1){ //IF RESULTING TERM IMPLIES ORIGINAL TERM
if(lastImplFound==-1){
lastImplFound=impl;
}else{ // IF MORE THAN ONE IMPLICATION,THEN IT IS NOT AN ESSENTIAL PRIME IMPLICANT.GO TO NEXT ORIGINAL TERM
lastImplFound=-1;
break;
}//end else
}
}
if(lastImplFound!=-1){ // ONE IMPLICATION FOR THE ORIGINAL TERM. THIS IS AN ESSENTIAL PRIME IMPLICANT
implicant(s_table,lastImplFound);
return lastImplFound;
}
}//end for impl
return -1;
}
public static void implicant(int [][] s_table,int impA){ // DELETE OR MAKE VALUE 0 THE ROW WHERE THE ESSENTIAL PRIME IMPLICANT IS AND THE COLUMNS OF ALL THE ORIGINAL TERMS IMPLIED BY IT
for(int i=0;i<s_table[0].length;i++){
if(s_table[impA][i]==1)
for(int impB=0;impB<s_table.length;impB++){
s_table[impB][i]=0;
}
}
}//end implicant
public static int largestImplicant(int[][] s_table){
int maxImp=-1;
int max=0;
for(int imp=0;imp<s_table.length;imp++){ // LOCATES WHICH HAS MORE NUMBER OF 1'C IN EACH PRIME
int num=0;
for(int i=0;i<s_table[0].length;i++){
if(s_table[imp][i]==1)
num++;
}//end for i
if(num>max){ // TERM WITH MORE 1'S AT THE END OF THE LOOP WILL BE ADDED TO THE FINAL TERMS
max=num;
maxImp=imp;
}//end if num>max
}//end for imp
if(maxImp!=-1){ // IF WE HAVE SUCCESSFULLY LOCATED A PRIME IMPLICANT
implicant(s_table,maxImp); // DELETE OR MAKE VALUE 0 THE ROW WHERE THE ESSENTIAL PRIME IMPLICANT IS AND THE COLUMNS OF ALL THE ORIGINAL TERMS IMPLIED BY IT
return maxImp;
}//end if maxImp!=-1
return -1;
}
public static int implies(String term1, String term2){ // RETURNS 1 IF RESULTING TERM IMPLIES THE ORIGINAL TERM, 0 OTHERWISE
char[] term1Array=term1.toCharArray();
char[] term2Array=term2.toCharArray();
//EX. ORG TERM IS 100100, RES TERM IS 1--10- ,RESULTING TERM IMPLIES THE ORIGINAL TERM. SINCE - HERE IS TREATED AS 0 OR 1
for(int i=0;i<var;i++){
if(term1Array[i]!=term2Array[i] && term1Array[i]!='-')
return 0;
}
return 1;
}
//end class
public quine(String name){
super(name); //ASSIGNS LABEL OF THE WINDOW
setLayout(new GridLayout(1, 1)); //SETS THE LAYOUT
setLocation(350,200); //SETS THE LOCATION OF THE WINDOW ON THE SCREEN
GridBagLayout gridbag = new GridBagLayout(); //used to align buttons
GridBagConstraints constraints = new GridBagConstraints();//to specify the size and position for the gridbaglayout
setLayout(gridbag);
constraints.weighty = 1; //distributes spaces among columns
constraints.weightx = 1; //distributes spaces among rows
constraints.gridwidth = GridBagConstraints.REMAINDER; //to specify that the component be the last one in its column
Label label1 = new Label(" How many variables does the function have?"); //CREATES A LABEL
label1.setVisible(true); //MAKES THE LABEL VISIBLE, ASSIGNS NEW FONT AND COLOR THEN ADD TO THE WINDOW
label1.setFont(new Font("Sans Serif", Font.BOLD, 12));
label1.setBackground(Color.CYAN);
add(label1);
text1= new TextField("",10);
gridbag.setConstraints(text1,constraints); //applies constraints to text
text1.setEditable(true); //SO THAT WE COULD STILL HAVE AN UNLIMITED LENGTH OF INPUT
text1.setForeground(Color.black);
text1.setBackground(Color.white);
text1.setVisible(true);
text1.addActionListener(this); //ACTIVATES ACTIONLISTENER FOR THIS FIELD
add(text1);
label1 = new Label(" Please list all the minterms that evaluates to 1:");//CREATES LABEL
gridbag.setConstraints(label1,constraints);
label1.setVisible(true); //MAKES THE LABEL VISIBLE, ASSIGNS NEW FONT AND COLOR THEN ADD TO THE WINDOW
label1.setBackground(Color.green);label1.setFont(new Font("Sans Serif", Font.BOLD, 12));
label1.setBackground(Color.CYAN);
add(label1);
text = new TextField("Enter your numbers here separated by a comma",50);
gridbag.setConstraints(text,constraints); //applies constraints to text
text.setEditable(true); //ENABLES UNLIMITED LENGTH OF INPUT
text.setForeground(Color.black);
text.setBackground(Color.white);
text.setVisible(true);
text.addActionListener(this); //ACTIVATES ACTIONLISTENER FOR THIS FIELD
text.setForeground(Color.blue);
add(text);
JButton enter = new JButton ("Enter"); // CREATES BUTTON NAMED Enter
enter.setVisible(true); //MAKES IT VISIBLE, APPLIES THE CONSTRAINTS, AND ADD TO THE WINDOW
add(enter);
enter.setBackground(Color.green);
enter.addActionListener(this); //ACTIVATES ACTIONLISTENER
gridbag.setConstraints(enter,constraints);
JButton reset = new JButton ("Reset"); // CREATES BUTTON NAMED Reset
reset.setVisible(true); //MAKES IT VISIBLE, APPLIES THE CONSTRAINTS, AND ADD TO THE WINDOW
gridbag.setConstraints(reset,constraints);
reset.setBackground(Color.green);
add(reset);
reset.addActionListener(this);
label1 = new Label(" Result:");
gridbag.setConstraints(label1,constraints);
label1.setVisible(true);
label1.setBackground(Color.cyan);
label1.setFont(new Font("Sans Serif", Font.BOLD, 12));
label1.setBackground(Color.CYAN);
add(label1);
result = new TextField(" ",50);
gridbag.setConstraints(result,constraints); //applies constraints to text
result.setEditable(true);
result.setForeground(Color.black);
result.setBackground(Color.white);
result.setVisible(true);
add(result);
}
public void actionPerformed(ActionEvent e) {
String stringInput="";
String numOfVar="";
String temp="";
String temp1="";
int num=0;
if(e.getActionCommand() == "Enter"){ // IF Enter BUTTON IS CLICKED
stringInput = text.getText(); // GETS STRING INPUT FROM TEXT(MINTERMS)
numOfVar = text1.getText(); //GETS STRING INPUT FROM TEXT1(VARIABLES)
var = Integer.parseInt(numOfVar); //CONVERTS numOfVar TO INTEGER
StringTokenizer token= new StringTokenizer(stringInput," ,"); //TOKENIZE INPUT. ELIMINATE ALL COMMAS AND SPACES
while(token.hasMoreTokens()){ //WHILE THERE ARE MORE TOKENS
temp1=token.nextToken(); //GETS TOKEN
numbers++; //COUNTS THE NUMBER OF INPUTS
num=Integer.parseInt(temp1); //CONVERT INPUT TO INTEGER
temp=Integer.toBinaryString(num); //CONVERTS INTEGER FORM OF INPUT TO BINARY IN ITS PROPER LENGTH BASED ON THE NUMBER OF VARIABLES GIVEN
if(temp.length()!=var){
while(temp.length()!=var){
temp="0"+temp;
}
}
inputTerm.add(temp); //ADDS RESULT(BINARY FORM) TO inputTerm
}//end while
getPrimeImplicants(); //GET PRIMEIMPLICANTS
simplifymore(); // SIMPLIFY MORE
result.setText(finalT); // DISPLAYS THE RESULT (SIMPLIFIED) TO RESULT TEXTFIELD
}//end if
if(e.getActionCommand()== "Reset"){ //RESETS THE VALUES FOR NEXT SET OF INPUTS
var=0;
table=new ArrayList[5][5]; // SERVES AS OUR STORAGE FOR ARRANGING TERMS AND TO OUR RESULTING TERMS THAT ARE BEING COMPARED.
inputTerm= new Vector <String>(); // STORES OUR ORIGINAL INPUT/NUMBERS
resultingTerms= new Vector <String>(); //STORES THE RESULTING TERMS FOR EACH COMPUTATION
finalT=""; //STORES THE FINAL TERMS IN THEIR ALGEBRAIC FORM
numbers=0; //COUNTS THE NUMBER OF INPUTS FROM THE USER
text.setText(""); //ERASE THE TEXTS DISPLAYED ON THE TEXT FIELDS
text1.setText("");
result.setText("");
}
}
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {qWindow.setVisible(false);} //CLOSES THE WINDOW AFTER PROGRAMS STOPS RUNNING
public void windowClosing(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
}//end class
And this is the second class. Funny (it only consists of less than 10 lines unlike the first one)
public class Term {
public String num;
public boolean used;
}
Can you please help me incorporate these two classes into one (if that's possible)? I tried declaring String num and boolean used inside the first class and removed the Term but it shows lot of errors. I tried separating the initTerm method into two: one returns a string and the other boolean. But it adds error. What else can I do? Can you also advise me some techniques in doing this?
You can put the whole class inside quine so that Term becomes an inner class of quine. The class Term is then visible to the code in quine and you don't need a separate file anymore for the class Term.
1) Don't declare variables as public unless they are static. It's standard practise to use getter/setter methods to access member variables.
2) Have you tried creating a super class that extends JFrame then get quine to extend that class. Add getter/setters in the super class. Then the sub class can access them via getVariable() etc etc.
3) Class names should start with an upper case letter. Variables, methods and package names should all be lower case.

Categories

Resources