could not remove/add jpanel in jframe - java

I'm stuck with an issue that is, I have a JFrame with 2 JPanels added in it as showed in Figure :
in figure above, one JPanel have some JButtons and second JPanel have some form fields, I want to change/(remove old and add new JPanel) when I click on JButtons in first JPanel accordingly as shown bellow :
I have code snippet :
myPanel.clickListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
MainFrame.this.getContentPane().remove(((BorderLayout)getLayout()).getLayoutComponent(BorderLayout.CENTER));
MainFrame.this.getContentPane().add(twoPanel, BorderLayout.CENTER);
MainFrame.this.invalidate();
MainFrame.this.validate();
}
});
myPanel.clickListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
MainFrame.this.getContentPane().remove(((BorderLayout)getLayout()).getLayoutComponent(BorderLayout.CENTER));
MainFrame.this.getContentPane().add(customerPanel, BorderLayout.CENTER);
MainFrame.this.invalidate();
MainFrame.this.validate();
}
});
MainFrame.this.setMaximumSize(new Dimension(600, 550));
MainFrame.this.setMinimumSize(new Dimension(599, 549));
MainFrame.this.setSize(600, 550);
MainFrame.this.setResizable(false);
MainFrame.this.setVisible(true);
}
});
through above code I'm able to add new JPanel but unable to remove first JPanel.

in my opinion you should use CardLayout.
It allows you to change visibility of JPanel, so that is actually what you want to do.
You define two JPanels for the right side and then in listner just toggle them.
Look here for the example:
https://docs.oracle.com/javase/tutorial/uiswing/layout/card.html

Related

Toggling between screens using setVisible(boolean) in Swing

I have created a simple game in Swing which has a screen. Clicking on a cell results in color change of two adjacent cells. This is achieved by this code:
public class SelfGrid extends BattleGrid {
#Override
protected JPanel getCell()
{
JPanel panel = new JPanel();
panel.setBackground(Color.black);
panel.setBorder(BorderFactory.createLineBorder(Color.blue, 1));
panel.setPreferredSize(new Dimension(20, 20));
panel.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e)
{
panel.setSize(new Dimension(20,80));
panel.setBackground(Color.orange);
}
}
});
return panel;
}
}
public abstract class Battle extends JPanel {
public BattleGrid() {
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel grid = new JPanel();
grid.setLayout(new GridLayout(0,10));
JPanel panel = new JPanel();
panel = getCell();
grid.add(panel);
}
}
this.add(grid);
}
protected abstract JPanel getCell();
}
When I use setVisible(boolean) method to toggle between two screens and the original screen is brought back, only the cells that were clicked on remain colored. In other words, the dimension of each JPanel is restored to 20,20. I was told that this is because setVisible() method actually repaints components on the screen. How can I bring back the original screen without any changes being made to it contents? Thank you.
Instead of making programatic color changes directly to the UI elements, create a two dimensional array that represents the colors of the cells, and modify that. Then, repaint the cells based off the values in the array each time visibility changes or a cell is clicked.

JPopupMenu gets closed as soon as the mouse enters in an embedded JCheckboxMenuItem

I wrote the following code to have a JPopupMenu that allows multiple selection of different items.
The problem is that, as soon as the mouse enters one of the displayed JCheckboxMenuItems, the JPopupMenu gets closed. This issue doesn't occur if I replace JCheckboxMenuItem with, for example, JLabel but, for sure, JLabel doesn't work for my purpose.
Any idea of what could trigger this issue? Any idea of how this problem can be resolved in a better way? I apologize for the newbie question but I'm not a java developer. Thanks in advance for any help.
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedborder(),"Select Layers");
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
for (MyAction layer : layers) {
JCheckBoxMenuItem box = new JCheckBoxMenuItem(layer);
box.setIcon(new SquareIcon(myColor));
panel.add(box);
}
JPopup popup = new JidePopup();
popup.add(panel)
JButton button = new JButton("Layers");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
popup.show(button,0,button.getHeight())
}
});
Thats in the nature of JPopupMenus. They disappear when the invoker component loses the focus. But I found a little trick here.
Create your own class and extend it from JPopupMenu. Then override the setVisible method that it will only forward true to the super class and create an own method that will setVisible of the super class to false.
public class StayOpenPopup extends JPopupMenu{
public void setVisible(boolean visible){
if(visible == true)
super.setVisible(visible);
}
public void disappear() {
super.setVisible(false);
}
}
Then use it like this in your code
[...]
StayOpenPopup popup = new StayOpenPopup();
popup.add(panel);
[...]
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(popup.isVisible())
popup.disappear();
else popup.show(button,0,button.getHeight());
}
});
Now one click on button will show it. And it will stay visible until next click on Button.

Resize window when adding Swing components

I have a JFrame which consists of some Swing components. One button has an ActionListener to add an extra button to the frame (so the user can add more information).
Now I want the window (jframe) to resize whenever a new component is added. Now the components get smaller whenever a new one is added, but the frame stays the same size.
Here is the code of the actionlistener:
addAnswerButtonMA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
answerFieldsMA.add(new JTextField());
checkBoxesMA.add(new JCheckBox());
multipleanswerPanel.add(answerFieldsMA.get(answerFieldsMA.size() - 1));
multipleanswerPanel.add(checkBoxesMA.get(checkBoxesMA.size() - 1));
multipleanswerPanel.revalidate();
validate();
}
});
Some background (not sure if needed):
I'm making a quiz program, the administrator can add questions to the quiz by using a separate gui. If he wants to add a Multiple-answer question, he can add an extra answer by clicking the addAnswerbuttonMA to make an extra field and checkbox appear. The field represents the answer and the checkbox represents whether the answer is correct or not.
Packing the frame solves it.
addAnswerButtonMA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
answerFieldsMA.add(new JTextField());
checkBoxesMA.add(new JCheckBox());
multipleanswerPanel.add(answerFieldsMA.get(answerFieldsMA.size() - 1));
multipleanswerPanel.add(checkBoxesMA.get(checkBoxesMA.size() - 1));
multipleanswerPanel.revalidate();
validate();
pack()
}
});

Clicking a JLabel to open a new frame

I am designing the graphics for a game i am programming, i wanted to know if there is an easy way of opening a frame when a JLabel is cliked?
Is there easy code for this?
Implement MouseListener interface and use it mouseClicked method to handle the clicks on the JLabel.
label.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
// you can open a new frame here as
// i have assumed you have declared "frame" as instance variable
frame = new JFrame("new frame");
frame.setVisible(true);
}
});
create a label and add click event in it .
Something like this :
JLabel click=new JLabel("Click me");
click.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
JFrame jf=new JFrame("new one");
jf.setBackground(Color.BLACK);
jf.setSize(new Dimension(200,70));
jf.setVisible(true);
jf.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
});
don't to create a new JFrame, never bunch of JFrames, have to calculating with OutOfMemoryException, because this Object never will be GC'ed,
for multiple of views to use CardLayout
see answer The Use of Multiple JFrames, Good/Bad Practice? by #Andrew Thompson
You could do that like this:
label.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e)
{
JPanel j = new JPanel();
frame.setContentPane(j);
}
});
1:- Implement your class containing the JLabel with MouseListener interface
2:- add MouseListener to your JLabel
3:-Override mouseClicked Event in your class
4:- In mouseClicked Even't body add your code to open a new JFrame/Frame .

adding components in applet

I am making an applet and as part of my applet, I want this to happen: When the user presses "OK", the old components (some radio buttons) are removed, and a new JPanel is added, with a bunch of textfields.
However, I cannot figure out how to add a new component to the applet after it has started. I made the problem simpler by ignoring the removal part (Which I know how to do) and just adding a simple JLabel instead, but even that won't add!
Here is my code so far:
// imports omitted
public class Class extends Applet implements ActionListener
{
Button okButton;
CheckboxGroup radioGroup;
Checkbox radio1;
Checkbox radio2;
Checkbox radio3;
JLabel j;
public void init()
{
setLayout(new FlowLayout());
okButton = new Button("OK");
j = new JLabel("hello");
radioGroup = new CheckboxGroup();
radio1 = new Checkbox("Red", radioGroup,false);
radio2 = new Checkbox("Blue", radioGroup,true);
radio3 = new Checkbox("Green", radioGroup,false);
add(okButton);
add(radio1);
add(radio2);
add(radio3);
okButton.addActionListener(this);
}
public void repaint(Graphics g)
{
if (radio1.getState()) add(j);
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == okButton) repaint();
}
}
What am I doing wrong?
You shouldn't override the repaint method, and certainly not add a component in this method. Just remove the radio buttons from the applet (using its remove method) and add the label in the applet in your actionPerformed method, the same way you add them in the init method.
You might have to call validate after.
Add components and then call validate() of your container. In this case yourApplet.validate(). This will trigger repainting and rearranging of all elements.
you could do something like
JFrame fr= new JFrame(); // global variables
JPanel panelToBeAdded = new JPanel();
JPanel initialPanel = new JPanel();
JTextField fieldToBeAdded = new JTextField();
panelToBeAdded.setPreferredSize( new Dimension(400,400));
initialPanel.setPreferredSize( new Dimension(400,400));
initialPanel.setVisible(true);
fr.add(initialPanel);
fr.setVisible(true);
fr.pack();
public void actionPerformed(ActionEvent ae) {
initialPanel.setVisible(false);
//radiobuttons.setVisible(false);---> hide the radio buttons
panelToBeAddedd.add(fieldToBeAddedd);
panelToBeAddedd.setVisible(true);
fr.add(panelToBeAddedd);
}
public void repaint( Graphics g ) {
// do something
}
What am I doing wrong?
Your repaint(Graphics) method is not the same method you are calling in your actionPerformed method.
Also, repaint is a pretty bad name for a method which is adding a new component.
public void swapComponents()
{
if (radio1.getState()) {
remove(radio1);
remove(radio2);
remove(radio3);
add(j);
validate();
}
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == okButton) {
swapComponents();
}
}
When the user presses "OK", the old components (some radio buttons) are removed, and a new JPanel is added, with a bunch of textfields.
Use a CardLayout, as shown here. It is perfect for situations like this.

Categories