Java Removing/Adding JPanel - java

Currently I have a client that contains two panels... one is the main game and the other is a side panel containing tools. The side panel can be shown/hid (thus making the frame only show the game).
activateSidePanel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (sp) {
frame.remove(enhancedPanel);
frame.repaint();
frame.pack();
sp = false;
} else if (!sp) {
frame.add(enhancedPanel);
frame.repaint();
frame.pack();
sp = true;
}
}
});
That is my action listener for the button. The button hides correctly, however it doesn't show. When I click the button again it just makes the frame smaller and does not bring back the side panel. Confused on this one.

} else if (!sp) {
Why do test for !sp? A boolean can only have two values, so all you need is an if/else statement (without the test on the else.
Instead of removing/adding the panel I would try invoking the setVisible(false/true) method first.
If that doesn't work then then general code for removing/adding components is:
panel.add(...)
panel.revalidate();
panel.repaint();
You should not need to invoke pack() because you don't want the frame to keep resizing, you only want the main panel to become bigger/smaller.

Related

Pressing twice on a Jbutton

I am a beginner in GUI programming and I am working on a project with a different kind of button.
For one of my Jbutton, when pressed it calls another frame that performs a task.
However, that frame goes on the background when I am working on the main frame.
When you press again the button for the second time a null pointer error is generated.
I want to be able to just bring back the frame that is in the background when the button is pressed for the second time.
changecontrastB.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// calls the contrast adjuster function
ContrastAdjuster mycontrast= new ContrastAdjuster();
// running that function which brings that frame forward
mycontrast.run("Brightness/Contrast...");
mycontrast.setVisible(true);
if (changecontrastB.isSelected() && mycontrast.isVisible()==false )
{
changecontrastB.setEnabled(false);
mycontrast.setVisible(true);
}
}
});
changecontrastB is my actual Jbuton.
Do the following:
In the class with the button, create a member variable of type JFrame:
JFrame frame = null;
In the action listener called from the button, include an if like this (you need to adapt it to your class names):
if (frame = null)
frame = new MyFrame(); //Other initializations might be needed too.
else
frame.toFront();

Making JMenuItem show one JPanel and hide another

I'd like to be able to switch between two possible JPanels in my frame by selecting a certain JMenuItem. What I tried so far:
Action listener in my JMenuBar class:
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(fullList))
gui.switchToFullList();
else if (e.getSource().equals(history))
gui.switchToHistory();
}
In GUI class:
void switchToFullList() {
remove(history);
add(fullList);
}
void switchToHistory() {
remove(fullList);
add(history);
}
where history and fullList are JPanels.
This doesn't seem to modify my frame in any way.
If you want to show one Panel and hide another, they both should ba childreen of your Frame, then you can acces those Panels by: frame.JpanelName.
Example of removing history and adding fullList:
frame.remove(frame.history);
frame.getContentPane().add(frame.fullList);
frame.validate();
frame.repaint();

switching jpanels with menuItem inside Jframe

I want to know how can I switch JPanels inside my main JFrame, I have tried this code but when I click the menu item it changes then I click other menu item and does not change, I click the menu Item I clicked first and it changes ....is there other way I can easily switch jpanels? do not show me the cardLayout crap because it doesn't work with what i need and it seems that every answer on google involves that demo, anyway if there is a simple way of doing things I appreciate it if someone helps me point in the right direction thanks.
menuItem.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainPane.remove(getContentPane());
mainPane.add(cdPanel, BorderLayout.CENTER);
mainPane.validate();
}
});
there are two ways
remove (JFrame.getContentPane.removeAll()) and add JPanel to JFrame, required to call JFrame.(re)validate and JFrame.repaint after all changes to already visible Swing GUI is done, once time, last code lines
(better, correct, proper of ways) use CardLayout, code example in official Oracle tutorial, a few good, some excelent examples here
Edited Code:
public static void main(String[] args)
{
// TODO code application logic here
JFrame frame = new JFrame();
frame.setSize( 300, 300);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
JPanel panelOne = new JPanel();
panelOne.setBackground( Color.red );
JPanel panelTwo = new JPanel();
panelTwo.setBackground(Color.blue);
frame.setContentPane( panelOne );
frame.setVisible(true);
//This delay is just here so you can see the transition
try
{
Thread.sleep( 1000 );
}
catch ( InterruptedException ie )
{
ie.printStackTrace();
}
panelTwo.setSize( frame.getContentPane().getSize() );
frame.setContentPane( panelTwo );
}
I would like to point out that there is a class called JTabbedPane. It might not be what you're looking for, but it's essentially one pane, with multiple tabs on it that a user can click and switch views.
http://docs.oracle.com/javase/tutorial/uiswing/components/tabbedpane.html
http://docs.oracle.com/javase/6/docs/api/javax/swing/JTabbedPane.html

Killing all processes, force everything to stop

I have a game that runs off of JPanel which has on it many other things which have their own independent timers and such. It seems that when I try to remove the panel from my frame to replace it with another JPanel it refuses to actually end all of its own processes. So even if I am able to remove it from the screen of the panel by removing it and setting it null, its processes are still going off in the background, IE the music and the stuff flying around.
What i need to know is some solution as to how to completely kill this JPanel and terminate its life to its entirety.
Seems not many people have run into this problem.
I remember having that issue in my own game..
Simply create some custom method i.e destroy() which will stop all timers gameloops music etc.
i.e
MyPanel panel=new MyPanel();
...
panel.destory();//stop music, timers etc
frame.remove(panel);
//refresh frame to show changes
frame.revalidate();
frame.repaint();
where panel would be:
class MyPanel extends JPanel {
private Timer t1,t2...;
//this method will terminate the game i.e timers gameloop music etc
void destroy() {
t1.stop();
t2.stop();
}
}
Alternatively you could make your Swing Timers observers of sorts by making it check each time whether the panel is visible and if not it should stop executing. This would though now of course cause you to create a timer which will only start the others once the panel becomes visible:
class MyPanel extends JPanel {
private Timer t1,t2,startingTimer;
MyPanel() {
t1=new Timer(60,new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
if(!MyPanel.this.isVisible()) {//if the panel is not visible
((Timer)(ae.getSource())).stop();
}
}
});
startingTimer=new Timer(100,new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
if(MyPanel.this.isVisible()) {//if the panel is visible
t1.start();//start the timers
t2.start();
((Timer)(ae.getSource())).stop();//dont forget we must stop this timer now
}
}
});
startingTimer.start();//start the timer which will check when panel becomes visible and start the others as necessary
}
}
now all you would do is:
frame.remove(panel);//JPanel timers should also see panel is no more visible and timer will stop
//refresh frame to show changes
frame.revalidate();
frame.repaint();
Try this:
myFrame.getContentPane().remove(myPanel);
myFrame.validate();
Make sure your music and other components are within the panel so they are removed as well.

Closing a Window with Button

I am currently studying Java to improve myself. I have a program which has a main window, menu and submenus.
I have other windows on when I click on my submenus.
One of them is setRates which is
public SetMyRates(){
JPanel dataPanel = new JPanel(new GridLayout(2, 2, 12, 6));
dataPanel.add(setTLLabel);
dataPanel.add(setDollarsLabel);
dataPanel.add(setTLField);
dataPanel.add(setDollarsField);
JPanel buttonPanel = new JPanel();
buttonPanel.add(closeButton);
buttonPanel.add(setTLButton);
buttonPanel.add(setDollarsButton);
Container container = this.getContentPane();
container.add(dataPanel, BorderLayout.CENTER);
container.add(buttonPanel, BorderLayout.SOUTH);
setTLButton.addActionListener(new SetTL());
setDollarsButton.addActionListener(new SetDollars());
closeButton.addActionListener(new closeFrame());
dataPanel.setVisible(true);
pack();
}
and I want that window to close when I click on my closeButton.
I made a class for closeButton, actionListener which is:
private class closeFrame implements ActionListener{
public void actionPerformed(ActionEvent e){
try{
dispose();
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, "Please enter correct Rate.");
}
}
}
But when I click that button, it closes my main window instead of my submenus window. What should I exactly do to fix the problem?
You need to get a reference to the Window that you want to close and call dispose() directly on that reference. How you do this will depend on the details of your program -- information that we're currently not privy to.
Edit: one way to get that reference is via SwingUtilities.getWindowAncestor(...). Pass in the JButton reference returned from your ActionEvent object and call dispose on it. Something like...
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o instanceof JComponent) {
JComponent component = (JComponent)o;
Window win = SwingUtilities.getWindowAncestor(component);
win.dispose();
}
}
caveat: code neither compiled nor run nor tested in any way.
Also note that for this to work, the component that holds and activates the ActionListener has to reside on the Window that you wish to close, else this won't work.
From what I think you could easily when opening an another window just store a reference to it and use it inside the action listener. Something along these lines:
JFrame openedWindow;
//inside the listener
if(openedWindow)
openedWindow.dispose();
else dispose();

Categories

Resources