First I have a GUI (gui1), when I press a button, a different GUI (gui2) is created. My question is: How I can get access to elements from gui2, using methods from gui1?
Example: When I press a button from gui1, I want to QuesHandText.setText(myVector[0]); QuesHandText is a JTextField from gui1 and myVector[0] a var from gui2. The result error message: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
When I press Ok from Gui2 , I want to setText for the JTextField on Gui1
http://img72.imageshack.us/img72/2822/36185233.png
//imports
public class Gui extends JFrame{
public JButton Simulate, Particular, Start, HandSelection;
public JTextField QuesHandText, FlopTurnRiverText, RezultatText;
public Gui g;
public Gui()
{
QuesHandText = new JTextField(4);
//instruct
ClassParticular handler1 = new ClassParticular();
Particular.addActionListener(handler1);
}
public Gui(String t)
{
//instruct
myVector[0]="some_string";
myVector[1]="some_string2";
}
public class ClassParticular implements ActionListener{
public void actionPerformed(ActionEvent event){
//instruc
HandSelection hs = new HandSelection();
HandSelection.addActionListener(hs);
StartClass hndlr = new StartClass();
Start.addActionListener(hndlr);
add(HandSelection);
add(Start);
}
}
public class HandSelection implements ActionListener{
public void actionPerformed(ActionEvent e){
g = new Gui("Hand selection");
g.setVisible(true);
g.setSize(1135,535);
g.setDefaultCloseOperation(HIDE_ON_CLOSE);
g.setResizable(false);
}
}
public class StartClass implements ActionListener{
public void actionPerformed(ActionEvent event){
QuesHandText.setText(myVector[0]); // THE PROBLEM IS HERE, I KNOW IT !!
}
}
}
You have two constructors of Gui.
public Gui()
And
public Gui(String t)
You have initialized QuesHandText in the first one, but not in the second one.
If you use the second one to initialize the Gui you are supposed to get a NullPointerException.
I think you should do this in constructors:
[Edited as suggested by Kleopetra]
public Gui(){
this("");
}
public Gui(String t){
//instruct (I am not sure what it means)
quesHandText = new JTextField(4);
classParticular handler1 = new ClassParticular();
particular.addActionListener(handler1);
myVector = new String[2]; // or some other size you need.
myVector[0]="some_string";
myVector[1]="some_string2";
}
1.your problem is
public class Gui extends Jframe{
that should be
public class Gui extends JFrame{
2.another problems are
public JButton Simulate, Particular, Start, HandSelection;
public JTextField QuesHandText, FlopTurnRiverText, RezultatText;
public Gui g;
remove JButton and JTextField because they are JComponents and API names
or declare JButton and JTextField correctly
.
public JButton myButton, ...
public JTextField myTextField, ...
3.don't extends JFrame create that as local variable
4.don't re_create a new GUI from ActionPerformed use CardLayout
Related
First I am a beginner in java. I'm making a window with small button and a label (with 0 in default position), when I click on the button the label will change to 1 and when I tap another click the button will be 2. But, I have an error in calling the method.
my code:
package prototype;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Prototype {
public static int count;
public static JLabel l;
public void Proto()
{
JFrame f = new JFrame();
JButton b = new JButton("click");
JLabel lo = new JLabel("0");
JPanel p = new JPanel();
f.setBounds(120,120,500,500);
b.addActionListener(new MyAction());
p.add(lo);
p.add(b);
f.getContentPane().add(p,BorderLayout.CENTER);
f.show();}
public class MyAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
count++;
l.setText(Integer.toString(count));}
public static void main(String[] args) {
//I want to call the proto method but it give me an eror
new proto();
}}}
public class Prototype extends JFrame{
private static int count;
private JLabel l;
public Prototype() {
super();
JButton b = new JButton("click");
l = new JLabel("0");
JPanel p = new JPanel();
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
count++;
l.setText(Integer.toString(count));
}
});
p.add(l);
p.add(b);
this.getContentPane().add(p, BorderLayout.CENTER);
this.pack();
this.setVisible(true);
}
public static void main(String...args){
Prototype p=new Prototype();
}
}
I changed the method to a constructor, to have the possibility of creating a object of type Prototype and directly create a frame with it. Also I extended the class with JFrame to not need to create an extra JFrame. Next step was to remove the ActionListener class and creating a new ActionListener while adding it to the button. In my eyes this is useful if you have several buttons with different functionalities, so you can see the function of the button directly just by looking at the code of the button. and the last step was to create a new Object of type Prototype in the main method
If I we're you use a SwingWorker instead of manually setting the text of JLabel. Because this is not a proper way updating your GUI. This should be done using SwingWorker. Please read about publish and processmethod.
I tried to create a dialog box with Jbutton but when I am adding actionListener to it and passing the class to button which i have created to implements ActionListener I am getting "PathakP(Class Name) cannot be resolved to a type"
the code I have used is
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class GUI1 extends JFrame {
private JTextField J;
private Font pf,bf,itf,bif;
private JRadioButton pb,bb,ib,bib;
private ButtonGroup B;
private JButton ab;
public GUI1(){
super("To check the Font styles" );
setLayout(new FlowLayout());
J=new JTextField("This is the Text who's Font will be Changed pahtak is with me ",40);
add(J);
pb=new JRadioButton("Plain Button",true);
bb=new JRadioButton("Bold Button",false);
bib=new JRadioButton("Bold & Italic Button",false);
ib=new JRadioButton("Italic Button",false);
ab=new JButton("PathakButton");
add(ab);
add(pb);
add(bb);
add(bib);
add(ib);
B=new ButtonGroup();
B.add(pb);
B.add(bb);
B.add(bib);
B.add(ib);
pf=new Font("Serif",Font.PLAIN,15);
bf=new Font("Serif",Font.BOLD,15);
itf=new Font("Serif",Font.ITALIC,15);
bif=new Font("Serif",Font.BOLD+Font.ITALIC,16);
J.setFont(pf);
pb.addItemListener(new HandlerClass(pf));
bb.addItemListener(new HandlerClass(bf));
bib.addItemListener(new HandlerClass(bif));
ib.addItemListener(new HandlerClass(itf));
ab.addActionListener(new PathakP());
}
private class HandlerClass implements ItemListener{
private Font font;
public HandlerClass(Font f){
font=f;
}
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
J.setFont(font);
}
private class PathakP implements ActionListener{
public void actionPerformed(ActionEvent ae) {
JOptionPane.showMessageDialog(null, "This is just JOptionPane example");
}
}
}
}
Main Class
import javax.swing.*;
public class Apples {
public static void main(String[] args) {
GUI1 G=new GUI1();
G.setVisible(true);
G.setSize(500,250);
G.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I don't believe there is any error in the main class
I can troubleshoot this error by just creating another class outside but I want to know why it is not taking the class I have created and show unused in it
Your PathakP is written inside of HandlerClass. You have two solutions from there (after having corrected your bracket problem)
Either write it inside of GUI instead and since you're calling it from the constructor, it will be binded to this instance of GUI
Or, if you want to keep it within HandlerClass, you need to bind it to an instance of HandlerClass : ab.addActionListener(new HandlerClass().new PathakP())
Ok, here is my problem. Class B is a class that build a GUI ,which has a textField and button. class A has an instance of class B.Now I enter some value in the textfield, when I click the button, in class A I want to print out the value I just enter in the textfield, how can I achieve that?
Code below may better explain what I want to achieve:
public class A
{
B myB = new B();
(when the JButton was clicked,
how can I get the new textfield value here?)
}
public class B
{
JLabel myLabel;
JButton myButton;
public B()
{
getContentPane().setLayout(null);
myLabel = new JLabel();
myLabel.setLocation(0,0);
myLabel.setSize(100,30);
myLabel.setBackground( new Color(-6710887) );
myLabel.setText("");
getContentPane().add(myLabel);
myButton = new JButton();
myButton.setLocation(0,50);
myButton.setSize(100,30);
myButton.setBackground( new Color(-16737895) );
myButton.setText("Submit");
getContentPane().add(myButton);
myButton.addActionListener(this);
setSize(400,400);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
(how can I pass this "myLabel.getText()" value to class A when
this action performed?)
}
}
Can anybody help me finish this little program? Thanks in advance!
You need to expose the value in text field with a method in class B. Then class A can call that method. What it actually sounds like though is that class A (or something else) should be a ActionListener for your button.
However, a bigger problem is that you don't have a text field you just have a label in class B. This code is a good reason why you shouldn't use a GUI builder, especially when learning Swing.
Some reading:
http://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html
http://docs.oracle.com/javase/tutorial/uiswing/events/
I often make an "App" class that ties all my GUI-builder-built components together. Any GUI builder worth anything lets you add getters to the generated source code. Add some getters to the GUI-built components to retrieve key elements of the GUI, then let the App class use the getters to interact with the components as necessary. This won't win any MVC/MVVM/MVP design awards, but it gets the job done, which ought to count for something.
public class App {
private B _b;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
App app = new App();
app.run();
}
});
}
void run() {
_b = new B();
_b.getMainButton().addActionListener(new MainButtonListener());
_b.setVisible(true);
}
private void handleMainButtonClicked() {
String mainText = _b.getMainTextArea().getText();
System.out.println("Button clicked; main text = " + mainText);
}
public class MainButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
handleMainButtonClicked();
}
}
}
public class B extends JFrame {
private JPanel _contentPane;
private JTextArea _jTextArea;
private JButton _jButton;
public B() {
initComponents();
}
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
_contentPane = new JPanel();
setContentPane(_contentPane);
_jTextArea = new JTextArea();
_contentPane.add(_jTextArea, BorderLayout.CENTER);
_jButton = new JButton("My Button");
_contentPane.add(_jButton, BorderLayout.SOUTH);
}
public JButton getMainButton() {
return _jButton;
}
public JTextComponent getMainTextArea() {
return _jTextArea;
}
}
I have an assignment where I have to click a button 1 in panel 1 and change the information on button 2 in panel 2, however I cannot figure out how to pass the information.
I thought I might be able to pass the information from method b() from panel2 back to one but that's not working.
I'm pretty stuck and don't know how to move forward with the program. Any help is appreciated.
Panel1
public class MyJPanel1 extends JPanel implements ActionListener {
Student st1 = new student("Fred","Fonseca",44);
JButton j = new JButton(st1.getInfo());
JButton b1 = new JButton("..");
public myJPanel1() {
super();
setBackground(Color.yellow);
// the whatsUp of this student has to shown in the other panel
j.addActionListener(this);
add(j);
}
public void actionPerformed(ActionEvent event) {
Object obj = event.getSource();
//=====================================
if (obj == j){
b1.setText(st1.whatsUp()); // Output on JButton in JPanel2
}
}
}
}
Panel2
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class myJPanel2 extends JPanel {
JButton j1 = new JButton("");
public void b(JButton b1) {
JButton j1 = b1;
}
public myJPanel2() {
super();
setBackground(Color.pink);
setLayout(new GridLayout(3,1));
add(j1);
// j1.setText(b1);
}
}
Create a method in MyJPanel2 which sets the text in JButton.
public class myJPanel2 extends JPanel {
JButton button = new JButton("");
...........
public void setButtonText(String text) {
button.setText(text);
}
}
In MyJPanel2, you need to store a reference of MyJPanel1. Then just call the setButtonText in the ActionListener
public class MyJPanel1 extends JPanel implements ActionListener {
private MyJPanel2 panel;
public MyJPanel1(MyJPanel2 panel) {
this.panel = panel;
}
public void actionPerformed(ActionEvent event) {
if (obj == j){
panel.setButtonText(yourText);
}
}
}
}
A couple things to keep in mind. Java is an Object Oriented language, meaning that you want define your Objects using Classes, and then reuse those objects as much as possible. If you have two panels, each one containing a button, then that is the perfect time to define the Class once
public class MyPanel extends JPanel{
protected JButton button;
public MyPanel(String buttonName){
button = new JButton(buttonName);
}
//etc etc etc
}
and then use the Class over and over
public class MyProgram {
protected MyPanel panel1;
protected MyPanel panel2;
public MyProgram(){
panel1 = new MyPanel("Button 1");
panel2 = new MyPanel("Button 2");
}
//etc etc
}
Now, once you have your program set up like this, it is very easy to communicate between the two panels, since in MyProgram you have both instances of your panels available.
So, lets say your MyPanel class had a method called setButtonText
public void setButtonText(String text){
button.setText(text);
}
You could call this method in your MyProgram in order to change the text on one of the buttons
myPanel1.setText("New Button 1 text");
But how do we know if the button in myPanel1 or myPanel2 was pushed? You can look into how Java uses ActionListener to communicate events between different objects.
Good luck!
If I write sea you don't have connected that two panels together. The best way to coonect them together is from thrid calass wher you declare this two clasess. And set this two classes eachOther.
Example:
class conecctor{
ClassA first;
ClassB secod;
public void init(){
{
first=new ClassA();
second=new ClassB();
first.setClasB(second);
second.setClasA(first);
}
}
class ClassA{
ClassB classB;
public void setClassB(ClassB classB){
this.classB=classB;
}
}
class ClassB{
ClassA classA;
public void setClassA(ClassA classA){
this.classA=classA;
}
}
And then when you have instances in each class you can call all public methods from evrywher.
Beter way is to create interface and just pass the interface (listener) steal you pass whole class if that clas implements interface but it its more clearly and other advatages.
I have a basic GUI class with a frame, a table, and a button. I want to make it launch from the ActionListener of another one of my basic GUI frames located in a different class
this is my main class:
public class IA {
public static void main(String[] args) {
MainFrame m1 = new MainFrame();
m1.setVisible(true);
} /*enter code here*/
public static void vts1 () {
ViewTeamStatistics v1 = new ViewTeamStatistics();
v1.setVisible(true);
}
}
It initiates my main menu and from the main menu i want to initiate another class named ViewTeamStatistics
this is the actionperformed. this is what is supposed to tell the program to open the frame after i press the button
private void vtsActionPerformed(java.awt.event.ActionEvent evt) {
ViewTeamStatistics v1 = new ViewTeamStatistics();
v1.setVisible(true);
}
The compiler comes back with no errors but when I run the program and press the button nothing happens.
I don't fully understand your question, do you want to launch a new frame upon pressing a button? If that's it here is a sample code :
public class ExampleWindow implements ActionListener{
private JFrame mainFrame;
private JButton button;
public ExampleWindow(){
button = new JButton("Press me!");
button.addActionListener(this);
mainFrame = new JFrame("Frame name");
mainFrame.add(button);
mainFrame.setVisible(true);
//Remember about this line
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
new SomeWindow();
}
}
class SomeWindow{
private JFrame frame;
public SomeWindow(){
frame = new JFrame;
frame.setVisible(true);
}
}
I didn't try to compile it so there might be some errors.