How add JPanel in Frame - java

In my question, this is Refectoring Class. In this class, i'm using JPanel for adding button by a separate Method panel() and Call in the RefectClass Constactor.
public class RefectClass extends JFrame {
JButton btnHome,btnBack;
JPanel btnContainer;
public RefectClass(){
super("Title Here");
setSize(350,300);
add(this.panel(),BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void panel(){
btnContainer=new JPanel();
btnHome=new JButton("Home");
btnBack=new JButton("Back");
btnContainer.add(btnHome);
btnContainer.add(btnBack);
}
}
Now how to add panel to JFrame? it gives an error, when i try to use it. I'm unable use to the panel() Mehtod.

Your panel() method returns void - it should return your newly created JPanel instead such that you can add it to the JFrame:
public JPanel panel(){
btnContainer=new JPanel();
btnHome=new JButton("Home");
btnBack=new JButton("Back");
btnContainer.add(btnHome);
btnContainer.add(btnBack);
return btnContainer;
}
Let me point out, though, that this is a very unusual approach. You shouldn't have to initialize a member in a public method that returns the newly initialized member when the method is actually just needed inside the class. Imagine a client calling the panel method multiple times from outside (since it is public). BtnContainer, btnHOme and BtnBack would be overriden but they wouldn't appear on the screen.
The method seems fairy simply - why not just include it directly in your constructor?
Or at least make the method private.

Your panel() method doesn't return anything so you can't write
add(this.panel(),BorderLayout.CENTER);
try
this.panel();
add(this.btnContainer,BorderLayout.CENTER);

Related

Why is JPanel not adding any component at Runtime?

public class Create_JFrame extends JFrame{
public Create_JFrame(){
//Create a Frame
JFrame Frame = new JFrame("Bla-Bla");
JPanel Panel_1 = new JPanel();
JPanel Panel_2 = new JPanel();
JButton Option_1 = new JButton("Option-1");
//Layout management for Panels
Frame.getContentPane().add(BorderLayout.WEST, Panel_1);
//Add button to Panel
Panel_1.add(Option_1);
//Registering Listeners for all my buttons
Option_1.addActionListener(new ListenerForRadioButton(Panel_2));
//Make the frame visible
Frame.setSize(500, 300);
Frame.setVisible(true);
}//end of Main
}//end of Class
public class ListenerForRadioButton implements ActionListener{
JPanel Panel_2;
JButton browse = new JButton("Browse");
//Constructor, will be used to get parameters from Parent methods
public ListenerForRadioButton(JPanel Panel){
Panel_2 = Panel;
}
//Overridden function, will be used for calling my 'core code' when user clicks on button.
public void actionPerformed(ActionEvent event){
Panel_2.add(browse);
System.out.println("My listener is called");
}//end of method
}//end of class
Problem Statement:
I have 2 JPanel components in a a given JFrame. Panel_1 is having a Option_1 JButton. When user clicks on that I am expecting my code to add a JButton 'browse' in Panel_2 at runtime.
Runtime Output:
System is not adding any JButton in Panel_2. However, I see my debug message in output, indicating that system was successful in identifying user's click action on 'option-1'.
Question:
Why is JPanel not adding any component at Runtime?
Panel_2.add(browse);
Panel_2.revalidate();
adding a 'revalidate' will solve the problem.
There are some reasons. but:
usually it's because of using unsuitable LayoutManager.
sometimes it's because of adding the JPanel to it's root component in worng way. which any operation (add, remove,...) works but is not visible.
you must refresh the view when you make some changes on it, like adding or removing components to/from it.
try to use Panel_2.revalidate() to refresh.
if it doesn't work properly use it with Panel_2.repaint() method.
see Java Swing revalidate() vs repaint()
see Difference between validate(), revalidate() and invalidate() in Swing GUI
using setSize twice for your jframe is another way.
Frame.setSize(498, 300); then Frame.setSize(500, 300);

My buttons wont appear until i hover over it with my mouse

i have this problem and yes i saw that other people had the problem to but i not realy able to compare there code to mine and see the problem that way so i hope u can help me.
i use intellij to write my code and use there gui desinger to make gui's but when i added a button i didnt get it to display untill i hover it with a mouse and the possitions are wrong and i cant realy get it to work. here are the classes
// this is the jpanel class
public class paintMenu extends JPanel{
public JPanel menuPanel;
public JButton newGameButt;
public JButton loadGameButt;
public JButton helpbutt;
public JButton optionsButt;
public JButton info;
public JButton quitButt;
public paintMenu(){
add(newGameButt);
add(loadGameButt);
add(helpbutt);
add(info);
add(optionsButt);
add(quitButt);
setVisible(true);
}
//this is de jframe class
public class jframepainter extends JFrame {
paintMenu menupaint = new paintMenu();
public jframepainter(){
//main frame settings
setTitle("Kingdom V " + Reference.version);
setSize(Reference.width, Reference.height);
setResizable(false);
setLocationRelativeTo(null);
setVisible(Kingdom.vissible);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//draw jpnael
getContentPane().add(menupaint);
}
Try setting the JFrame to visible after you add your JPanel to it. Also you may want to call this.pack() after you add your JPanel.
//main frame settings
setTitle("Kingdom V " + Reference.version);
setSize(Reference.width, Reference.height);
setResizable(false);
setLocationRelativeTo(null);
//draw jpnael
getContentPane().add(menupaint); //Moved this before setting Visible
this.pack(); // call pack before setting visible
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(Kingdom.vissible);
I don't know what the Kingdom class is, but i can assume that vissible is a typo and may be causing a compile-time error. You didn't clearly describe your problem.

Java Swing: Access panel components from another class

Hi i basically have two classes,
one main and one just to separate the panels, just for code readability really.
i have :
public class Main{
public static void main (String args[]) {
JFrame mainJFrame;
mainJFrame = new JFrame();
//some other code here
CenterPanel centerPanel = new CenterPanel();
centerPanel.renderPanel();
mainFrame.add(centerPanel.getGUI());
}
}
class CenterPanel{
JPanel center = new JPanel();
public void renderPanel(){
JButton enterButton = new JButton("enter");
JButton exitButton = new JButton("exit");
center.add(exitButton);
center.add(enterButton);
}
public JComponent getGUI(){
return center;
}
}
Above code works perfectly. It renders the centerPanel which contains the buttons enter and exit. My question is:
I still need to manipulate the buttons in the main, like change color, add some action listener and the likes. But i cannot access them anymore in the main because technically they are from a different class, and therefore in the main, centerPanel is another object.
How do I access the buttons and use it (sets, actionlisteners, etc)? even if they came from another class and i still wish to use it inside the main?Many Thanks!
Make the buttons members of CenterPanel
class CenterPanel{
JPanel center = new JPanel();
JButton enterButton;
JButton exitButton;
public void renderPanel(){
enterButton = new JButton("enter");
exitButton = new JButton("exit");
center.add(exitButton);
center.add(enterButton);
}
public JButton getEnterButton()
{
return enterButton;
}
public JButton getExitButton()
{
return exitButton;
}
public JComponent getGUI(){
return center;
}
}
You have reference to centerPanel in your main method. After you invoke centerPanel.renderPanel();
the buttons will be added to the 'center' reference of type JPanel in CenterPanel instance. You can get the reference of 'center' by invoking centerPanel.getGUI(); in main method.This will return the center reference of type JComponent. JComponent is a awt container.so, you can call center.getComponents(). This will return all the components in an array present in the JPanel. i.e. center reference. You can iterate them, get their type and do whatever you want.

How to switch JPanels from different classes

I have three classes one JFrame class and two JPanel classes. I have added the intial JPanel to the JFrame like so
public JFrame() {
add(new 1stPanel(this));
setVisible(true);
setLayout(null);
}
Then i want to use an actionlistener on a button in the 1st panel to remove it and add the other panel which is in another class. I tried giving each class a variable and using the simple remove() and add() like this:
private 1stpanel 1p;
private 2ndpanel 2p;
btn.addActionListener((new ActionListener(){
public void actionPerformed(ActionEvent e)
{
remove(1p);
add(2p);
validate();
repaint();
}
}));
that doesn't work i have also tried using JFrame.remove(1p) but that doesn't work either. When i do removeAll() it gets rid of everything in the 1stpanel JPanel but then i can't add the 2ndpanel.
What code can i use to take out the 1st panel or 1stpanel class and add the 2nd panel which is in another class.
Thanks for the help in advance.
Try to use CardLayout and swap cards (panels).
Could be you problem is the creation add(new 1stPanel(this)). You add a local variable but then use fields of class.
your code lines
remove(1p);
add(2p);
validate();
repaint();
which you are calling inside the action listener are being called on the this object which I suspect is the JPanel itself. If it is so define a method in the class that is extending the JFrame, place these codes inside that method, and on action event call that method.

how to call active frame that already exist from another class that extends JDialog then remove all of its component?

I have class main extends jframe, it has a button that calls /shows another class that extends jdialog.
If the button from jdialog is triggered, it will dispose that dialog and will remove all component of jframe, then add it to a new jpanel.
What should I do?
Here's my new broken code:
public class mainz extends JFrame{
mainz(){
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JToolBar r = new JToolBar();
r.add(Box.createHorizontalGlue());
add(r, BorderLayout.NORTH);
JButton n = new JButton();
r.add(n, BorderLayout.EAST);
n.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
show();
}
});
}
public void show(){
dialogz d = new dialogz(this);
d.setVisible(true);
}
public void lastHope(){
getContentPane().removeAll();
getContentPane().validate();
getContentPane().repaint();
}
public static void main (String[]args){
new mainz().setExtendedState(MAXIMIZED_BOTH);
}
}
public class dialogz extends JDialog{
public dialogz(final mainz owner) {
setSize(300, 300);
JButton n = new JButton("execute");
add(n);
final JFrame ew = (JFrame)super.getOwner();// <<
n.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
dispose();
//owner.lastHope;
ew.removeAll();// <<
ew.validate();// <<
ew.repaint();// <<
}
});
}
void yes(){
getOwner().removeAll();
getOwner().validate();
getOwner().repaint();
}
}
I know I can prevent my main class from extending jframe, and call it from main instead, but I want to do it like that...
Please help me ... T-T
Sorry for my English, I from a far away country ~,~"
update:
the error is
java.lang.ClassCastException: javax.swing.SwingUtilities$SharedOwnerFrame cannot be cast to javax.swing.JFrame
it will be done with delete the line that contain
// <<
then call lastHope();
but i think there's a another way to get that existing jframe to removeall
(by casting it first or something ~,~" )
You are calling getParent() but you never set the parent (or owner). That should happen in the constructor as already pointed out. Also, be mindful that getParent() returns a Container object and getOwner() returns a Window object. Both of these refer to the JFrame which is the parent and owner. If you want to use it as a JFrame, you'll have to cast the output as (JFrame). But removeAll() is in Container class so if that's all you want, there'll be no need for casting.
Update:
JFrame frame = new JFrame();
JDialog dialog = new JDialog(frame);//frame is owner
JFrame parentOfDialog = (JFrame)(dialog.getParent());
//OR
//JFrame parentOfDialog = (JFrame)(dialog.getOwner());
parentOfDialog.removeAll();
If you are using your custom class, pass JFrame in the constructor and call super.
Please read the javadoc on JDialog before you try to use it. Also, read more about inheritance.
I'm not clear on what your goal is, but if you want to change the components that are displayed in a container, such as a JFrame or JDialog's contentPane, then I recommend that you use a CardLayout to do this since it allows you to easily swap "views".
There could be two ways to do this:
Your JDialog class could use a reference to the JFrame that is passed in via its constructor (and you should then pass it immediately into the dialog's super constructor so that your modality will work correctly). You could then call any public methods in the JFrame's class.
Or since the JDialog is modal, the JFrame's code will halt while the dialog is visible. You could swap "views" immediately after the dialog has been disposed of and is no longer visible. this would keep the JFrame manipulating code in the JFrame class.
Edit: note that if you don't use CardLayout, then you're responsible for calling revalidate() and repaint() on any container who gets its components changed.
As an aside: since English is not your first tongue and nor is it the native language of many folks on this forum, please avoid using non-standard abbreviations. The clearer your communication with us, the easier it will be for us to understand you and help you.

Categories