Opening a static form/jFrame on clicking on button - java

I have two JFrames. The first one is defined as public firstJframe and the second one is defined as public static final jFrame. I want to open the second JFrame on clicking a button on the first JFrame. How can I do this?
.setVisible does not work for this. I really don't know how to proceed with this.

Try calling revalidate() for the object you want to update(in your case the second frame).
Example:
JButton myButton = new JButton("Open new window");
JFrame newFrame = new JFrame("New Window");
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newFrame.pack();
newFrame.setVisible(true);
newFrame.revalidate();
}
});
Update
If that does not work, try calling this:
newFrame.invalidate();
newFrame.validate();

I propose:
under the button type:
this.dispose
new public static final jFrame.setvisible(true);

Related

Add multiple actionListener to multiple JButtons

I am working on a GUI and trying to get different buttons to perform different tasks.
Currently, each button is leading to the same ActionListener.
public class GUIController {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(3,3));
JLabel leight =new JLabel("8");
frame.getContentPane().add(leight);
JLabel lfive =new JLabel("0");
frame.getContentPane().add(lfive);
JLabel lthree =new JLabel("0");
frame.getContentPane().add(lthree);
JButton beight =new JButton("Jug 8");
frame.getContentPane().add(beight);
JButton bfive =new JButton("Jug 5");
frame.getContentPane().add(bfive);
JButton bthree =new JButton("Jug 3");
frame.getContentPane().add(bthree);
LISTN ccal = new LISTN (leight,lfive,lthree);
beight.addActionListener(ccal);
bfive.addActionListener(ccal);
bthree.addActionListener(ccal);
frame.pack();
frame.setVisible(true);
}
}
my actionlistener file
public class JugPuzzleGUILISTN implements ActionListener {
JLabel leight;
JLabel lfive;
JLabel lthree;
JugPuzzleGUILISTN(JLabel leight,JLabel lfive, JLabel lthree){
this.leight = leight;
this.lfive = lfive;
this.lthree = lthree;
}
public void actionPerformed(ActionEvent e) {
}
}
}
Anything I write in ActionEvent applies to all three buttons, how can I make it so that each button has their own function?
Thank you so much!
how can I make it so that each button has their own function
Add a different ActionListener to each button.
Better yet, use an Action instead of an ActionListener. An Action is just a fancy ActionListener that has a few more properties.
Read the section from the Swing tutorial on How to Use Action for examples of defining inner classes so you can create a unique Action for each button.
Anything I write in ActionEvent applies to all three buttons, how can I make it so that each button has their own function?
You have similar actions which you want all the 3 buttons to be able to trigger. However you also have different functions which you want to implement for each button.
One of the ways will creating 3 more listeners, each to be added to their respective button. So each button now will be added with 2 listeners (your current one + newly created ones).
//Example:
beight.addActionListener(ccal);
bfive.addActionListener(ccal);
bthree.addActionListener(ccal);
beight.addActionListener(ccal_beight);
bfive.addActionListener(ccal_bfive);
bthree.addActionListener(ccal_bthree);
There are other ways such as using if-statements in your current listener to check which button is clicked, but I find separate listeners easier to maintain with lower code coupling.

How can I use Button to Close Frame and Open New Frame?

That's My Code Down Here. I want the answer for java.awt.Button and java.awt.Frame.
Can any one help me with it?
import java.awt.*;
import java.awt.event.*;
public class TestGUI extends Frame implements ActionListener, WindowListener{
private Label lbl;
private Label lbl1
private Label lbl2;
private Label lbl3;
private TextField tf;
private TextField tf1;
private TextField tf2;
private Button btn;
private Button btn1;
private Frame frame;
public TestGUI() {
setLayout(new FlowLayout());
lbl = new Label("Hi Guys! That's My First GUI Program and is made by me too");
add(lbl);
lbl1 = new Label("Enter Your Name Please ~");
add(lbl1);
tf1 = new TextField(30);
tf1.setEditable(true);
add(tf1);
lbl2 = new Label("Enter Your Age Please ~");
add(lbl2);
tf2 = new TextField(30);
tf2.setEditable(true);
add(tf2);
lbl3 = new Label("Enter Your School/College Name Please ~");
add(lbl3);
tf = new TextField(28);
tf.setEditable(true);
add(tf);
btn = new Button("Cancel");
add(btn);
btn.addActionListener(this);
addWindowListener(this);
setTitle("My own GUI");
setSize(500, 300);
setVisible(true);
}
public static void main(String[] args){
TestGUI app = new TestGUI();
}
#Override
public void actionPerformed(ActionEvent evt){
}
#Override
public void windowClosing(WindowEvent evt){
System.exit(0);
}
#Override public void windowDeactivated(WindowEvent evt){}
#Override public void windowActivated(WindowEvent evt){}
#Override public void windowOpened(WindowEvent evt){}
#Override public void windowClosed(WindowEvent evt){}
#Override public void windowIconified(WindowEvent evt){}
#Override public void windowDeiconified(WindowEvent evt){}
}
Thanks in Advance.
You're just complicating the things. Instead of extending the frame & implementing those interfaces, just extend JFrame.
public class TestGUI extends JFrame{...}
In your TestGUI frame create another JFrame say otherFrame and create two bottons say Open & Close and then bind ActionListener to them.
openBtn.addActionListener(new ActionListener(){
otherFrame.setVisible(true);
});
closeBtn.addActionListener(new ActionListener(){
otherFrame.setVisible(false);
});
The setVisible() method accepts boolean & this is what you actually need.
Much simpler & cleaner code.
It might make more sense for you to use a JFrame instead of a Frame (I recomend you read Kumar Vivek Mitra's answer here to get a better idea of why).
If you use a JFrame, you'll need to call yourJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) to stop your program when you close the window.
To respond to your button clicks, simply pass Anonymous Classes to your buttons addOnClickListener() method, like this:
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Do stuff here
}
});
Then you should be able to remove your existing actionPerformed() method.
For opening a new frame and closing your existing one, you should be creating two JFrame objects instead of extending Frame (or JFrame). Then, when you want to open your second frame, just call secondFrame.setVisable(true), and close your first one with firstFrame.dispose. However, I'd have a look at JDialogs and JOptionPanes first to see if they might work better for you.
After all this you should be able to remove all your WindowListener stuff, as that's for something slightly different. (Have a look here if you're interested)
Finally, don't forget to add a semicolon after your lbl1 label. ;)
Good luck!
You may use ActionListener interface.
However for a little addition to above guys commented. You may add animation to your frame by adding for loop and setSize method within the loop and the height width of the corresponding loop's variable.

adding to a textfield in panel1 from a button in panel2

Ok so I have 2 jPanels.
one of them has a number of buttons that when pressed should add text to the the textfield that is in the second jPanel.
I am brand spanking new to swing with previously only having to write back end code and web based code so I am having difficulty seeing how you would accomplish this.
I only have buttons created in one panel and a textfield in another so i suspect code would be irrelevant.
Any articles that someone could point me to or examples are greatly appreciated.
So I had this problem ones,
So Lets say you have two JFrame JFrame1 and JFrame2
In order to communicate with each other at runtime both has to have most recent initialized object of each individual frame.
Now lets say this is your first frame where is your textbox,
public class JFrame1 extends JFrame{
JTextField jTextField= null;
public JFrame1() throws HeadlessException {
super("JFrame");
setSize(200, 200);
jTextField = new JTextField();
add(jTextField);
setVisible(true);
}
public void setValueToText(String value){
jTextField.setText(value);
}
}
Then This is second and where is your Button,
public class JFrame2 extends JFrame{
JButton jButton= null;
JFrame1 frame1=null;
public JFrame2() throws HeadlessException {
super("JFrame");
frame1=new JFrame1();
jButton = new JButton("Clieck Me");
add(jButton);
setVisible(true);
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
frame1.setValueToText("Hi");
}
});
setVisible(true);
}
public static void main(String[] args) {
JFrame2 jf= new JFrame2();
jf.setSize(200, 200);
}
}
Now Just run second class file and click one button which will set hi on your textbox which is in second frame.
So As you see answer lay's in Initialized second object in frame.
My execution is like,
Run JFrame2
Initialized JFrame1 in JFame2 const.
you can make the JTextField an instance variable of the enclosing JFrame and make the two panels inner classes of it. By this, the two panels will have a reference to the same field which belongs to the outer class.
So, you will end up having something similar to:
public class Outer extends JFrame{
private JTextField text = new JTextField();
...
public Outer(){
this.add(new Inner1(), BorderLayout.NORTH);
this.add(new Inner2(), BorderLayout.SOUTH);
}
class Inner1 extends JPanel{
...
public Inner1(){
this.add(text);
}
}
class Inner2 extends JPanel implements ActionListener{
private JButton button = new JButton();
public Inner2(){
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == button)
text.setText("Hello StackOverFlow");
}
}
}
add your code to change the text in another panel, when a button clicked in the first panel.
mybutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//do your logic to change the text in another panel
}
});

How can I remove JButton from JFrame?

I want to remove JButton when user click JButton.
I know that I should use remove method, but it did not work.
How can I do this?
Here is my code:
class Game implements ActionListener {
JFrame gameFrame;
JButton tmpButton;
JLabel tmpLabel1, tmpLabel2, tmpLabel3, tmpLabel4;
public void actionPerformed(ActionEvent e) {
gameFrame.remove(tmpLabel1);
gameFrame.getContentPane().validate();
return;
}
Game(String title) {
gameFrame = new JFrame(title);
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setBounds(100, 100, 300, 500);
gameFrame.setResizable(false);
gameFrame.getContentPane().setLayout(null);
tmpLabel4 = new JLabel(new ImageIcon("./images/bomber.jpg"));
tmpLabel4.setSize(200, 200);
tmpLabel4.setLocation(50, 100);
tmpButton = new JButton("Play");
tmpButton.setSize(100, 50);
tmpButton.setLocation(100, 350);
tmpButton.addActionListener(this);
gameFrame.getContentPane().add(tmpLabel4);
gameFrame.getContentPane().add(tmpButton);
gameFrame.setVisible(true);
}
}
If hiding the button instead of removing works for your code then you can use:
public void actionPerformed(ActionEvent event){
tmpButton.setVisible(false);
}
for the button.But the button is just hidden not removed.
The simplest solution might be to...
Attach an ActionListener to the button, see How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners for more details
When the ActionListener is clicked, extract the source of the event, JButton buttonThatWasClicked = (JButton)actionEvent.getSource()
Remove it from it's parent...
For example...
Container parent = buttonThatWasClicked.getParent();
parent.remove(buttonThatWasClicked);
parent.revaidate();
parent.repaint();
As some ideas...
First of all in your actionPerformed method you need to check that the button is clicked or not. And if the button is clicked, remove it. Here's how :
if(e.getSource() == tmpButton){
gameFrame.getContentPane().remove(tmpButton);
}
add this to your actionPerformed Method
don't add your button to jframe but add each component you want!
public void actionPerformed(ActionEvent event)
{
//gameFrame.getContentPane().add(tmpButton); -=> "Commented Area"
gameFrame.getContentPane().validate();
}
or hide your button like this
public void actionPerformed(ActionEvent event)
{
tmpButton.setVisible(false);
}

Text in Label not displaying correctly with setText method

I'm trying to set the text in a label dynamically by calling the setText method whenever a button is clicked. Here is my code:
import java.awt.*;
import java.awt.event.*;
class Date {
public static void main(String[] args) {
new MainWindow();
}
}
class MainWindow {
static Label month = new Label();
static Label day = new Label();
static Button submit = new Button("Submit");
MainWindow() {
Frame myFrame = new Frame("Date Window");
myFrame.setLayout(new FlowLayout());
myFrame.add(month);
myFrame.add(day);
myFrame.add(submit);
submit.addActionListener(new ButtonListener());
myFrame.addWindowListener(new WindowListener());
myFrame.setSize(200, 200);
myFrame.setVisible(true);
}
}
class WindowListener extends WindowAdapter {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == MainWindow.submit) {
MainWindow.month.setText("12");
MainWindow.day.setText("31");
}
}
}
When I initialize the two Label objects without any arguments, the strings "12" and "31" that are passed to the setText method aren't visible on the screen when the submit button is clicked until I click on the window and drag to resize it. I've noticed this on a Mac only. On a PC, the strings are are visible but obscured until I resize the window. However, if I initialize the labels like this:
static Label month = new Label("0");
static Label day = new Label("0");
On the Mac, the strings appear as intended, however, they're obscured until the window is resized. What am I missing?
Calling validate() on the Frame as mentioned here solved the problem.
Try repainting the frame or/and set enough space(setPreferredSize, setMininumSize)
Well, most of your posting are over a year old so I'll give you the benefit of the doubt. I never use AWT so I don't know what the problem is, but I'll suggest:
1) Name you classes properly. "Date" is already a class in the JDK. Choose a better name.
2) Try using Swing components instead of AWT.
3) Get rid of static variables from your class.
4) Get rid of the WindowListener to close the frame.
The code example you posted here is 10-15 years old. Try something newer. Start with the Swing tutorial for more recent examples.

Categories