how to call compoment from another frame - java

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!

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.

Change button's text with an external combobox java

I've two class. Can i change a text of a button in a class "home" with an actionlistener of the combobox in a class "panelGestisciImpianti"? I don't unterstand becasue don't works.
The code is this:
//home
package s;
public class home extends JFrame {
private JPanel contentPane;
private panelImpostazioni panel5= new panelImpostazioni();
private JButton btnImpostazioni = new JButton("no"); //$NON-NLS-1$
public static void main(String[] args) {
home frame = new home();
frame.setVisible(true);
}
public home() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState( JFrame.MAXIMIZED_BOTH) ;
setBounds(0, 0, 1963, 688);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);
btnImpostazioni.setBounds(0, 560, 140, 140);
contentPane.add(btnImpostazioni);
btnImpostazioni.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.add(panel5);
revalidate();
repaint();
}
});
}
public void changetext() {
btnImpostazioni.setText("yes");
}
}
//panelGestisciImpostazioni
package s;
public class panelImpostazioni extends JPanel {
private JComboBox comboboxLingua = new JComboBox();
static home h=new home();
public panelImpostazioni() {
setBounds(140, 0, 800, 560);
setLayout(null);
comboboxLingua.setBounds(100, 24, 150, 45);
comboboxLingua.setModel(new DefaultComboBoxModel(new String[] {"italiano", "inglese"}));
add(comboboxLingua);
comboboxLingua.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
h.changetext();
}
});
}
}
Thank you.
Its because when you create panel5 you have a new home created.
static home h = new home ().
So when you call changetext method you do it in a new invisible frame.
In order to make this work (it is really really bad) you have to pass your visible "home" as an argument to your panel5. Which means you have to initiate it in home's constructor and not as a field.
public panelImpostazioni(home h)
And in your combobox action listener
h.changetext ()

A basic logic issue whilst using setters and getters with Swing

Im writing a basic program to simulate a conversation between a user and the computer. I am trying to use a setter and getter to change the text in a textField in another class. The button is clicked and nothing appears in the textField. here is my code:
public class DialogueWindow extends JFrame {
SuperDialogue SD = new SuperDialogue();
JTextField textField = new JTextField();
JButton Answer1 = new JButton();
public DialogueWindow() {
initUI();
}
public void initUI() {
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
JButton Answer1 = new JButton();
Answer1.setBounds(102, 149, 113, 30);
Answer1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
textField.setText(SD.getReply1());
}
});
panel.add(Answer1);
textField = new JTextField();
textField.setBounds(56, 74, 174, 45);
panel.add(textField);
setTitle("Dialogue");
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
public class SuperDialogue {
private String answer;
public String getReply1(){
return this.answer;
}
public void setReply1(String a1){
this.answer = a1;
}
}
public class Conversation1 extends SuperDialogue {
public void Convo(){
String firstLine = "hello";
setReply1(firstLine);
DialogueWindow DW = new DialogueWindow();
DW.setVisible(true);
DW.setSize(300,300);
}
}
public class Main {
public static void main(String[] args) {
Conversation1 c1 = new Conversation1();
c1.Convo();
}
}
The SuperDialogue in your JFrame class is not the same as the one created in your main.
SuperDialogue SD = new SuperDialogue();
This line is creating a separate SuperDialog which does not has the same values. This one is never set, so getReply1() returns nothing.

JTextPane not updating after values changed

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
}
}

activate event with a keypress

I am trying to find a sulotion to translate the void keypressed from c# to java without any succes yet anyone a sulotion?
I want when i press the key 13(enter) that Private void doen() activates once.
import java.awt.event.*;
import javax.swing.JTextField;
import javax.swing.*;
import java.awt.*;
import java.awt.Toolkit;
import java.util.Timer;
import java.util.TimerTask;
public class Paneel extends JPanel {
private static final long serialVersionUID = 1L;
String text;
String AccountName = "default";
String autosavecheck = "";
String iss;
JProgressBar monsterbar, progressbar;
JButton sendknop, clearknop, creditsknop, saveknop, loadknop, restartknop,
disableautosaveknop;
JTextArea commandstextbox, dialoogtextbox;
JTextField naamtextbox, invoertextbox;
JOptionPane resetdialog;
Toolkit toolkit;
Timer timer;
public Paneel() {
setLayout(null);
// --------------------------------
dialoogtextbox = new JTextArea();
dialoogtextbox.setFont(new Font("sansserif", Font.BOLD, 12));
dialoogtextbox.setBounds(12, 12, 838, 207);
dialoogtextbox.list();
invoertextbox = new JTextField(12);
invoertextbox.setBounds(12, 330, 982, 20);
invoertextbox.setEnabled(false);
commandstextbox = new JTextArea();
commandstextbox.setBounds(856, 28, 138, 191);
naamtextbox = new JTextField(12);
naamtextbox.setBounds(772, 263, 220, 20);
toolkit = Toolkit.getDefaultToolkit();
timer1 = new Timer();
toolkit = Toolkit.getDefaultToolkit();
autosave = new Timer();
toolkit = Toolkit.getDefaultToolkit();
monstertimer = new Timer();
toolkit = Toolkit.getDefaultToolkit();
autodisabletimer = new Timer();
sendknop = new JButton("Send");
sendknop.setBounds(12, 260, 75, 23);
sendknop.addActionListener(new sendknopHandler());
add(sendknop);
}
private void keypressed() {
if (e.KeyChar == (char) Keys.Return) {
doen();
}
}
private void doen() {
text = invoertextbox.getText();
invoertextbox.setText("");
}
}
Well if you want to call the method once a JButton is pressed you'd have to add an ActionListener to the JButton and call the method from within the actionPerformed(ActionEvent ae) like this:
jBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("called");
//call method here
}
});
or if you want to call the method once a key is pressed on the JPanel use KeyBindings instead of a KeyListener like so:
JPanel panel=...;
...
panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), "send");
panel.getActionMap().put("send", new MyAction());
...
class MyAction extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("called");
//call method here
}
}
As you can, there are a number of approaches you could try. You didn't really specify on which component you were interested in monitoring, so we've thrown a few different suggestions at you...
In the following example of demonstrated key bindings and the default button of the RootPane.
Unfortunately, the JTextArea consumes the enter key before the root pane is notified, meaning that it won't fire. This is a general issue with text fields as they respond to the enter key action.
The other problem you will face is the fact that I've overridden the default behavior of the JtextField's enter key, meaning it will no longer insert new lines.
public class TestPane extends JPanel {
private JTextArea textArea;
private JButton doneButton;
public TestPane() {
textArea = new JTextArea(10, 50);
doneButton = new JButton("Done");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(4, 4, 4, 4);
add(new JScrollPane(textArea), gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.insets = new Insets(4, 4, 4, 4);
add(doneButton, gbc);
InputMap inputMap = textArea.getInputMap(JComponent.WHEN_FOCUSED);
ActionMap actionMap = textArea.getActionMap();
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter");
actionMap.put("enter", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("I'm done here");
}
});
doneButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("All the way out...");
}
});
}
#Override
public void addNotify() {
super.addNotify();
// This is the button that will be activate by "default", depending on
// what that means for the individual platforms...
SwingUtilities.getRootPane(this).setDefaultButton(doneButton);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exp) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.setVisible(true);
}
});
}
}
First: get your formatting right, see the instructions for inserting code snippets. Helps those of us who read it :)
I am not entirely sure what you are asking here, but I guess you are trying to get your program to respond to a user clicking any of your buttons. This takes place in the various ActionListeners you should have for buttons. For example, in your case, the sendknopHandler should contain the logic to handle what happens when a user presses this specific button. Inside this class, you will have to filter out the source of the action (i.e. the button pressed), what the action is, and how you want to respond.
learn all about listeners and more specific key listeners
Is "key 13" a button or is it when user types "13"?
if it's a button, just use
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
your statements;
}
}
otherwise use the key listener Peter responded.
a) public Paneel() { missing } after code line add(sendknop);, the same issue is with public class Paneel extends JPanel {,
b) from this code and in this form you'll never listening any event because code isn't runnable, your question is about Java Basic, not about Swing GUI, nor about listener
c) for listening of ENTER key you have to add ActionListener to the JButton
d) for Swing GUI have to use Swing Timer instead of util.Timer, otherwise you have an issue with Concurency in Swing
e) for Swing GUI don't to use KeyListener, there is KeyBindings and with output to the Swing Action
f) otherwise Swing JComponents have got Focus in the Window for KeyListener
Add a key listener to your invoertextbox by adding the following lines to the initialization part of your code:
invoertextbox.addKeyListener(this);
Then extend your class implement the KeyListener interface by adding:
import java.awt.event.KeyListener;
public class Paneel extends JPanel implements KeyListener {
And implement the following methods of the interface within your Paneel class:
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER) {
doen();
}
}
#Override
public void keyReleased(KeyEvent e) {
}
private void doen() {
text = invoertextbox.getText();
invoertextbox.setText("");
}
Consider using keyTyped(KeyEvent) instead of keyPressed(KeyEvent).
"Key typed" events are higher-level and generally do not depend on the
platform or keyboard layout. They are generated when a Unicode
character is entered, and are the preferred way to find out about
character input. In the simplest case, a key typed event is produced
by a single key press (e.g., 'a') […] (JavaDoc for KeyEvent)

Categories