How can I pass data from another class to a GUI? - java

How do I pass data/values from one class to another using GUI? I'm trying to pass the message2 array to namesOut label in GUI. I'm stuck and getting an error.
Here's my code:
GUI
package testClassesGUI;
import java.awt.BorderLayout;
public class UI extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UI frame = new UI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public UI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblDisplayOutNames = new JLabel("Display out names:");
lblDisplayOutNames.setBounds(32, 25, 121, 16);
contentPane.add(lblDisplayOutNames);
JLabel namesOut = new JLabel(""); //here i need to bring the data
namesOut.setBounds(32, 63, 228, 87);
contentPane.add(namesOut);
}
}
Logic:
Here I'm getting an error.
package testClassesGUI;
public class Logic {
private String[] someArray = { "Great", "World" };
// getter method
public String[] message2(){
return someArray;
}
// setter method
public void setSomeArray(String[] someArray){
this.someArray = someArray;
}
UI logicObject = new UI();
logicObject.namesOut.setText(message2); //here my error misplaced construct(s), variable declaratoridexpected
}
Your help is much appreciated.

Put this in your UI constructor. You should create a Logic object in it
public UI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblDisplayOutNames = new JLabel("Display out names:");
lblDisplayOutNames.setBounds(32, 25, 121, 16);
contentPane.add(lblDisplayOutNames);
JLabel namesOut = new JLabel(""); //here i need to bring the data
namesOut.setBounds(32, 63, 228, 87);
contentPane.add(namesOut);
Logic logic = new Logic(); <<---
String[] array = logic.message2(); |
|
String s = ""; |
for (String str : array){ |
s += str + " "; |
} |
|
namesOut.setText(s); <<----
}
You can delete this from your Logic class
UI logicObject = new UI();
logicObject.namesOut.setText(message2);

namesOut is a local variable declared in the constructor of UI. you cannot access it from Logic. declare it as a public member variable
public JLabel namesOut;

You have to define a function. Maybe a constructor:
Logic () {
logicObject.namesOut.setText(message2);
}
Also you can execute inside a code block, but it's not usual:
{
logicObject.namesOut.setText(message2);
}

Related

Passing a varable from a JFrame to another

I want to pass a variable from a JFrame to another when I'm pressing the btnCalculeaza button.
Here is my code:
JButton btnCalculeaza = new JButton("Calculeaza");
btnCalculeaza.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int algad = Integer.parseInt(textField.getText());
int analiza = Integer.parseInt(textField_1.getText());
int be = Integer.parseInt(textField_2.getText());
int depcom = Integer.parseInt(textField_3.getText());
int engleza1 = Integer.parseInt(textField_4.getText());
int engleza2= Integer.parseInt(textField_5.getText());
int fizica= Integer.parseInt(textField_6.getText());
int grafica= Integer.parseInt(textField_7.getText());
int informatica= Integer.parseInt(textField_8.getText());
int matematici= Integer.parseInt(textField_9.getText());
int programare1= Integer.parseInt(textField_10.getText());
int programare2= Integer.parseInt(textField_11.getText());
int tpsm= Integer.parseInt(textField_12.getText());
double nota1;
nota1=(7*algad+analiza*6.0+7*be+3*depcom+2*engleza1+2*engleza2+fizica*7+grafica*3+informatica*4+matematici*6+programare1*5+programare2*4+tpsm*4)/60;
System.out.println(nota1);
new Anul2(nota1).setVisible(true);
Anul2 anul2 =new Anul2();
anul2.setVisible(true);
frame.dispose();
}
});
And the second JFrame:
public class Anul2 extends JFrame {
private double nota1;
public Anul2(double nota1) {
this.nota1 = nota1;
}
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Anul2 frame = new Anul2();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Anul2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 527, 407);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblMediaGeneralaPana = new JLabel("Media generala pana acum:");
lblMediaGeneralaPana.setBounds(12, 331, 160, 16);
contentPane.add(lblMediaGeneralaPana);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setText(Double.toString(nota1));
lblNewLabel.setBounds(171, 331, 56, 16);
contentPane.add(lblNewLabel);
}
}
I would like to pass the nota1 variable to the second JFrame(called Anul2) and then I want to convert it to a JLabel
Your real problem is that your mixing up responsibilities in your code.
You should fully separate your data processing form your UI stuff.
Meaning: you have a local variable
nota1=(7*algad+analiza*6.0+7*be+3*depcom+2*engleza1+2*engleza2+fizica*7+grafica*3+informatica*4+matematici*6+programare1*5+programare2*4+tpsm*4)/60;
and its extremely complicated computation within an action listener. Such things don't belong there.
Instead, you should have a distinct class that only holds all the parameters required for that computation. And then, that class has probably a method computeNota().
Now: in your action listener, you create an object of that class, and then you could pass on that object to new JFRame for example.
Decouple the processing of your data from showing it to the user!
Two ways,
Pass a reference of the first JFrame to the second JFrame Constructor.
Use getFrames() method along with getDeclaredFields() to get the nota1 variable value.

How can i disable jbutton when pressed 10 times

I need some help about Java GUI. I want to add 10 numbers to memory from JTextField. And when it's done JButton must gonna be disable and program must show me a message dialog. How can I do this?
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Uygulama extends JFrame {
private JPanel contentPane;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Uygulama frame = new Uygulama();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Uygulama() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 233, 140);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(48, 13, 116, 22);
contentPane.add(textField);
textField.setColumns(10);
JButton btnHesapla = new JButton("HESAPLA");
btnHesapla.addActionListener(new ActionListener() {int counter = 0;
public void actionPerformed(ActionEvent arg0) {
while(counter < 9) {
counter++;
if(counter == 10) {
buton.setEnabled(false);}
}
});
btnHesapla.setBounds(58, 48, 97, 25);
contentPane.add(btnHesapla);
}
}
Add an ActionListener to your JButton if using Swing, and inside that, you'll increment a global variable by one. Then you ask if the variable is == 10 and do yourButton.setEnabled(false) or yourButton.setEnabled(counter < 10) if you're not using an if. You already have your listener set up, so it's only a matter of adding a variable you'll increment inside it and a call to setEnabled of your button.
Here's a working example with an ArrayList used to store the numbers. No need to use a global count variable here because the size of the ArrayList already tells us how many numbers we have stored :-)
public class NumbersApplication extends JFrame {
private JPanel contentPane;
private JTextField textField;
private List<Integer> numbers;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NumbersApplication frame = new NumbersApplication();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public NumbersApplication() {
numbers = new ArrayList<>();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 233, 140);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(48, 13, 116, 22);
contentPane.add(textField);
textField.setColumns(10);
JButton btnHesapla = new JButton("HESAPLA");
btnHesapla.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int number = Integer.parseInt(textField.getText());
numbers.add(number);
btnHesapla.setEnabled(numbers.size() < 10);
System.out.println(number + " has been added to memory.");
if (numbers.size() == 10) {
System.out.println("Your numbers are: " + numbers);
}
}
});
btnHesapla.setBounds(58, 48, 97, 25);
contentPane.add(btnHesapla);
}
}

Adding resources to a Java project

I'm trying to add an icon to my JButton, but I keep getting an NullPointerException meaning that the image i specified cannot be found.
Both my classes and the buttonremoterefresh.png are directly inside the src folder (the classes are inside the default package). I have been googling this around since last night and no matter what I try, I can't manage to load the resource.
public class InfiltratorClient {
private MainWindow mw;
public static void main(String[] args) {
new InfiltratorClient();
}
public InfiltratorClient () {
mw = new MainWindow();
}
}
public class MainWindow extends JFrame {
private JPanel contentPane;
private InfiltratorClient n;
public MainWindow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
this.setSize(650, 600);
setVisible(true);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(258, 228, 140, 105);
contentPane.add(btnNewButton);
//In this Line i get the exception
ImageIcon icon = new ImageIcon(MainWindow.class.getResource("buttonremorerefresh.png"));
btnNewButton.setIcon(icon);
repaint();
revalidate();
}
}
use this code
JButton button = new JButton();
try {
Image img = ImageIO.read(getClass().getResource("buttonremorerefresh.png"));
button.setIcon(new ImageIcon(img));
} catch (IOException ex) {
}

Scrolling Text Pane JFrame Java

I'm trying to create a sort of log of all the keys hit, at the moment I just need to figure out how to either:
Link the position of the "text" to the scroll bar to the right
OR
Add a different component which is suited better to hold large amounts of multiple line text.
What am I doing wrong here? Thanks!
public class MacroMakerGui extends JFrame {
public static final long serialVersionUID = 1L;
public static JPanel contentPane;
public static JTextField textField = new JTextField();;
public static MacroKeyListener keylistener = new MacroKeyListener(textField);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MacroMakerGui frame = new MacroMakerGui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MacroMakerGui() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 126, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
JButton btnNewButton = new JButton("Record Macro");
btnNewButton.setBounds(10, 220, 99, 30);
contentPane.add(btnNewButton, null);
textField.setBounds(10, 189, 99, 20);
contentPane.add(textField);
textField.setColumns(10);
JEditorPane editorPane = new JEditorPane();
editorPane.setBounds(10, 11, 84, 153);
contentPane.add(editorPane);
JScrollBar scrollBar = new JScrollBar();
scrollBar.setBounds(93, 11, 17, 153);
contentPane.add(scrollBar);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnNewButton.addKeyListener(keylistener);
}
});
}
}
Instead of JScrollBar, use JScrollPanel. Add that to the contentPane, and add your editorPane as a chiled of the JScrollPanel.

Slot Machine Randomise

I am creating a slot machine project(for fun).I am displaying the fruits in a JTextField. I have managed to display random fruits in the JTextFields, but the random fruits are the same, for example, the result would be -> Orange, Orange, Orange. Or it would be, Kiwi, Kiwi, Kiwi. ETC.
Here is my code.
import java.awt.BorderLayout;...
import java.util.Random;
public class Game extends JFrame {
String [] fruits = { "Cherry", "Lemon", "Orange", "Grape", "Kiwi" };
String fruit = fruits[(int) (Math.random() * fruits.length)];
private JPanel contentPane;
private JTextField Slot_1;
private JTextField Slot_2;
private JTextField Slot_3;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Game frame = new Game();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Game() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
Slot_1 = new JTextField();
Slot_1.setText("----------------");
Slot_1.setEditable(false);
Slot_1.setBounds(41, 53, 95, 28);
contentPane.add(Slot_1);
Slot_1.setColumns(10);
Slot_2 = new JTextField();
Slot_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
Slot_2.setText("-----------------");
Slot_2.setEditable(false);
Slot_2.setColumns(10);
Slot_2.setBounds(183, 53, 95, 28);
contentPane.add(Slot_2);
Slot_3 = new JTextField();
Slot_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
Slot_3.setText("---------------");
Slot_3.setEditable(false);
Slot_3.setColumns(10);
Slot_3.setBounds(317, 53, 95, 28);
contentPane.add(Slot_3);
JButton btn_Pull = new JButton("Pull");
btn_Pull.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Slot_1.setText(fruit);
Slot_2.setText(fruit);
Slot_3.setText(fruit);
}
});
btn_Pull.setBounds(145, 108, 166, 29);
contentPane.add(btn_Pull);
JButton btnMenu = new JButton("Menu");
btnMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnMenu.setBounds(383, 243, 61, 29);
contentPane.add(btnMenu);
}
}
Thank you
String fruit = fruits[(int) (Math.random() * fruits.length)];
The value of fruit is fixed at the start of your class.
Slot_1.setText(fruit);
Slot_2.setText(fruit);
Slot_3.setText(fruit);
The value of fruit doesn't change just because you assign it to 3 different text fields.
If you want random values then you need to invoke the random() method 3 time. Maybe something like:
Slot_1.setText( fruits[(int) (Math.random() * fruits.length)] );
...
Or create a method that returns a random string:
private String getFruit()
{
return fruits[(int) (Math.random() * fruits.length)];
}
and use:
slot_1.setText( getFruit() );
Also:
Variable names should not start with an upper case character (Slot_1...). Your other variables are correct (fruits, fruit) so be consistent.
Don't use a null layout. Swing was designed to be used with layout managers.
Slot_1.setText(fruit);
Slot_2.setText(fruit);
Slot_3.setText(fruit);
You expect these the magically change somehow? fruit is simply a string variable, and you only set it once at the top of your class. You need to call the Math.random() function for each slot. You could do this by making fruit a function that got the random number and produced a new fruit each time, then you'd replace fruit above by fruit(). Or you could just copy the simple code line from the top int the lines here.
add a function to your class called generateFruit();
private String generateFruit()
{
return this.fruits[(int) (Math.random() * this.fruits.length)];
}
then call it instead of the set fruit variable.
Slot_1.setText(this.generateFruit());
I also added in a method that changes fruit1, fruit2 and fruit3, and I call that method in the action listener that changes the values. This will change the values every time you push pull.
public class Game extends JFrame {
String [] fruits = { "Cherry", "Lemon", "Orange", "Grape", "Kiwi" };
String fruit1 = fruits[(int) (Math.random() * fruits.length)];
String fruit2 = fruits[(int) (Math.random() * fruits.length)];
String fruit3 = fruits[(int) (Math.random() * fruits.length)];
private JPanel contentPane;
private JTextField Slot_1;
private JTextField Slot_2;
private JTextField Slot_3;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Game frame = new Game();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Game() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
Slot_1 = new JTextField();
Slot_1.setText("----------------");
Slot_1.setEditable(false);
Slot_1.setBounds(41, 53, 95, 28);
contentPane.add(Slot_1);
Slot_1.setColumns(10);
Slot_2 = new JTextField();
Slot_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
Slot_2.setText("-----------------");
Slot_2.setEditable(false);
Slot_2.setColumns(10);
Slot_2.setBounds(183, 53, 95, 28);
contentPane.add(Slot_2);
Slot_3 = new JTextField();
Slot_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
Slot_3.setText("---------------");
Slot_3.setEditable(false);
Slot_3.setColumns(10);
Slot_3.setBounds(317, 53, 95, 28);
contentPane.add(Slot_3);
JButton btn_Pull = new JButton("Pull");
btn_Pull.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Slot_1.setText(fruit1);
Slot_2.setText(fruit2);
Slot_3.setText(fruit3);
newRandomPullValues();
}
});
btn_Pull.setBounds(145, 108, 166, 29);
contentPane.add(btn_Pull);
JButton btnMenu = new JButton("Menu");
btnMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnMenu.setBounds(383, 243, 61, 29);
contentPane.add(btnMenu);
}
public void newRandomPullValues() {
fruit1 = fruits[(int) (Math.random() * fruits.length)];
fruit2 = fruits[(int) (Math.random() * fruits.length)];
fruit3 = fruits[(int) (Math.random() * fruits.length)];
}
}

Categories