JFrame whose content changes as we click on the different buttons - java

I am using Java's Swing here to make a UI application. I have a created a JFrame, with some buttons. When I click on this button, I want a new JFrame with some different content at this place. However, I do not want a new JFrame to load here.
One approach, I know is of setting the visbility of the second JFrame to be True in the actionPerformed(ActionEvent obj) method of the button in the first JFrame. But it again loads a new JFrame and I don't want that.
public class FirstUI extends JFrame {
JButton but1;
public FirstUI(){
but1= new JButton("Click here");
add(but1);
XYZ obj= new XYZ():
but1.addActionListener(obj);
}
public class XYZ implements ActionListener{
public void actionPerformed(ActionEvent obj1){
// WHAT TO DO HERE
}
}
}
I only want a single JFrame whose content changes as we click on different buttons. How can I achieve that ?

Have a look at CardLayout, this would allow to switch the content of your frame:
A CardLayout object is a layout manager for a container. It treats each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards. The first component added to a CardLayout object is the visible component when the container is first displayed.
See How to Use CardLayout for an example.

You can also dynamically manipulate the contents of your JFrame at runtime. You can use add(...), remove(...), removeAll(...) methods to add and remove the contents as you do before showing the frame. After you're done you need to call revalidate() and repaint() methods of the modified container to make everything settle down and displayed properly.
However I think the right solution depends on the actual concept you are trying to implement. If you want to add or remove a couple of GUI elements to emphasize a functionality, then the correct way is to manipulate the container as I outlined. But if you want slightly different GUI depending on system state (not more then 2-3) then CardLayout would be a better suited choice

You can set visibility of parent class false.
Then you get only one Frame at a time with your required content.
You have to create static object of the frame and setVisible(fase) at the click event of the Button.
Ex.
public class demo {
static JFrame jf;
public static void main(String a[])
{
JButton b=new JButton("OK");
JPanel jp=new JPanel();
jf=new JFrame();
jf.setVisible(true);
jf.setSize(200,200);
jf.add(jp);
jp.add(b);
b.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e)
{
jf.setVisible(false);
JFrame f= new JFrame();
f.setSize(200,200);
f.setVisible(true);
}
});
}
}
It will help you.
you got my point?

One approach is to change the JFrame's Content Pane. which is basically a JPanel. You can do that byframe.setContentPane( <your new panel> );
The Second approach is to do what #Peter Lang did. and that is to use a Layout Manager which could change different content groups.

Related

Change instance of JPanel

i've created a JPanel with loaded components, called bkg, so I want to change it to SlideShow, that extends jpanel, and show it when i click on a button. this is the code called from the button:
public void startGame(){
bkg.removeAll();
bkg.revalidate();
bkg.repaint();
bkg = new SlideShow();
contentPane.add(bkg, BorderLayout.CENTER);
}
In the SlideShow constructor I've created some test labels, but when I click the button, all of old bkg components disappear (as I want) but nothing from SlideShow components I placed in the costructor appears... How can change the bkg JPanel to another external class that extends JPanel?
Suggestions:
Why remove/revalidate/repaint the bkg variable when you immediately replace the current object held by that variable with another?
What you want to revalidate and repaint is the contentPane after replacing the bkg object after adding it to the contentPane.
It's almost always better to use a CardLayout rather than manually swapping. The tutorial can be found here: CardLayout tutorial.
Or since it looks like you're re-starting a game, perhaps then give the SlideShow class a reset() method, one that sets both its model and its visible state to its original conditions.
So
public void startGame(){
// *** no need for this ***
// bkg.removeAll();
// bkg.revalidate();
// bkg.repaint();
bkg = new SlideShow();
contentPane.add(bkg, BorderLayout.CENTER);
// *** add this ***
contentPane.revalidate();
contentPane.repaint();
}
Or if you go the reset option, then the method would simplify to:
public void startGame(){
bkg.reset();
}
However that reset method would be key, the details depending on the structure of the rest of your program.

How to access JFrame's method from JDialog?

I have my main JFrame and one more JDialog.
If user click on the button, i want JDialog to call method from this JFrame(which contains some operations on ComboBox in this JFrame).
How can I do that?
I don't want to use MyJFrame form = new MyJFrame(); because it will make a new JFrame which i don't want to do, i want to call method from JFrame which is running currently on my computer.
Thanks.
Assuming the JButton is on the JDialog.
If both are in the same class, why not just do this?
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//I just got clicked
form.doSomething();
}
});
which can be shortened to
button.addActionListener(e -> form.doSomething());
If they aren't, and you're extending JDialog (which I wouldn't recommend) just pass the JFrame in its constructor, then your dialog will have access to it.
It's not possible to add much more without seeing more of your code.
Maybe JOptionPane.showInputDialog() , show a JDialog to take input from User.

Transitions between JPanel?

First of all... I'd like to say that I am not interested in using the card layout for this... Unless it's necessary (which means that not using the card layout would be result in unnecessary workarounds and complex code). This is for learning purposes after all and I will look into the card layout very soon enough anyway...
Okay so my question is pretty basic GUI layout I guess. My code is not working and this whole layouting confuses me quite a lot...
I'm having trouble how to make the transition between JPanels like this:
I have one window. I press a button, the old window is replaced by another window. I press a button and that window will be replaced by another window.
I'd like to add that I am skipping a lot of irrelevant code in my example below...
I start off with a JFrame:
public class StartWindow extends JFrame{
public StartWindow(){
//Add JButton & ActionListener
//When the button is pressed:
add(new NextWindow());
}
public static void main(String [] args){
new StartWindow();
}
}
then I have several JPanels...
public class NextWindow extends JPanel{
public NextWindow(){
//Add a JButton & ActionListener
//When the button is pressed:
add(new NextWindow2());
remove(this);
//This does not work. Nothing happens.
}
}
public class NextWindow2 extends JPanel{ // Stuff and so on}
So, I'd like to know a proper way to handle this situation!
You are adding a panel to itself. You need to remove the panel from the JFrame, add the new one to it, and call revalidate() on the JFrame.

How to execute an action on a component with a button of an external object?

It was hard to word the title for this one, but here's the explanation:
I have a menu bar that I'm adding as an external object from my MenuBar.java that extends JMenuBar to my main program file APP.java that extends JFrame.
MenuBar and a JPanel (which is in my main program file, APP.java) are added to the JFrame. How do I make buttons from the MenuBar perform actions on the JPanel.
Here's how my JMenuItem objects look like right now in MenuBar.java:
item = new JMenuItem("New);
item.setMnemonic(KeyEvent.VK_N);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
ActionEvent.ALT_MASK));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JLabel block = new JLabel();
block.setPreferredSize(new Dimension(120, 160));
//***This is where I run into a problem... I want to add this JLabel to my JPanel in
// the main file, and I also want to revalidate/repaint the JPanel to take show
// the new JPanels as they're added.....
}
});
file.add(item);
I'm not sure if I need to extend my APP to implement ActionListener.... but then I am not sure what to do afterwards.
EDIT:
Well, I was able to perform the intended action by making my content panel public and static, thus making it available without instantiating the APP object. And then I was able to implement this code into my actionPerormed methods in ActionListeners:
APP.content.add(new Thumb());
APP.content.validate();
Thumb() method creates a new JLabel;
Hopefully this won't mess up my stuff later on down the line, being that my content panel is static now.
This is hard to answer.
I would use setAction(Action) (indirectly). One can make an Action as child of AbstractAction, and an Action can hold its text, an icon, mnemonic key and more.
One typical usage is a JTextPane that provides a Action[] getActios() and those actions might be added to the menu bar or a JToolBar.
Please look up some code samples.
I leave it at this half of an answer.
An intro.
It would depend on what actions you want to perform, but the overall solution is the same. You need to pass a reference of the object of the object you want to work with to the menu class.
If you can, its better to pass a model of interace, limiting your actions to only performing work you really want them to

How do I make a button in a Java Applet that opens a JFrame?

I've made a few JFrames and I want to call them from a JApplet. What is the best way to do this? Could I just instantiate my JFrames in my init method and then call them whenever a button is pushed?
How do I make a button in a Java Applet that opens a JFrame?
You probably shouldn't do this, but rather if you want to open another window from the JApplet, create and show a JDialog. They are created and displayed similar to a JFrame, but uses different constructors. You will need to get the applet's Window for the "owner" parameter of the JDialog, and this can be obtained via:
Window w = (Window) SwingUtilities.getAncestorOfClass(Window.class, comp);
Where comp is a visible component in the JApplet.
Ok, it sounds like you initialize a JFrame on initialization and you store it. You don't need to re-instantiate the JFrame from initalization. Instead just store it in a field of your Applet and use it when ever the button is pressed.
OR you can use Singletons and lazy initialization:
class JFrameToOpen extends JFrame {
private static JFrame frame = null;
private JFrameToOpen() {
//init
}
public static GetJFrame() {
if(frame==null) {
frame=new JFrameToOpen();
}
return frame;
}
}
But singletons are ugly and many people choose to avoid them.
You can just create JFrame with its default constructor and then show it:
JFrame frame = new JFrame();
JLabel label = new JLabel("Welcome");
frame.add(label);
frame.pack();
frame.setVisible(true);
This code forks from the applet similar way as from the standalone program. No need for any special tricks. The applet itself then can only contain buttons like "press to launch the application".

Categories

Resources