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.
Related
The following class creates a form (Jpanel) tasked with acquiring multiples Strings from the user and do something with them. It it functionally working, but it bugs me that the height of the JTextFields (a component that allows for the modification of one line of text) is automatically adjusted and can became extravagantly big.
I have tried the method setBounds(), but:
I do not want to calculate the position or width of the JTextField, just its height; and
It does not limit the height of the JTextField!
Any suggestion, please?
public class MultiplesStrings extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1106317992372206473L;
/** The greater {#link JPanel}. */
private JPanel contentPane;
private JPanel[] interaction;
private JLabel[] text;
private JTextField[] insertText;
/** The {#link JButton} that submits the form information. */
JButton button;
#SuppressWarnings("unused")
private Consumer<MultiplesStrings> instructions;
// =========================================================
// TODO | Constructor
/**
* Create the frame.
*/
public MultiplesStrings(String title, String[] messages,
int x, int y, int width, int height,
Consumer<MultiplesStrings> instructions) {
// ===== MAIN FRAME DEFINITION =====
this.setTitle(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(x, y, width, height);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(10, 10, 10, 10));
setContentPane(contentPane);
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
// contentPane.setBackground(Colours.newColor("DDDDDD"));
// ===== INTERACTION FRAME DEFINITION =====
this.interaction = new JPanel[messages.length];
this.text = new JLabel[messages.length];
this.insertText = new JTextField[messages.length];
for(int i=0 ; i<messages.length ; i++)
{
interaction[i] = new JPanel();
interaction[i].setLayout(new BoxLayout(interaction[i], BoxLayout.LINE_AXIS));
interaction[i].setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
interaction[i].add(Box.createHorizontalGlue());
// ===== TEXT =====
text[i] = new JLabel(messages[i]);
text[i].setAlignmentY(RIGHT_ALIGNMENT);
// text.setBounds(0, imageResolution + margin, Width, buttonHeight);
interaction[i].add(text[i]);
// ===== INSERT TEXT FIELD =====
insertText[i] = new JTextField();
// this.insertTextField.setBounds(Width + margin, imageResolution + margin, moveWidth, buttonHeight);
insertText[i].setColumns(10);
interaction[i].add(insertText[i]);
this.add(interaction[i]);
}
// ===== SUBMIT BUTTON DEFINITION =====
this.button = new JButton("Submit");
// Button behavior
MultiplesStrings support = this;
button.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) { }
} );
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
instructions.accept(support);
// support.setVisible(false);
}
} );
this.getRootPane().setDefaultButton(button);
this.add(button);
}
// =========================================================
// TODO | Input-output manipulation
/** Acquires all {#link String}s written by the user in the {#link JTextField}s used for {#code interactions}. */
public String[] acquireInputs() {
String[] output = new String[interaction.length];
for(int i=0 ; i<output.length ; i++)
output[i] = insertText[i].getText();
return output;
}
// =========================================================
// TODO | Main
public static final int width = 300;
public static final int height = 500;
private static String[] input;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() { public void run() {
try {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double screenWidth = screenSize.getWidth();
double screenHeight = screenSize.getHeight();
// Creates a centered form
MultiplesStrings ms = new MultiplesStrings("Test",
new String[] { "Insert first string: ", "Insert second string: ", "Insert third string: "},
(int) (screenWidth-width)/2, (int) (screenHeight-height)/2, width, height,
(MultiplesStrings obj) ->
{
input = obj.acquireInputs();
for(int i=0 ; i<input.length ; i++)
System.out.println("The " + i + "-th input is: " + input[i]);
}
);
ms.setVisible(true);
} catch (Exception e) { e.printStackTrace(); }
}
});
}
}
This is because BoxLayout uses the whole space of the container. With other words, it stretches all components to take the advantage of the total available space (since you use PAGE_AXIS, it refers to available height).
One of the solutions is to use a BorderLayout as an outside container and add this BoxLayout-ed panel inside at, with BorderLayout.PAGE_START constraints. PAGE_START constraints refers as "Hey you BoxLayout, there is no available space for you". Take a look at this example:
public class BoxLayoutSample extends JFrame {
public BoxLayoutSample() {
super("");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
contentPane.add(new JTextField(15));
contentPane.add(new JTextField(15));
setLocationByPlatform(true);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new BoxLayoutSample().setVisible(true));
}
}
It gives us:
This is what you have by now.
But if you use an outside BorderLayout-ed panel:
public class BoxLayoutSample extends JFrame {
public BoxLayoutSample() {
super("");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = getContentPane(); //This is the outer panel
contentPane.setLayout(new BorderLayout());
JPanel boxLayoutPanel = new JPanel(); //This is the nested panel
boxLayoutPanel.setLayout(new BoxLayout(boxLayoutPanel, BoxLayout.Y_AXIS));
//Components to nested panel
boxLayoutPanel.add(new JTextField(15));
boxLayoutPanel.add(new JTextField(15));
//PAGE_START to wrap it on the top
contentPane.add(boxLayoutPanel, BorderLayout.PAGE_START);
setLocationByPlatform(true);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new BoxLayoutSample().setVisible(true));
}
}
You get:
Also, calling setBounds method to a component will be ignored if it contains a layout. In order to see setBounds effect you must container.setLayout(null) since the layout is responsible for the component's bounds. However, THIS IS NOT RECOMMENDED. INSTEAD USE LAYOUT MANAGERS. Let them work for you.
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);
}
Code is underneath. Basically what I'm trying to do is I have display going on in my JPanel of a JTextPane. I have a button that edits the value of the string that's supposed to be displayed in the JTextPane. I can't figure out how to update the JTextPane however. I've tried revalidate(), validate(), repaint(), none of those seemed to work.
The code is complete, it should be able to run.
import java.awt.Canvas;
public class windowBuild extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private int health = 20;
private int energy = 4;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
windowBuild frame = new windowBuild();
frame.setVisible(true);
}
});
}
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String which = e.getActionCommand();
if (which.equals("Claw")){
energy = energy-1;
System.out.println("Player one's dragon clawed the opponent. Dragon's energy is now at: "+ energy);}
else if (which.equals("Wait")){
System.out.println("Turn succesfully skipped");}
System.out.println(getEnergy());
}
}
public windowBuild() {
ButtonHandler bh;
System.out.println("Starting frame...");
bh = new ButtonHandler();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new TitledBorder(null, "Dragon Duel",
TitledBorder.CENTER, TitledBorder.TOP, null, Color.CYAN));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnClaw = new JButton("Claw");
btnClaw.setBounds(288, 511, 109, 39);
contentPane.add(btnClaw);
btnClaw.addActionListener(bh);
if (energy == 0)
btnClaw.setEnabled(false);
JButton btnWait = new JButton("Wait");
btnWait.setBounds(645, 511, 109, 39);
contentPane.add(btnWait);
btnWait.addActionListener(bh);
StringBuilder sb = new StringBuilder();
String strB = Integer.toString(health);
sb.append("H: ").append(strB).append("/20");
String healthString = sb.toString();
JTextPane txtpnH_1 = new JTextPane();
txtpnH_1.setEditable(false);
txtpnH_1.setFont(new Font("Impact", Font.PLAIN, 30));
txtpnH_1.setText(healthString);
txtpnH_1.setBounds(134, 511, 109, 39);
contentPane.add(txtpnH_1);
String strR = Integer.toString(energy);
String energyString = "E: ";
energyString += strR;
energyString += "/4";
JTextPane txtpnH = new JTextPane();
txtpnH.setEditable(false);
txtpnH.setText(energyString);
txtpnH.setFont(new Font("Impact", Font.PLAIN, 30));
txtpnH.setBounds(39, 511, 85, 39);
contentPane.add(txtpnH);
}
}
Thanks so much!!
Take the time to read through the Code Conventions for the Java Programming Language
Make use of appropriate layout managers, see A Visual Guide to Layout Managers and Using Layout Managers for more details
For what it's worth, use JTextField instead JTextPane, you're gaining little to no benefit by using JTextPane for what you seem to be trying to achieve. In fact, you might actually be better of us just using JLabel, seen as you don't want them to be editable
Avoid overriding top level containers, like JFrame, instead start with something like JPanel, build your UI on it and then deploy it to what ever top level container you want.
The problem you have is a reference issue. In the constructor of your windowBuild, you are defining all your UI components. This means that there is no way you can reference them anywhere else from with your program. Instead, make those components you need to reference else where instance fields.
public class WindowBuild extends JFrame {
//...//
private JTextPane txtpnH_1;
private JTextPane txtpnH;
//...//
public WindowBuild() {
//...//
txtpnH_1 = new JTextPane();
//...//
txtpnH = new JTextPane();
//...//
}
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String which = e.getActionCommand();
// Now you can use txtpnH_1.setText and txtpnH.setText
}
}
I'm attempting to implement a changelistener on a JSlider. I've tried two separate methods neither has worked. The commented out section is the first attempt. The one that's implemented now would probably be the better suited for my purposes. Can anyone point out what is going wrong with this:
public class MixWindow extends JFrame implements ChangeListener{
private JPanel contentPane;
public static int uniA [] = new int [512];
ChangeListener sizeAction;
int level = 0;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MixWindow frame = new MixWindow();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
initUni();
}
public MixWindow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JSlider slider = new JSlider(0,255);
slider.setOrientation(SwingConstants.VERTICAL);
slider.setBounds(66, 275, 72, 140);
slider.setPaintTicks(true);
slider.setMajorTickSpacing(20);
slider.setValue(uniA[0]);
//slider.addChangeListener(sizeAction);
contentPane.add(slider);
final JLabel label = new JLabel("");
label.setBounds(66, 262, 61, 16);
contentPane.add(label);
/*sizeAction=new ChangeListener()
{
public void stateChanged (ChangeEvent event)
{
System.out.println("This is getting silly");
JSlider slider=(JSlider)event.getSource();
level=slider.getValue();
uniA[0] = level;
String temp = String.valueOf(level);
label.setText(temp);
}
};*/
}
public static void initUni(){
for(int i = 0; i < uniA.length; i++){
uniA[i] = 0;
}
}
#Override
public void stateChanged(ChangeEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Stuff has changed");
Object source = arg0.getSource();
System.out.println(arg0 + " has Changed");
}
}
The reason the ChangeListener isn't working in your 1st approach, is that your listener reference sizeAction is null when you register the listener.
slider.addChangeListener(sizeAction);
While this won't throw an exception, it won't register the listener when it is instantiated.
Simply alllow this line to appear after you define the listener and it will start working.
If you wish to use your other ChangeListener implementation instead you can use:
slider.addChangeListener(this);
hi i have two frames created in the same way:
public class DateFilter extends JFrame {
private final JDateChooser dateChooser = new JDateChooser();
private final JDateChooser dateChooser_1 = new JDateChooser();
private final JComboBox comboBox = new JComboBox();
private final JButton filtruotiButton = new JButton();
public DateFilter() {
super();
setBounds(100, 100, 277, 167);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
jbInit();
} catch (Throwable e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
getContentPane().setLayout(null);
setTitle("Priemimo datos filtras");
setResizable(false);
getContentPane().add(dateChooser);
dateChooser.setBounds(70, 40, 117, 20);
getContentPane().add(dateChooser_1);
dateChooser_1.setBounds(70, 65, 117, 20);
dateChooser_1.setEnabled(false);
...
tell me plz someone how to get data from one to another frame
for example if i want to place date from this frame's dateChooser to another frame's textField using button
You will need to pass the instance of the first frame to the second and than call a method on this instance.
Little sample code:
public class FrameA extends JFrame {
public void setSomeDate() {
}
}
public class FrameB extends JFrame {
public void doSomething() {
FrameA frameA = new FrameA();
frameA.setSomeDate();
}
}
Since I guessed that you are a beginner, I answered with this pretty simple and basic example. A more sophisticated way would be using the MVC pattern, of course!