Display output from a method on a JPanel in Java - java

I have a GUI the gets an input from a text area and on the click of button produces a report. The report is supposed to be displayed below the input area. On the click of the button, the input data are passed to a a void method called Calculate(), and right now the correct results are displayed on the console by System.out.printf(). How can I redirect this output to the report area?
public class Progress extends JFrame
{
JTextArea input;
JButton calculate;
JPanel report;
public void Notify()
{
calculate = new JButton("Calculate");
calculate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Calculate();
}
});
}
}
...
public void Calculate()
{
GenerateReport m = new GenerateReport();
m.Parsecsv(input.getText());
}
So, as a newbie to Java, I wanted to know how I can redirect the output of my Calculate() method to the report panel?

Well you could modify your Calculate to return a string containing the information you want to print into the text area. I assume you know how to make simple methods that aren't void and return a data type:
public String Calculate() {
<something to get the text needed is done here>
return <text from report>;
}
Then you could make a "JOptionPane.showMessageDialog( Calculate() )" to show the report, or you could as mentioned create a JLabel to print the report within the frame your working with.
Something like:
JLabel lab1 = new JLabel(null, Calculate() );
If I understand you right?

I think what you're trying to ask is, "What is a JLabel?". You can use a JLabel to output your text from your calculate method.
Or you can return a String from your calculate method and somehow display it otherwise.

Related

Why is my boolean value preemptively being returned?

I am working on a login validator and have a class that checks username and password validity. After checking, a boolean variable (isValidLoginCredentials) is updated in the LoginProxy class, which can be fetched by a get method and used for another purpose. However, the value that is returned by the get method is always the default value that I assigned to isValidLoginCredentials when the class was created. I think the issue is that I am calling the getter method in main() before I have a chance to update isValidLoginCredentials, but I don't understand what changes I should make to stop this. Here is the relevant part of the class and main program.
public class LoginProxy implements ActionListener
{
private JLabel usernameLabel;
private JTextField usernameText;
private JLabel passwordLabel;
private JPasswordField passwordText;
private JButton loginButton;
private boolean isValidLoginCredentials = false;
public void createLogin()
{
/*Here was code irrelevant to the problem I removed*/
loginButton.addActionListener(new LoginProxy());
loginButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String user = usernameText.getText();//get the username
String pass = passwordText.getText();//get the password
String credentials = user +":"+pass;//creates the string I compare to other valid
//credentials
ConcreteLoginValidator validator = new ConcreteLoginValidator(credentials);
try
{
isValidLoginCredentials = validator.checkLogin();
System.out.println("The credentials are "+isValidLoginCredentials);
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
}
});
}
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
}
public boolean getValidity()
{
return isValidLoginCredentials;
}
And here is the main method
public static void main(String[] args)
{
boolean isValidLogin = false;
LoginProxy proxy = new LoginProxy();
proxy.createLogin();
isValidLogin = proxy.getValidity();
if(isValidLogin == true)
{
JFrame frame = MainUI.getInstance();
frame.setSize(900, 600);
frame.pack();
frame.setVisible(true);
}
}
What should I add so that isValidLogin=proxy.getValidity(); returns a value only after I have already entered and checked whether the login credentials are correct?
Going straight to the point, a quick fix is to put the code below:
if(isValidLoginCredentials) {
JFrame frame = MainUI.getInstance();
frame.setSize(900, 600);
frame.pack();
frame.setVisible(true);
}
After this part:
System.out.println("The credentials are "+isValidLoginCredentials);
The code you call on createLogin() just sets the action listener to the button in the UI, hence the code will be executed just when you click on the button.
On the top of that, when you open a window, it starts a separated thread. I don't know the rest of the code, but assuming that when you instantiate the LoginProxy, it opens the login window. But the way you wrote, it will open the window and check the isValidLogin straight away (it doesn't wait you to click the button).
If you want to prove that, you can simply put a System.out.println before and after the proxy.createLogin(). You will realise that both lines will be reached while the UI is rendered.
Using a modal dialog that blocks until it is closed.
Very simplified example:
public class Dialog { // LoginProxy in questions code
private String value = null;
public void show(Window owner) {
var dialog = new JDialog(owner, JDialog.DEFAULT_MODALITY_TYPE);
var field = new JTextField(40);
var okButton = new JButton("OK");
okButton.addActionListener(ev -> {
value = field.getText();
dialog.dispose();
});
var panel = new JPanel();
panel.add(field);
panel.add(okButton);
dialog.add(panel);
dialog.pack();
dialog.setLocationRelativeTo(owner);
dialog.setVisible(true); // this will be blocked until JDialog is closed
}
public String getValue() {
return value;
}
}
called like
public static void main(String[] args) {
var dialog = new Dialog();
dialog.show(null);
System.out.println(dialog.getValue()); // check if valid and open JFrame in questions code
}
Advantage of this solution IMHO: the dialog class (LoginProxy) does not need to know about the main class and main JFrame. It has a clear single function: ask for user input.
the dialog creation is even easier using JOptionPane
In order to guarantee reading a value written in another thread, you must make the field volatile:
private volatile boolean isValidLoginCredentials;
You must also wait until the other completes before reading it. That aspect I leave to the reader.

get value of changed JTextField on Java Swing

Hey guyz i'm working on a GPA calculator for my java assignment, and the gui i have created is 100% based on Events i.e. no buttons for the user to submit his data. my question is how do i know if a textfield value has changed and if it did how do i get the original value befor the change.
another question how can i store each component in an arrayList do the user can create as many rows as they like Thanks
this is the snapshot of mu GUIenter image description here
BTW feel free any other suggestion
You can use keylistener
JTextField usernameTextField= newJTextField();
usernameTextField.addKeyListener(new () { public void keyReleased(Key KeyAdapter Event e) { JTextField textField = (JTextField) e.getSource(); String text = textField.getText(); textField.setText(text.toUpperCase()); } public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { } });

how to array,ascending,descending,bubble,inputarea,outputarea in JFrame

I don't know where to start I don't want to be spoon fed either. Help me with tons of problem.
My goal in this program is to get input from the user by letting them type in the input area and there area three button (ascending, array, bubble sort) must them to pick and then the output must show in outputarea.
my code only ends up in getting the input of the user in input area.
My problems are:
Can I tell the user to input like this (1, 2, 3, 5, 6) with comma and neglected the comma then convert it to array to sort it.
After they click the either three buttons how can i output it in the output area.
Is my code in the right track or not? :D
Sorry for my bad english.
i dont want to be spoonfeed just help me guys :D
more power stackoverflow
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JavaGui205 extends JPanel
{
final JTextField inputarea,outputarea;
final JButton asc,desc,bubble;
int getsd;
JavaGui205()
{
//initialize textfield and buttons
inputarea=new JTextField("Inputarea",20);
outputarea=new JTextField("Outputarea",20);
asc=new JButton("Ascending");
desc=new JButton("Descending");
bubble=new JButton("BubbleSort");
//adding function on fields
inputarea.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==inputarea)
{
String sd=e.getActionCommand();
getsd=Integer.parseInt(sd);
}
}
});
//ascending function
asc.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
}
});
//adding to frame
add(inputarea);
add(asc);
add(desc);
add(bubble);
add(outputarea);
}
public static void main(String[]args)
{
JFrame frame = new JFrame("WTF");
frame.add(new JavaGui205());
frame.setVisible(true);
frame.setSize(300,150);
}
}
I try some fixixation.I add these code tnx to mr Wyatt Lowery.but i have some problems how can i convert those string array into integer array then contain its values to use to three buttons then the product of those will display in the output area.Im sorry guys im slowpoke T_T :D i try my best to research but nothing happens
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==inputarea)
{
String sd=inputarea.getText();
String[] inputArray=sd.split(",\\s*");
}
}
Your problems in order:
Get the string from the text field inputarea.getText() and store it into a variable(E.g. inputText = inputarea.getText()). You can use the method split() to separate the values and put it into an array(E.g. String[] inputArray = inputText.split(", "))
When the button is clicked, set the outputarea text equal to the array
(E.g. outputarea.setText(inputArray.toString()))
Try working on your coding conventions :-)

Java Swing default focus on frame

I am learning java and Swing right now and trying to develop simple programms for education purposes.
So here is the question.
I have gridlayout and fields on my frame with default text
accNumberField = new JTextField("0", 10);
accNumberField.addFocusListener(new FocusListener() {
int focusCounter = 0;
#Override
public void focusGained(FocusEvent arg0) {
// TODO Auto-generated method stub
if (focusCounter > 0)
accNumberField.setText("");
focusCounter++;
}
What I want is that when user click on field for the first time the default text is disappered. So I add focus listener and used accNumberField.setText(""); in focusGained method.
But the problem is that for default first field in my frame getting focus right in time of frame creation. And default text is disappearing from the begining. I used counter as you can see. But that's not what I wanted.
I want that no field would get focus in time of creation and every field would be able to get focus from the time when user would click on one of them.
Sorry if I spelled something wrong. English is not my native language.
Found a thread having a code example of your desired functionality, Java JTextField with input hint. Precisely, you need to provide your own implementation of JTextField which will be holding the "default-text" in a field, specially created for that.
For your second question, you can set the focus to some button or frame itself.
Is there any reason that you use focusListener()? why not use mouseListener() as follow?
accNumberField.addMouseListener(new MouseAdapter()
{
#Override
public void mouseReleased(MouseEvent e)
{
accNumberField.setText("");
}
});
if you want to clear the text for the first click, you can simply use a boolean:
//outside constructor
private boolean isTextCleared = false;
//in constructor
accNumberField.addMouseListener(new MouseAdapter()
{
#Override
public void mouseReleased(MouseEvent e)
{
if (!isTextCleared)
{
accNumberField.setText("");
isTextCleared = true;
}
}
});

Passing input from one frame to another(JAVA)

Here's the thing...
I have 2 GUI programs.
A Menu Program,which is basically a frame with buttons of food items,the buttons when clicked
opens this other program,an Input Quantity Program,which is a frame with a text field,buttons for numbers,buttons for Cancel and Confirm. The quantity that is confirmed by the user will be accessed by the menu program from the Input Quantity Program to be stored in a vector so that every time a user wants to order other food items he will just click another button and repeat the process.
Now I've coded the most part and got everything working except one thing,the value returned by the Input Quantity Program has this delay thing.
This is what I do step by step:
1)Click a food item in Menu,it opens the Input Quantity window.
2)I input the number I want,it displayed in the text box correctly.
3)I pressed confirm which will do 3 things,first it stores the value of the text field to a variable,second it will call the dispose() method and third a print statement showing the value of the variable(for testing purposes).
4)The menu program then checks if the user has already pressed the Confirm button in the Input program,if true it shall call a method in the Input program called getQuantity() which returns the value of the variable 'quantity' and store it in the vector.
5)After which executes another print statement to check if the passed value is correct and then calls the method print() to show the ordered item name and it's recorded quantity.
Here are the screenshots of the GUI and the code will be below it.
ActionPerformed method of the CONFIRM BUTTON in the Input Quantity Program:
private void ConfirmButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
confirmed = true;
q= textField.getText().toString();
quantity =Integer.parseInt(q) ;
System.out.println("getQTY method inside Input Quantity Interface:" +getQuantity());
System.out.println("Quantity from confirmButton in Input Quantity Interface actionPerformed: "+quantity);
//getQuantity();
}
ACTION LISTENER CLASS of the MENU ITEM BUTTONS in MENU PROGRAM which does step 2 above:
class f implements ActionListener {
#Override
public void actionPerformed(ActionEvent e)
{
inputGUI.setVisible(true);
int q =0;
q=inputGUI.getQuantity(); //call method to get value from Input Program
System.out.println("Quantity inside Menu actionperformed from AskQuantity interface: "+q);
orderedQuantity.add(q); //int vector
textArea.append("\n"+e.getActionCommand()+"\t"+ q);
orderedItems.add(e.getActionCommand()); //String vector
print();
/*
System.out.println("Enter QTY: ");
int qty = in.nextInt();
orderedQuantity.add(qty);
print();*/
}
Here are screenshots of the print statements in the console:
Here I first ordered Pumpkin Soup,I entered a quantity of 1
Here I ordered seafood marinara and entered a quantity of 2
Here I ordered the last item,pan fried salmon and entered a quantity of 3
As you can see the first recorded quantity is 0 for the first item I ordered then when I added another item,the quantity of the first item gets recorded but the 2nd item's quantity is not recorded..same goes after the third item... and the quantity of the 3rd item is not recorded even if the program terminates :(
How can I solve this problem?
I think I see your problem, and in fact it stems directly from you're not using a modal dialog to get your input. You are querying the inputGUI before the user has had a chance to interact with it. Hang on while I show you a small example of what I mean...
Edit
Here's my example code that has a modal JDialog and a JFrame, both acting as a dialog to a main JFrame, and both using the very same JPanel for input. The difference being the modal JDialog will freeze the code of the main JFrame at the point that it has been made visible and won't resume until it has been made invisible -- thus the code will wait for the user to deal with the dialog before it progresses, and therein holds all the difference.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DialogExample {
private static void createAndShowGui() {
JFrame frame = new JFrame("Dialog Example");
MainPanel mainPanel = new MainPanel(frame);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MainPanel extends JPanel {
private InputPanel inputPanel = new InputPanel();
private JTextField responseField = new JTextField(10);
private JDialog inputDialog;
private JFrame inputFrame;
public MainPanel(final JFrame mainJFrame) {
responseField.setEditable(false);
responseField.setFocusable(false);
add(responseField);
add(new JButton(new AbstractAction("Open Input Modal Dialog") {
#Override
public void actionPerformed(ActionEvent e) {
if (inputDialog == null) {
inputDialog = new JDialog(mainJFrame, "Input Dialog", true);
}
inputDialog.getContentPane().add(inputPanel);
inputDialog.pack();
inputDialog.setLocationRelativeTo(mainJFrame);
inputDialog.setVisible(true);
// all code is now suspended at this point until the dialog has been
// made invisible
if (inputPanel.isConfirmed()) {
responseField.setText(inputPanel.getInputFieldText());
inputPanel.setConfirmed(false);
}
}
}));
add(new JButton(new AbstractAction("Open Input JFrame") {
#Override
public void actionPerformed(ActionEvent e) {
if (inputFrame == null) {
inputFrame = new JFrame("Input Frame");
}
inputFrame.getContentPane().add(inputPanel);
inputFrame.pack();
inputFrame.setLocationRelativeTo(mainJFrame);
inputFrame.setVisible(true);
// all code continues whether or not the inputFrame has been
// dealt with or not.
if (inputPanel.isConfirmed()) {
responseField.setText(inputPanel.getInputFieldText());
inputPanel.setConfirmed(false);
}
}
}));
}
}
class InputPanel extends JPanel {
private JTextField inputField = new JTextField(10);
private JButton confirmBtn = new JButton("Confirm");
private JButton cancelBtn = new JButton("Cancel");
private boolean confirmed = false;
public InputPanel() {
add(inputField);
add(confirmBtn);
add(cancelBtn);
confirmBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
confirmed = true;
Window win = SwingUtilities.getWindowAncestor(InputPanel.this);
win.setVisible(false);
}
});
cancelBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
confirmed = false;
Window win = SwingUtilities.getWindowAncestor(InputPanel.this);
win.setVisible(false);
}
});
}
public boolean isConfirmed() {
return confirmed;
}
public void setConfirmed(boolean confirmed) {
this.confirmed = confirmed;
}
public String getInputFieldText() {
return inputField.getText();
}
}
So solution: use a modal JDialog.
Suppose i am having two GUI frames f1 and f2. Now by clicking a button on f1 i want to invoke frame f2 and also sending some data from f1(frame class) to f2(frame class).
One possible way is to declare a constructor in f2 which takes the same data as parameters which i wanted to send to it from f1.Now in frame f1's coding just include these statements:
f1.setVisible(false);//f1 gets invisible
f2 newFrame=new f2(uname,pass);//uname and pass have been takenfrom f1's text fields
f2.setVisible(true);
I think this will clear up your problem.

Categories