Java Multidemensional Array Loop that inputs data with Button Action - java

Questions I am pulling my hair out over.
How do I get the array to add data to current index, then increment to the next index to add changed JTextField data for the next button press. currently I'm overwriting the same index.
I have tried to figure out actionlisteners for the button "Submit" that uses a counter with nesting of the loop. played with ideas from question 23331198 and 3010840 and 17829577 many others as a reference but didn't really get it to far. Most searches pull up info on managing buttons with arrays and creating button arrays so I assume I'm not using the correct wording to search with. I have read a few places that an MD array is not the best option to use.
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.JTextArea;
import javax.swing.JTextField;
public class GUIandLogicTest extends JFrame
{
// Variable Decloration
private static JFrame mainFrame;
private static JPanel mainPanel;
private static JTextField fieldOne;
private static JTextField fieldTwo;
private static JTextArea textArea;
private static JLabel textFieldOneLabel;
private static JLabel textFieldTwoLabel;
double[][] tutArray = new double[10][2];
// int i =0 ;
// Set GUI method
private void gui()
{
// constructs GUI
mainFrame = new JFrame();
mainFrame.setSize(800, 800);
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
textFieldOneLabel = new JLabel("number 1");
mainPanel.add(textFieldOneLabel);
fieldOne = new JTextField(10);
mainPanel.add(fieldOne);
textFieldTwoLabel = new JLabel("number 2");
mainPanel.add(textFieldTwoLabel);
fieldTwo = new JTextField(10);
mainPanel.add(fieldTwo);
textArea = new JTextArea(50, 50);
mainPanel.add(textArea);
JButton Exit = new JButton("Quit");// Quits program
mainPanel.add(Exit);
Exit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
JButton submit = new JButton("Enter");
// Reads jfields and set varibles to be submitted to array
mainPanel.add(submit);
submit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
double txtField1 = Double
.parseDouble(fieldOne.getText().trim());
double txtField2 = Double
.parseDouble(fieldTwo.getText().trim());
if (txtField1 < 0)
{
}
if (txtField2 < 0)
{
}
int arrayIndex = 0;
tutArray[arrayIndex][0] = txtField1;
tutArray[arrayIndex][1] = txtField2;
arrayIndex++;
for (int i = 0; i < tutArray.length; i++)
{
textArea.append("Number1: " + tutArray[i][0] + " Number2: "
+ tutArray[i][1]);
textArea.append("\n");
textArea.append(String.valueOf(arrayIndex++));
textArea.append("\n");
// textArea.append(String.valueOf(arrayIndex++));
}
}
});
JButton report = new JButton();
// will be used to pull data out of array with formatting and math
mainFrame.setVisible(true);
mainFrame.add(mainPanel);
}
public static void main(String[] arg)
{
GUIandLogicTest GUIandLogic = new GUIandLogicTest();
GUIandLogic.start();
}
public void start()
{
gui();
}
}
This is what I was looking for thanks for the help!
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.JTextArea;
import javax.swing.JTextField;
public class GUIandLogicTest extends JFrame
{
// Variable Decloration
private static JFrame mainFrame;
private static JPanel mainPanel;
private static JTextField fieldOne;
private static JTextField fieldTwo;
private static JTextArea textArea;
private static JLabel textFieldOneLabel;
private static JLabel textFieldTwoLabel;
double[][] tutArray = new double[10][2];
int arrayIndex = 0;
// int i =0 ;
// Set GUI method
private void gui()
{
// constructs GUI
mainFrame = new JFrame();
mainFrame.setSize(800, 800);
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
textFieldOneLabel = new JLabel("number 1");
mainPanel.add(textFieldOneLabel);
fieldOne = new JTextField(10);
mainPanel.add(fieldOne);
textFieldTwoLabel = new JLabel("number 2");
mainPanel.add(textFieldTwoLabel);
fieldTwo = new JTextField(10);
mainPanel.add(fieldTwo);
textArea = new JTextArea(50, 50);
mainPanel.add(textArea);
JButton Exit = new JButton("Quit");// Quits program
mainPanel.add(Exit);
Exit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
JButton submit = new JButton("Enter");
// Reads jfields and set varibles to be submitted to array
mainPanel.add(submit);
submit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
double txtField1 = Double
.parseDouble(fieldOne.getText().trim());
double txtField2 = Double
.parseDouble(fieldTwo.getText().trim());
textArea.setText("");
if (txtField1 < 0)
{
}
if (txtField2 < 0)
{
}
tutArray[arrayIndex][0] = txtField1;
tutArray[arrayIndex][1] = txtField2;
arrayIndex++;
for (int i = 0; i < arrayIndex; i++)
{
textArea.append("Number1: " + tutArray[i][0] + " Number2: "
+ tutArray[i][1]);
// textArea.append("\n");
//textArea.append(String.valueOf(arrayIndex++));
textArea.append("\n");
// textArea.append(String.valueOf(arrayIndex++));
}
}
});
JButton report = new JButton();
// will be used to pull data out of array with formatting and math
mainFrame.setVisible(true);
mainFrame.add(mainPanel);
}
public static void main(String[] arg)
{
GUIandLogicTest GUIandLogic = new GUIandLogicTest();
GUIandLogic.start();
}
public void start()
{
gui();
}
}

You can add the index as a field in your main object:
protected int index;
in your actionPerformed you increase index:
index++;
NOTE:
But why do you extend from JFrame AND use the field mainFrame?
you can use
this.setSize(800,800);
this.add(mainPanel);
Please declare (because of extends JFrame):
private static final long serialVersionUID = 1L;
Please start the name of an object with a lower case letter:
JButton exit = new JButton("Quit");

Related

Connect jbutton to void class

I wanted to connect jcomp1 to the void class somma
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
import javax.swing.*;
import javax.swing.event.*;
#SuppressWarnings({ "unused", "serial" })
public class Calcolatrice extends JPanel {
private JButton jcomp1;
public Calcolatrice() {
//construct components
jcomp1 = new JButton ("Somma");
}
void somma(){
String val1 = jcomp5.getText();
String val2 = jcomp6.getText();
String sum = val1 + val2;
System.out.println(sum);
}
And I tried with:
jcomp1.addActionListener(new ActionListener() {
public void somma(ActionEvent e) {
String val1 = jcomp5.getText();
String val2 = jcomp6.getText();
String sum = val1 + val2;
System.out.println(sum);
}
} );
But it doesn't seem to work...
Any ideas?
I just started coding and I thought this was an easy project but I'm already having troubles. For this reason could you explain as clear as possible please? Thank you.
This is an example of how to create a basic java swing frame with an interactive button.
public class Win extends JFrame implements ActionListener {
private JButton btn;
private JTextField tf;
private JTextField tf1;
private Label label;
private Panel panel;
public Win() {
btn = new JButton("Click");
tf = new JTextField(" ");
tf1 = new JTextField(" ");
label = new Label();
label.setPreferredSize(new Dimension(300,100));
panel = new Panel();
btn.addActionListener(this);
panel.add(btn);
panel.add(tf);
panel.add(tf1);
panel.add(label);
this.add(panel);
this.setSize(500, 500);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
label.setText(tf.getText()+" "+tf1.getText());
System.out.println("clicked");
}
}
You just need to instanciate the win class inside your main method.

Basic Multiply and Divide Java GUI

I am trying to have the number the user inputs into the frame either multiply by 2 or divide by 3 depending on which button they decide to click. I am having an hard time with working out the logic to do this. I know this needs to take place in the actionperformed method.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Quiz4 extends JFrame ActionListener
{
// Global Variable Declarations
// Our list input fields
private JLabel valueLabel = new JLabel("Enter a value between 1 and 20: ");
private JTextField valueField = new JTextField(25);
// create action buttons
private JButton multiButton = new JButton("x2");
private JButton divideButton = new JButton("/3");
private JScrollPane displayScrollPane;
private JTextArea display = new JTextArea(10,5);
// input number
private BufferedReader infirst;
// output number
private NumberWriter outNum;
public Quiz4()
{
//super("List Difference Tool");
getContentPane().setLayout( new BorderLayout() );
// create our input panel
JPanel inputPanel = new JPanel(new GridLayout(1,1));
inputPanel.add(valueLabel);
inputPanel.add(valueField);
getContentPane().add(inputPanel,"Center");
// create and populate our diffPanel
JPanel diffPanel = new JPanel(new GridLayout(1,2,1,1));
diffPanel.add(multiButton);
diffPanel.add(divideButton);
getContentPane().add(diffPanel, "South");
//diffButton.addActionListener(this);
} // Quiz4()
public void actionPerformed(ActionEvent ae)
{
} // actionPerformed()
public static void main(String args[])
{
Quiz4 f = new Quiz4();
f.setSize(1200, 200);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{ // Quit the application
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
} // main()
} // end of class
Here's something simpler, but it essentially does what you want out of your program. I added an ActionListener to each of the buttons to handle what I want, which was to respond to what was typed into the textbox. I just attach the ActionListener to the button, and then in the actionPerformed method, I define what I want to happen.
import java.awt.FlowLayout;
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;
import javax.swing.SwingUtilities;
public class Quizx extends JFrame {
private JPanel panel;
private JTextField textfield;
private JLabel ansLabel;
public Quizx() {
panel = new JPanel(new FlowLayout());
this.getContentPane().add(panel);
addLabel();
addTextField();
addButtons();
addAnswerLabel();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setTitle("Quiz 4");
this.setSize(220, 150);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setVisible(true);
}
private void addTextField() {
textfield = new JTextField();
textfield.setColumns(9);
panel.add(textfield);
}
private void addButtons() {
JButton multButton = new JButton("x2");
JButton divButton = new JButton("/3");
panel.add(multButton);
panel.add(divButton);
addMultListener(multButton);
addDivListener(divButton);
}
private void addLabel() {
JLabel valueLabel = new JLabel("Enter a value between 1 and 20: ");
panel.add(valueLabel);
}
private void addAnswerLabel() {
ansLabel = new JLabel();
panel.add(ansLabel);
}
private void addMultListener(JButton button) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
ansLabel.setText(String.valueOf(Integer.parseInt(textfield.getText().trim()) * 2));
}
});
}
private void addDivListener(JButton button) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
ansLabel.setText(String.valueOf(Double.parseDouble(textfield.getText().trim()) /3));
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Quizx();
}
});
}
}
Hope that helps.

Missing something to finish my program

Im working on my palindrome program and implementing it into a JFrame. Im stuck on how to display the result in the resultTF in the CalculateButtonHandler scope. any help would be appreciated.
Heres my code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class Exercise5 extends JFrame
{
private static final int Width = 400;
private static final int Height = 200;
private JLabel wordJL,resultJL;
private JTextField wordTF,resultTF;
private JButton checkJB,exitJB;
private CalculateButtonHandler checkHandler;
private ExitButtonHandler exitB;
public Exercise5()
{
setTitle ("Palindrome");
wordJL = new JLabel ("Enter a word: ", SwingConstants.RIGHT);
resultJL = new JLabel ("Result: ", SwingConstants.RIGHT);
wordTF = new JTextField(10);
resultTF = new JTextField(10);
checkJB = new JButton ("Calculate");
checkHandler = new CalculateButtonHandler();
exitJB = new JButton ("Exit");
exitB = new ExitButtonHandler();
exitJB.addActionListener (exitB);
Container pane = getContentPane();
pane.setLayout (new GridLayout (3,2));
pane.add(wordJL);
pane.add(wordTF);
pane.add(checkJB);
pane.add(exitJB);
pane.add(resultJL);
pane.add(resultTF);
setSize(Width, Height);
setVisible (true);
setDefaultCloseOperation (EXIT_ON_CLOSE);
}
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
if(e.getSource().equals(checkJB)) {
String pal1, pal2="";
pal1 = wordTF.getText();
int length = pal1.length();
for ( int i = length - 1 ; i >= 0 ; i-- ) {
pal2 = pal2 + pal1.charAt(i);
}
if (pal1.equals(pal2))
resultTF.setText("True");
else
resultTF.setText("False");
}
}
}
private class ExitButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
System.exit(0);
}
}
public static void main (String[] args){
Exercise5 rectObject = new Exercise5();
}
}
you haven't added checkHandler as the action listener of checkJB.. try:
checkJB = new JButton ("Calculate");
checkHandler = new CalculateButtonHandler();
checkJB.addActionListener(checkHandler); //THIS LINE!

Java JFrame cannot create button(arraylist)

I wanted to create dynamic list of buttons using ArrayList. If I copy the method which is written AddButton in constructor , it works. However, If I run this method in ActionListener, it won't work. How do I resolve this ?
Code:
package HelloJFrame;
import java.awt.FlowLayout;
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.JTextField;
public class Main extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextField text1;
public static void main(String[] args) {
// TODO Auto-generated method stub
new Main().setVisible(true);
}
public Main() {
super("Hello JFrame");// Set Title from JFrame constructor
setSize(600, 600);
setResizable(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
text1 = new JTextField(20);
// text.setSize(200, 20);
add(text1);
JButton submit = new JButton("Add Button");
submit.addActionListener(this);
submit.setActionCommand("ekle");
add(submit);
}
#Override
public void actionPerformed(ActionEvent e) {
AddButton(2);
}
public void AddButton(int number) {
ArrayList<JButton> buttons = new ArrayList<JButton>();
for (int i = 0; i < number; i++) {
buttons.add(new JButton("Button #" + i));
}
/*
* JButton button = new JButton("Click!");
* button.addActionListener(this); add(button);
*/
for (int i = 0; i < buttons.size(); i++) {
this.add(buttons.get(i));
}
}
}
After adding all the buttons to the frame you need to add
revalidate();
repaint();
to make sure the layout manager is invoked.
Also, method names should NOT start with an upper case character. "AddButton" should be "addButton".

Undo and redo methods for awt `Graphics` objects

I' making this simple paintbrush-type paint toolbox (some interesting ideas in my previous question)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class MainClass2{
static JLabel colorlabel = new JLabel(" Color ");
public static JLabel xlab = new JLabel("0");
public static JLabel ylab = new JLabel("0");
static JFrame frame1 = new JFrame();
static JButton quitbutton = new JButton("Quit");
static JButton infobutton = new JButton("Info");
static JButton clearbutton = new JButton("Clear");
static JButton savebutton = new JButton("Save");
private static int stroke1 = 4;
static SpinnerNumberModel spinnervals = new SpinnerNumberModel(stroke1,1,15,1);
static JSpinner spinnerbrush = new JSpinner(spinnervals);
static JButton selectcolor = new JButton("Select Color");
static JButton selectbg = new JButton("Select Background");
public static Color col1 = Color.WHITE;
private static Color col2 = Color.WHITE;
static AuxClass4 panel1 = new AuxClass4(col1, col2, stroke1);
static JPanel panel2 = new JPanel();
static JPanel panel3 = new JPanel();
static JPanel panel4 = new JPanel();
private static void addPanel1(){
panel1.setPreferredSize(new Dimension(800,500));
}
private static void addPanel2(){
ButtonAction inst1 = new ButtonAction();
xlab.setMinimumSize(new Dimension(30,30));
ylab.setMinimumSize(new Dimension(30,30));
xlab.setBorder(BorderFactory.createLineBorder(Color.BLACK));
ylab.setBorder(BorderFactory.createLineBorder(Color.BLACK));
panel2.add(new JLabel(" X: "));
panel2.add(xlab);
panel2.add(new JLabel(" Y: "));
panel2.add(ylab);
panel2.add(savebutton);
panel2.add(clearbutton);
panel2.add(quitbutton);
panel2.add(infobutton);
panel2.setLayout(new FlowLayout());
quitbutton.addActionListener(inst1);
infobutton.addActionListener(inst1);
clearbutton.addActionListener(inst1);
savebutton.addActionListener(inst1);
selectcolor.addActionListener(inst1);
selectbg.addActionListener(inst1);
}
//add to panel3
private static void addPanel3(){
StrokeAction inst2 = new StrokeAction();
spinnerbrush.addChangeListener(inst2);
panel3.add(new JLabel("Stroke size"));
panel3.add(spinnerbrush);
panel3.add(selectcolor);
panel3.add(new JLabel("Current color:"));
colorlabel.setSize(20, 20);
colorlabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
colorlabel.setOpaque(true);
colorlabel.setBackground(Color.WHITE);
colorlabel.setForeground(Color.WHITE);
panel3.add(colorlabel);
panel3.add(selectbg);
}
private static class ButtonAction implements ActionListener{
#Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource()==quitbutton){
System.exit(0);
}
else if(arg0.getSource()==infobutton){
JOptionPane.showMessageDialog(frame1, "Paint Toolbox designed in Java");
}
else if(arg0.getSource()==selectcolor){
panel1.changeColor();
}
else if(arg0.getSource()==selectbg){
panel1.changeBg();
}
else if(arg0.getSource()==clearbutton){
panel1.colfg = panel1.colbg;
colorlabel.setBackground(panel1.colfg);
colorlabel.setForeground(panel1.colfg);
panel1.setForeground(null);
}
else if(arg0.getSource()==savebutton){
panel1.saveImage();
}
}
}
private static class StrokeAction implements ChangeListener{
#Override
public void stateChanged(ChangeEvent arg0) {
if (arg0.getSource()==spinnerbrush){
Object o1 = spinnervals.getValue();
Integer int1 = (Integer) o1;
stroke1 = int1.intValue();
panel1.changeStroke(stroke1);
}
// TODO Auto-generated method stub
}
}
public static void main(String args[]){
addPanel1();
addPanel2();
addPanel3();
frame1.add(panel1, BorderLayout.NORTH);
frame1.add(panel2, BorderLayout.SOUTH);
frame1.add(panel3, BorderLayout.CENTER);
frame1.setTitle("PaintBox v2.2");
frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame1.setSize(800,600);
frame1.setResizable(false);
frame1.setLocationRelativeTo(null);
frame1.setVisible(true);
}
}
class AuxClass4 extends JPanel implements MouseMotionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
private int xval;
private int yval;
public Color colfg;
public Color colbg;
public int strokesize;
public int fileorder;
public AuxClass4(Color input1, Color input2, int input3){
colfg=input1;
colbg=input2;
strokesize = input3;
this.setBorder(BorderFactory.createLineBorder(Color.CYAN, 10));
this.setBackground(colbg);
//this.setMaximumSize(new Dimension(500,380));
this.addMouseMotionListener(this);
}
public void paintComponent(Graphics g1){
super.paintComponent(g1);
g1.setColor(colfg);
g1.fillRect(xval, yval, strokesize, strokesize);
}
#Override
public void mouseDragged(MouseEvent arg0) {
xval = arg0.getX();
yval = arg0.getY();
repaint(xval, yval, strokesize,strokesize);
// TODO Auto-generated method stub
}
#Override
public void mouseMoved(MouseEvent arg0) {
xval = arg0.getX();
yval = arg0.getY();
String xvalret = Integer.toString(xval);
String yvalret = Integer.toString(yval);
MainClass2.xlab.setText(" " + xvalret + " ");
MainClass2.ylab.setText(" " + yvalret + " ");
}
public void changeColor(){
colfg = JColorChooser.showDialog(this, "Select color", colfg);
MainClass2.colorlabel.setBackground(colfg);
MainClass2.colorlabel.setForeground(colfg);
}
public void changeBg(){
colbg=JColorChooser.showDialog(this, "Select color", Color.WHITE);
colfg=colbg;
this.setBackground(colbg);
MainClass1.colorlabel.setBackground(colfg);
MainClass1.colorlabel.setForeground(colfg);
}
public void changeStroke(int inputstroke){
strokesize=inputstroke;
}
public void saveImage(){
final String dir = System.getProperty("user.dir");
JOptionPane.showMessageDialog(this, "File saved under " + dir + "/saveimage" + fileorder +".png");
fileorder+=1;
}
}
It works fine for now, but I started wondering if it is possible to implement undo and redo methods for Graphics objects. Intuitively, there should be some way to add the created objects to some table in a 'historical' order. User then should be able to navigate in this table.
Unfortunately, I have no experience with this approach, especially with graphics, so any suggestion would be massively welcome.
I would recommend UndoManager
http://docs.oracle.com/javase/6/docs/api/javax/swing/undo/UndoManager.html
See also the example
http://www.java2s.com/Code/Java/Swing-JFC/Undomanager.htm
Take a look at the command pattern. I think this javaworld article explains it quite nicely.
In a nutshell you will have to have an interface containing undo and redo. Objects that implement this will be added to a list. As you undo and redo you can navigate through the list calling undo and redo. It means that you may have to write more code becuase for every event you actually draw you will have to write the equivelent to undo it.

Categories

Resources