My program is suppose to make a GUI that calculates the square root of a number that is entered. I can not figure out why this code will not compile. I keep getting the following error message:
cannot find symbol
symbol : method getText(double)
What am I doing wrong?
import java.awt.event.ActionEvent; //Next group of lines import various Java classes
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.GridLayout;
import java.text.*;
public class SquareRoot extends JFrame
{
public static void main(String[] args) {
//Creates Window
JFrame frame = new JFrame();
frame.setSize(450, 300);
frame.setTitle("Find the Square Root");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel Numberlbl = new JLabel("Enter a number:");
final JTextField NumberField = new JTextField(10);
NumberField.setText("");
JLabel Answerlbl = new JLabel("Square Root of your number is:");
final JTextField AnswerField = new JTextField(10);
AnswerField.setText("");
JLabel ButtonLabel = new JLabel("Calculate Square Root");
JButton button = new JButton("√");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,2));
panel.add(Numberlbl);
panel.add(NumberField);
panel.add(ButtonLabel);
panel.add(button);
panel.add(Answerlbl);
panel.add(AnswerField);
frame.add(panel);
class CalculateListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
double NumberX = Double.parseDouble(NumberField.getText());
double Answer = Math.sqrt(NumberX);
AnswerField.setText(Answer);
}
}
ActionListener listener = new CalculateListener();
button.addActionListener(listener);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
The only compilation error I got was for the AnswerField.setText() line - if you look at the API reference for setText() it takes a string, but you are trying to pass it a double.
Have a look at the NumberFormat class for converting the double to a string correctly. A simpler option is to use a Double object (as opposed to the double data type, note capitalization), and use its toString() method. A down-and-dirty method is to write it as ("" + Answer), since it will auto-convert it for you.
The code will not compile because the method setText(String text) expects a String parameter, and you are giving it a double.
To make your code work, use:
AnswerField.setText(String.valueOf(Answer));
final Double answer = Math.sqrt(NumberX);
AnswerField.setText(answer.toString());
This one compiles. Here you go:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SquareRoot extends JFrame
{
public static void main(String[] args) {
//Creates Window
JFrame frame = new JFrame();
frame.setSize(450, 300);
frame.setTitle("Find the Square Root");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel numberlbl = new JLabel("Enter a number:");
final JTextField numberField = new JTextField(10);
numberField.setText("");
JLabel answerlbl = new JLabel("Square Root of your number is:");
final JTextField answerField = new JTextField(10);
answerField.setText("");
JLabel buttonLabel = new JLabel("Calculate Square Root");
JButton button = new JButton("√");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,2));
panel.add(numberlbl);
panel.add(numberField);
panel.add(buttonLabel);
panel.add(button);
panel.add(answerlbl);
panel.add(answerField);
frame.add(panel);
class CalculateListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
double numberX = Double.parseDouble(numberField.getText());
double answer = Math.sqrt(numberX);
answerField.setText(""+answer);
}
}
ActionListener listener = new CalculateListener();
button.addActionListener(listener);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Related
Hello I found a Projekt on yt where you can search for a keyword and it will show all the websites it found on google. And right now I am trying to revive the keyword the user put in the textfield but it isn't working. It does not find the textfield (tf1) I made, but I don't know what I did wrong. Thanks in advance!
here's my code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Main implements ActionListener {
public static void main(String[] args) {
int frameWidth = 600;
int frameHeight = 600;
JFrame f = new JFrame();
JLabel l1 = new JLabel();
JTextField tf1 = new JTextField();
JButton b1 = new JButton();
f.getContentPane().setBackground(Color.PINK);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.setSize(frameWidth, frameHeight);
f.setTitle("Search");
f.setLocationRelativeTo(null);
f.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
f.add(l1);
f.add(tf1);
f.add(b1);
l1.setText("Enter Keywords");
tf1.setPreferredSize(new Dimension(200, 20));
tf1.revalidate();
b1.setText("Search");
b1.addActionListener(new Main());
f.setVisible(true);
// ArrayList<WebCrawler> bots = new ArrayList<>();
// bots.add(new WebCrawler("", 1));
// bots.add(new WebCrawler("", 2));
// bots.add(new WebCrawler("", 3));
// for(WebCrawler w : bots) {
// try {
// w.getThread().join();
//
// }catch(InterruptedException e) {
// e.printStackTrace();
// }
// }
}
#Override
public void actionPerformed(ActionEvent e) {
String keyword = tf1.getText(); //Here it does not find the tf I made
System.out.println(keyword); //just for confirmation
}
}
You have a reference issue.
tf1 is declared as a local variable within main, which makes it inaccessible to any other method/context. Add into the fact that main is static and you run into another problem area.
The simple solution would be to make tf1 a instance field. This would be further simplified if you grouped your UI logic into a class, for example...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JLabel label;
private JTextField textField;
private JButton searchButton;
public TestPane() {
setBorder(new EmptyBorder(32, 32, 32, 32));
setBackground(Color.PINK);
setLayout(new GridBagLayout());
label = new JLabel("Enter Keywords: ");
textField = new JTextField(20);
searchButton = new JButton("Search");
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(8, 8, 8, 8);
gbc.gridx = 0;
gbc.gridy = 0;
add(label, gbc);
gbc.gridx++;
add(textField, gbc);
gbc.gridy++;
gbc.gridx = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(searchButton, gbc);
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
JOptionPane.showMessageDialog(TestPane.this, "You want to search for: " + text);
}
};
textField.addActionListener(listener);
searchButton.addActionListener(listener);
}
}
}
This is basic Java 101. You might find something like What is the difference between a local variable, an instance field, an input parameter, and a class field? of help
I have created a JFrame with 3 JTextFields, a button and a label in the centre of the page. I will create a key where if the user enters 'a' in all three textfields and hits the button, the color of the text in the label should change to a different colour for example red.
The main problem I have is linkning my textfields and the button so they work together.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CE203_2017_Ex1 extends JFrame
{
public static void window()
{
//Button
JButton but = new JButton("Submit");
//JNumberTextField
JTextField rgb1 = new JTextField("",3);
JTextField rgb2 = new JTextField("",3);
JTextField rgb3 = new JTextField("",3);
//JLabel
JLabel text1 = new JLabel("hello my name is adam ", JLabel.CENTER);
text1.setForeground(Color.BLUE);
text1.setAlignmentX(0);
text1.setAlignmentY(0);
//JFrame
JFrame window1 = new JFrame("Adam");
window1.setVisible(true);
window1.setSize(500,500);
window1.add(text1);
//JPanel
JPanel butPanel = new JPanel();
butPanel.add(rgb1);
butPanel.add(rgb2);
butPanel.add(rgb3);
butPanel.add(but);
window1.add(butPanel, BorderLayout.SOUTH);
window1.add(text1);
Here is my actionlistener for the button
but.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JTextField input = (JTextField) e.getSource();
String passy = input.getText();
String p = new String (passy);
if (rgb1.equals("a")&& rgb2.equals("a")&& rgb3.equals("a")){
text1.setForeground(Color.WHITE);
}
else{
JOptionPane.showMessageDialog(null, "nocorrect");}}});
}
public static void main( String[] args )
{
window();
}
}
You want to test the text value in the textFields not the objects.
if (rgb1.getText().equals("a")&& rgb2.getText().equals("a")&& rgb3.getText().equals("a")) {
text1.setForeground(Color.WHITE);
}
I am a beginner here and I am trying to make a GUI that will display two buttons, addCard and deleteCard. However, the compiler is showing errors, and I cannot seem to find the error. Thank you in advance!
package studyfast;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Scratch{
JFrame projectFrame = new JFrame();
projectFrame.setSize(1000, 600);
projectFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panelEditCard = new JPanel();
JButton addCard = new JButton();
JButton deleteCard = new JButton();
panelEditCard.add(addCard);
panelEditCard.add(deleteCard);
projectFrame.add(panelEditCard);
projectFrame.setVisible(true);
public static void main(String[] args){
new Scratch();
}
}
You need to move your code inside the Scratch class inside a constructor
package studyfast;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Scratch
{
JFrame projectFrame = new JFrame();
JPanel panelEditCard = new JPanel();
JButton addCard = new JButton();
JButton deleteCard = new JButton();
public Scratch()
{
projectFrame.setSize(1000, 600);
projectFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
panelEditCard.add(addCard);
panelEditCard.add(deleteCard);
projectFrame.add(panelEditCard);
projectFrame.setVisible(true);
}
public static void main(String[] args)
{
new Scratch();
}
}
More help needed with this little project of mine again, this time trying to get two labels that are inside a panel in certain positions. Those positions being one on the left and then a separation of spaces (like a tab) and then the second label to make way for entries being added below them when a button is pressed which I am also unsure how to start.
I've uploaded an image of the current program running :
As you can see I have two buttons (may change to one at some point) and then a separate results panel with currently two labels inside that I want to move. I want 'Name' to be on the left side and 'Grade' slightly more to the right (separated by about a tabs worth of space). I'm also unsure what the two little lines are so if someone could explain that to me it would be great.
Where I plan to go with this is then for a button entry to lead to a name entry being entered below these labels and a grade entry being entered below these labels which keeps updating with each button press. If anyone could guide me in the right direction for this it would be great. I have provided the code for the panel below.
Thanks for taking the time to read this!
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GradePanel2 extends JPanel {
private JButton addEntry, calculate;
private JLabel name, grade, nameResult, gradeResult;
private JTextField nameField, gradeField, resultField;
public GradePanel2() {
// Button to add entry to list
addEntry = new JButton("Add entry to list");
addEntry.addActionListener(new buttonListener());
// Button to print all entries in correct format
calculate = new JButton("Print all user grades");
calculate.addActionListener(new buttonListener());
//Create Labels
name = new JLabel("Enter student name: ");
nameField = new JTextField(10);
nameField.addActionListener(new buttonListener());
grade = new JLabel("Enter students mark: ");
gradeField = new JTextField(5);
gradeField.addActionListener(new buttonListener());
//Result Labels
nameResult = new JLabel("NAME");
gradeResult = new JLabel("GRADE");
//Bottom segment for result
resultField = new JTextField();
resultField.setOpaque(false);
resultField.setEditable(false);
setLayout(new BorderLayout());
//Bottom Panel
JPanel GradePanel = new JPanel();
GradePanel.setBorder(BorderFactory.createTitledBorder("Students/Results"));
GradePanel.setOpaque(false);
GradePanel.setPreferredSize(new Dimension(0 , 100));
GradePanel.add(resultField);
resultField.setAlignmentX(LEFT_ALIGNMENT);
GradePanel.add(nameResult);
GradePanel.add(gradeResult);
//Button Panel
JPanel ButtonPane = new JPanel();
ButtonPane.setLayout(new BoxLayout(ButtonPane, BoxLayout.PAGE_AXIS));
addEntry.setAlignmentX(CENTER_ALIGNMENT);
calculate.setAlignmentX(CENTER_ALIGNMENT);
ButtonPane.add(addEntry);
ButtonPane.add(Box.createVerticalStrut(10));
ButtonPane.add(calculate);
//Label Panel
JPanel labelPane = new JPanel();
labelPane.setLayout(new BoxLayout(labelPane, BoxLayout.PAGE_AXIS));
labelPane.add(name);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(nameField);
labelPane.add(Box.createRigidArea(new Dimension (0,2)));
labelPane.add(grade);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(gradeField);
//Add all panels to the main panel
add(labelPane, BorderLayout.NORTH);
add(ButtonPane, BorderLayout.CENTER);
add(GradePanel, BorderLayout.SOUTH);
setBackground(Color.WHITE);
setPreferredSize(new Dimension(400, 300));
}
public class buttonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String studentName;
int studentMark;
studentName = nameField.getText();
String intMark = gradeField.getText();
studentMark = Integer.parseInt(intMark);
}
}
}
and then the driver class:
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Grade2{
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Grade Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GradePanel2 panel = new GradePanel2();
frame.add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}}
Take time to read this the most flexible Layout Manager that commonly used by programmer :)
https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
Btw I separate your class Bottom Panel It's a little bit confused while reading it. Much better try the Nested Classes to look your code clean and easy to read.
https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GradePanel2 extends JPanel {
private JButton addEntry, calculate;
private JLabel name, grade, nameResult, gradeResult;
private JTextField nameField, gradeField, resultField;
public GradePanel2() {
// Button to add entry to list
addEntry = new JButton("Add entry to list");
addEntry.addActionListener(new buttonListener());
// Button to print all entries in correct format
calculate = new JButton("Print all user grades");
calculate.addActionListener(new buttonListener());
//Create Labels
name = new JLabel("Enter student name: ");
nameField = new JTextField(10);
nameField.addActionListener(new buttonListener());
grade = new JLabel("Enter students mark: ");
gradeField = new JTextField(5);
gradeField.addActionListener(new buttonListener());
//Bottom segment for result
resultField = new JTextField();
resultField.setOpaque(false);
resultField.setEditable(false);
setLayout(new BorderLayout());
GridBagConstraints nameResultConstraints = new GridBagConstraints();//Constraints
GridBagConstraints gradeResultConstraints = new GridBagConstraints();//Constraints
//Button Panel
JPanel ButtonPane = new JPanel();
ButtonPane.setLayout(new BoxLayout(ButtonPane, BoxLayout.PAGE_AXIS));
addEntry.setAlignmentX(CENTER_ALIGNMENT);
calculate.setAlignmentX(CENTER_ALIGNMENT);
ButtonPane.add(addEntry);
ButtonPane.add(Box.createVerticalStrut(10));
ButtonPane.add(calculate);
//Label Panel
JPanel labelPane = new JPanel();
labelPane.setLayout(new BoxLayout(labelPane, BoxLayout.PAGE_AXIS));
labelPane.add(name);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(nameField);
labelPane.add(Box.createRigidArea(new Dimension (0,2)));
labelPane.add(grade);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(gradeField);
myBottomPanel mybottompanel = new myBottomPanel();//Object
//Add all panels to the main panel
add(labelPane, BorderLayout.NORTH);
add(ButtonPane, BorderLayout.CENTER);
add(mybottompanel, BorderLayout.SOUTH);
setBackground(Color.WHITE);
setPreferredSize(new Dimension(400, 300));
}
public class myBottomPanel extends JPanel{
public myBottomPanel()
{
this.setLayout(new GridBagLayout());
//Result Labels
nameResult = new JLabel("NAME");
gradeResult = new JLabel("GRADE");
//Constraints
GridBagConstraints nameResultConstraints = new GridBagConstraints();
GridBagConstraints gradeResultConstraints = new GridBagConstraints();
//Bottom Panel
setBorder(BorderFactory.createTitledBorder("Students/Results"));
setOpaque(false);
setPreferredSize(new Dimension(0 , 100));
nameResultConstraints.anchor = GridBagConstraints.LINE_START;
nameResultConstraints.weightx = 0.5;
nameResultConstraints.weighty = 0.5;
add(nameResult,nameResultConstraints);
add(gradeResult);
}
}
public class buttonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String studentName;
int studentMark;
studentName = nameField.getText();
String intMark = gradeField.getText();
studentMark = Integer.parseInt(intMark);
}
}
}
and here is your Frame.
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Grade2{
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Grade Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GradePanel2 panel = new GradePanel2();
frame.add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}}
OUTPUT
Hope this helps. :)
If you want data displayed in a column then you need to use an appropriate layout manager to achieve the effect you want.
Maybe you can use a GridBagLayout. You can have columns and spaces between the columns, but you need to use the appropriate constraints. Read the section from the Swing tutorial on How to Use GridBagLayout for more information and working examples.
However, the easier option would be to use a JTable which is a component designed for display data in rows/columns. Again check out the Swing tutorial on How to Use Tables.
I am trying to add the buttons to the centerPanel that I created, then add that panel to the main center borderlayout. for some reason though my tab will not repaint anymore. It worked fine a while ago when I had the DrawFieldsListener class in the same class file as the MagicSquare, but nothing in the code has changed from my splitting them into two class files. So i really don't know what is going on. When it did repaint before, it would also take a long time. Any help? thanks!
All source for the project is on GitHub if it is easier to read and understand there: https://github.com/andrefecto/Academic-Convivium-Project
MagicSquare Class:
package magicSquare;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MagicSquare extends JPanel {
JLabel sizeLabel = new JLabel("Enter A Square Size: ");
JButton setSize;
static JButton calculate;
static JButton reset;
static JTextField squareSize;
static JTextField field;
public static ArrayList<JTextField> inputFields = new ArrayList<JTextField>();
public static ArrayList<Integer> inputs = new ArrayList<Integer>();
public static ArrayList<Integer> totals = new ArrayList<Integer>();
public static int squared = 0;
public static int square = 0;
public static JPanel centerPanel = new JPanel();
public static JPanel bottomPanel = new JPanel();
public MagicSquare (){
setLayout(new BorderLayout());
JPanel subPanel = new JPanel();
subPanel.add(sizeLabel);
squareSize = new JTextField();
squareSize.setColumns(6);
subPanel.add(squareSize);
setSize = new JButton("Enter");
subPanel.add(setSize);
setSize.addActionListener(new DrawFieldsListener());
add(subPanel, BorderLayout.NORTH);
add(new DrawFieldsListener(), BorderLayout.CENTER);
}
}
my DrawFieldsListener class:
package magicSquare;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
class DrawFieldsListener extends JPanel implements ActionListener {
int square = MagicSquare.square;
int squared = MagicSquare.squared;
JPanel centerPanel = MagicSquare.centerPanel;
JTextField squareSize = MagicSquare.squareSize;
JTextField field = MagicSquare.field;
ArrayList<JTextField> inputFields = MagicSquare.inputFields;
JButton calculate = MagicSquare.calculate;
JButton reset = MagicSquare.reset;
JPanel bottomPanel = MagicSquare.bottomPanel;
public void actionPerformed(ActionEvent e){
square = Integer.parseInt(squareSize.getText());
squared = square*square;
centerPanel.setLayout(new GridLayout(square, square));
for(int i = 0; i < squared; i++){
field = new JTextField();
field.setColumns(3);
inputFields.add(field);
centerPanel.add(inputFields.get(i));
System.out.println("DRAWING");
}
add(centerPanel, BorderLayout.CENTER);
System.out.println("ADDING ADDITINOAL BUTTONS");
additionalButtons();
System.out.println("ADDED ADDITINOAL BUTTONS");
System.out.println("REPAINTING");
repaint();
System.out.println("REPAINTED");
}
public void additionalButtons(){
calculate = new JButton("Calculate");
reset = new JButton("Reset");
bottomPanel.setLayout(new GridLayout(2, 2));
bottomPanel.add(reset);
bottomPanel.add(calculate);
add(bottomPanel, BorderLayout.SOUTH);
calculate.addActionListener(new CalculateListener());
reset.addActionListener(new ResetListener());
}
}
Mistake #1
public static JPanel centerPanel = new JPanel();
Followed by...
class DrawFieldsListener extends JPanel implements ActionListener {
//...
JPanel centerPanel = MagicSquare.centerPanel;
static is not a cross object communication mechanism...and now I have no idea who is suppose to be responsible for managing the centerPanel...
Remember, static is not your friend, beware of how it is used
Mistake #2
setSize.addActionListener(new DrawFieldsListener());
add(subPanel, BorderLayout.NORTH);
add(new DrawFieldsListener(), BorderLayout.CENTER);
You are creating two instances of DrawFieldsListener (which is a panel), one is acting as the ActionListener and one is acting as the view, but which one is actually housing MagicSquare.centerPanel as a component can only have one parent...
Mistake #3
Not revalidating the container after you have changed it...
public void actionPerformed(ActionEvent e) {
square = Integer.parseInt(squareSize.getText());
squared = square * square;
centerPanel.setLayout(new GridLayout(square, square));
for (int i = 0; i < squared; i++) {
field = new JTextField();
field.setColumns(3);
inputFields.add(field);
centerPanel.add(inputFields.get(i));
System.out.println("DRAWING");
}
add(centerPanel, BorderLayout.CENTER);
System.out.println("ADDING ADDITINOAL BUTTONS");
additionalButtons();
System.out.println("ADDED ADDITINOAL BUTTONS");
System.out.println("REPAINTING");
revalidate();
repaint();
System.out.println("REPAINTED");
}
Swing is lazy when it comes to container management, it assumes that you will want to do a number of adds or removes, so it won't update the container hierarchy layout until you ask it to, as the operation can be expensive
A better solution...
Isolate responsibility and provide information to your objects in a de-coupled manner.
For example, the DrawFieldsListener shouldn't care about MagicSquare, but should provide a means by which "some body" can tell it how many squares it should create.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MagicSquare extends JPanel {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MagicSquare());
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
JLabel sizeLabel = new JLabel("Enter A Square Size: ");
JButton setSize;
private JSpinner squareSize;
JTextField field;
public MagicSquare() {
setLayout(new BorderLayout());
JPanel subPanel = new JPanel();
subPanel.add(sizeLabel);
squareSize = new JSpinner();
subPanel.add(squareSize);
setSize = new JButton("Enter");
subPanel.add(setSize);
DrawFieldsListener dfl = new DrawFieldsListener();
setSize.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int gridSize = (int) squareSize.getValue();
dfl.makeGrid(gridSize);
}
});
add(subPanel, BorderLayout.NORTH);
add(dfl, BorderLayout.CENTER);
}
class DrawFieldsListener extends JPanel {
private JButton calculate;
private JButton reset;
private ArrayList<JTextField> inputFields = new ArrayList<JTextField>();
private ArrayList<Integer> inputs = new ArrayList<Integer>();
private ArrayList<Integer> totals = new ArrayList<Integer>();
private int squared = 0;
private int square = 0;
private JPanel centerPanel = new JPanel();
private JPanel bottomPanel = new JPanel();
public void makeGrid(int gridSize) {
square = gridSize;
squared = square * square;
centerPanel.setLayout(new GridLayout(square, square));
for (int i = 0; i < squared; i++) {
field = new JTextField();
field.setColumns(3);
inputFields.add(field);
centerPanel.add(inputFields.get(i));
System.out.println("DRAWING");
}
add(centerPanel, BorderLayout.CENTER);
System.out.println("ADDING ADDITINOAL BUTTONS");
additionalButtons();
System.out.println("ADDED ADDITINOAL BUTTONS");
System.out.println("REPAINTING");
revalidate();
repaint();
System.out.println("REPAINTED");
}
public void additionalButtons() {
calculate = new JButton("Calculate");
reset = new JButton("Reset");
bottomPanel.setLayout(new GridLayout(2, 2));
bottomPanel.add(reset);
bottomPanel.add(calculate);
add(bottomPanel, BorderLayout.SOUTH);
// calculate.addActionListener(new CalculateListener());
// reset.addActionListener(new ResetListener());
}
}
}