Display string method by pressing a button in GUI - java

How would I be able to display this method in a GUI, just by pressing a button in the GUI
private String questionFredricton(){
Object qFredricton = cities.get(1);
String displayFredricton = "Where is " + qFredricton + " located?";
String ansFredricton = provinces.get(1);
return displayFredricton + ansFredricton;
}
I'm guessing something like this??
nextQuestion is my button
private void nextQuestionActionPerformed(java.awt.event.ActionEvent evt) {
print(questionFredricton());
}
I don't want to use use setText() or append() in my button because my strings are being displayed in separate textAreas, already defined in my method. If I do use setText/appnd, it puts all the strings in one box, which is not what I want.
for example by doing:
outputTextQuestion.setText(questionFredricton());//not what I want
Thanks in advance!

I do not think I fully understand what your asking but you could return a custom object rather then a string in your method. The object would have getters and setters for each string value you want to use. Your actionPerformed method then could get the values you need and do whatever with them.
public class MyFredriction
private String display;
private String answer;
public MyFredriction(String display, String answer) {
this.display = display;
this.answer = answer;
}
//TODO public String getDisplay()
//TODO public String getAnswer()
}

Related

How to pass JLabel to another class

I am trying to pass a simple string from a purchase class by throwing it in a getter, then trying to retrieve it from another class called pconfirm. Then trying to set the text of a label in that form to the amount being passed.
Purchase.java
private JLabel lblamnt;
public String amount() {
String gtext = lblamnt.getText();
return gtext;
}
Pconfirm.java
private JLabel lblgamnt;
public Pconfirm() {
Purchase purchase = new Purchase();
lblgamnt.setText("Test" + purchase.amount());
}
When i pass it it shows nothing.
I was under the presumption that you call it by Purchase.amount().
You need to have an actual object to use the method amount()
In your Purchase class constructor hopefully you give access to the JLabel or the ability to set the text like so
Purchase.java
public void setTextOfJLabel(String text)
{
lblamnt.setText(text);
}
Then you could do the following in
Pconfirm.java
private JLabel lblgamnt;
private Purchase purchObjName;
public Pconfirm() {
purchObjName = new Purchase();
purchObjName.setTextOfJLabel("The Purchase JLabel text");
lblgamnt.setText("Pconfirm JLabel text and " + purchObjName.amount());
}
Unless you explicitly set the text before calling amount your text of the JLabel will be null. You could also do something where every Purchase JLabel text is the same until changed by the user using the method I provided and you can set a default text like this
Purchase.java
private final String defaultJLabelText = "Purchase Default Text";
public Purchase()
{
lblamnt = new JLabel();
lblamnt.setText(defaultJLabelText);
}

How do I link the methods to the gui?

I am trying to create a football management system that will allow the user to input data into the gui and then it will save to a database. I have the methods, such as "getName" as shown in the code below and I am unsure how to link that to my gui. I have included the code for my methods and the a link to an image of my gui to allow you to see what it looks like as the code is long. Any help would be appreciated. Thanks.
import java.util.Date;
public class Player {
private int id;
private String forename;
private String surname;
private Date dob;
private String position;
private int number;
private int teamid;
public int getID() {
return id;
}
public void setID(int i) {
id = i;
}
}
By the look of it you need to apply a ActionPerformed event for your Add Button (off the hip):
// ADD Button.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Player player = new Player();
// Player ID
String id = textPlayerID.getText();
if (!id.equals("")) {
// Make sure a numerical value was supplied.
if (id.matches("\\d+")) {
player.setID(Integer.parseInt(id);
}
}
// Player First Name
String firstName = textForename.getText();
if (!firstName.equals("")) {
player.setForename(firstName);
}
// Player Last Name
String LastName = textSurname.getText();
if (!lastName.equals("")) {
player.setSurname(lastName);
}
// Player Date Of Birth
String dob = textDOB.getText();
if (!dob.equals("")) {
// You should add code here to 'validate' the fact that
// a valid date was supplied within the JTextField.
// Format the date desired.
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
// Convert String date to a Date data Type.
Date dateOfBirth = formatter.parse(dob);
player.setDOB(dateOfBirth);
}
// Player Position
String position = textPosition.getText();
if (!position.equals("")) {
player.setPosition(position);
}
// Player Number
String number = textNumber.getText();
if (!number.equals("")) {
// Make sure a numerical value was supplied.
if (id.matches("\\d+")) {
player.setNumber(Integer.parseInt(number);
}
}
// Player Team ID
String teamID = textTeamID.getText();
if (!teamID.equals("")) {
// Make sure a numerical value was supplied.
if (id.matches("\\d+")) {
player.setTeamID(Integer.parseInt(teamID);
}
}
// Create and call a method to add the contents
// of the player object into database. If the
// player already exists within the database then
// use the UPDATE sql statement. If the player
// does not exist within the databse then use the
// INSERT INTO sql statement.
addToDatabase(player);
}
With "link to the GUI" I suppose you mean call those methods when an event occurs in the GUI.
You can do that by first having an instance of your Player-class in your GUI-class and then call those methods in the appropriate event-handlers that are so conveniently but so unorganized created by NetBeans (those somethingActionPerformed methods).
Please be more specific on what you're trying to do if I haven't explained it enough for you and please name your GUI components for more clarity in your code.

Java GUI - How to append text to JTextArea from a static method?

I'm doing a simple exercise about client - server chat using Java IO. This is my code structure:
public class ChatRoomClientGUI{
private JTextArea textAreaMessages;
private JTextField textFieldMessage;
private JButton buttonSendMsg;
//...
private static Socket socket = null;
private static Scanner input = null;
private static PrintWriter output = null;
//...
private static void handleInputStream(){
String response = input.nextLine();
textAreaMessages.append(response + "\n"); // Error here
}
}
The problem I'm facing now is that I can't get access to the textAreaMessages variable because it is non-static and the handleInputStream() method is static. I've tried some ways but none of them works:
change textAreaMessages; to private static JTextArea textAreaMessages; => My IDE (IntelliJ IDEA) yield an error when I run the program
change handleInputStream() to a non-static method => This didn't work either because I call this method from a static context and this can't be changed.
So any ideas how to fix this problem ?
Thanks so much in advanced !
fairly ugly, but if you're sure there is going to be only one instance of your object, then modify (or add) the constructor to set a static variable to this:
private static ChatRoomClientGUI singleton;
...
public ChatRoomClientGUI() {
singleton = this;
...
}
private static void handleInputStream(){
String response = input.nextLine();
singleton.textAreaMessages.append(response + "\n");
}
You can create getter and setter for private JTextArea textAreaMessages; and while calling handleInputStream() pass the instance of this class and call the setter to append the text.
private static void handleInputStream(ChatRoomClientGUI gui) {
String response = input.nextLine();
gui.getTextField().append(response + "\n"); // Error here
}
public void setTextField(JTextField textField) {
this.textAreaMessages = textField;
}
public JTextField getTextField() {
return textAreaMessages;
}

JList selected item to String - Weird result: Donnees.Marques#3d5bac58

I try this and the result is not the value of my item but a value like this Donnees.Marques#3d5bac58
listCategories.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
String selectedCategories = listCategories.getSelectedValue().toString();
System.out.println(selectedCategories);
}
});
Per default when you use the .toString() method on your own objects you are printing its memory address as a string. This is for the same reason that you compare two objects with .equals() and not ==, as the default thing you're tampering with is the object memory address.
To fix this you need to override the super Object's toString metod, like this:
public class ListModel
{
// ...
#Override
public String toString()
{
String text = "I want to print this when I call listModel.toString()";
return text;
}
}
The default renderer for a JList display the toString() implementation of the Object that you are adding to the list.
You need to create a custom renderer for your JList since you are using a custom Object.
Read the section on How to Write a Custom Renderer for more information and examples.
String selectedCategories = listCategories.getSelectedValue().toString();
System.out.println(selectedCategories);
If you want to display a value from your object then you need to do:
Donnes.Marques item = (Donnes.Margues)listCategories.getSelectedValue();
System.out.println(item.getSomeProperty());
Or you can override the toString() method of your Donne.Marquee class.
Maybe try something like this.
DefaultListModel listModel=new DefaultListModel();
jList1.setModel(listModel);
int index = jList1.locationToIndex(evt.getPoint());
String classFromList =listModel.getElementAt(index).toString();
I think, You should override toString() method in your class.
Example
MyObject myObj = listCategories.getSelectedValue();
then
public class MyObject {
public String firstName;
public String lastName;
public int age;
public MyObject() {
}
#Override
public String toString() {
// write your own parametrs like this :
return firstName+" "+lastName;
}
}

Refreshing an FXML Table on button Press

How do you refresh the data in your tableView on button Press using FXML?
I have the following file structure and I want to refresh the data in this table when a button is pressed. Would anyone know a solution?
public class MyTable {
private final SimpleStringProperty ID = new SimpleStringProperty("");
private final SimpleStringProperty ParticipantID = new SimpleStringProperty("");
public Positions() {
this("", "")
}
public Positions(String ID, String ParticipantID) {
setMemberID(ID);
setParticipantID(ParticipantID);
}
public String getParticipantID() {
return ParticipantID.get();
}
public void setParticipantID(String pID) {
ParticipantID.set(ParticipantID);
}
public String getID() {
return ID.get();
}
public void ID(String cID) {
ID.set(ID);
}
}
I initialise this table on the tablecontroller file for this. Now on button press I would like the tableview which is an FXML file update itself. How do I do this?
Thanks but the solution to this was to have one global ObservableList<> data which you then modify on a button press action event. What I was trying to do was create another observable list which does not work.
If you want to update only on button press and not as data is modified that is the default way ?
The simplest way to do would be to create a bean to which all data is updated and the make the button synchronize it with the bean that represents a row in your table.
public class TableBean
{
MyTable child;
String Id;
String ParticipantId;
public void Sync()
{
child.Id(Id);
child.setParticipantID(ParticipantId);
}
}
It is important to note that your methods
violate JavaFX convetion , this probably brakes things. An example of 3 methods used for every propery in JavaFX.
private final IntegerProperty ratio = new SimpleIntegerProperty();
public int getRatio() {
return ratio.get();
}
public void setRatio(int value) {
ratio.set(value);
}
public IntegerProperty ratioProperty() {
return ratio;
}

Categories