I want to make JDialog-based window inactive, so all controls apeared disabled (in grey color). setEnabled(false) just makes impossible to click any control, even close window. But nothing turns gray. Help please.
EDIT: Here is sample code.
import javax.swing.JButton;
import javax.swing.JDialog;
public class Analyzer extends JDialog{
public Analyzer() {
JButton but = new JButton("test");
setLayout(null);
but.setBounds(10,10,100,100);
add(but);
setSize( 200, 200);
setVisible(true);
setEnabled(false);
}
public static void main(String[] args) {
new Analyzer();
}
}
The two ways I know to do this, one where you disable the components of a dialog recursively, and the second where you disable the entire dialog (including ability to drag the dialog):
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class DisableEg extends JPanel {
public static final String DISABLE_DIALOG_COMPONENTS = "Disable Dialog Components";
public static final String ENABLE_DIALOG_COMPONENTS = "Enable Dialog Components";
public static final String DISABLE_DIALOG = "Disable Dialog";
public static final String ENABLE_DIALOG = "Enable Dialog";
private static final int LOC_SHIFT = 150;
private Analyzer analyzer;
public DisableEg(JFrame frame) {
analyzer = new Analyzer(frame);
analyzer.pack();
analyzer.setLocationRelativeTo(frame);
Point location = analyzer.getLocation();
location = new Point(location.x - LOC_SHIFT, location.y - LOC_SHIFT);
analyzer.setLocation(location);
analyzer.setVisible(true);
add(new JButton(new AbstractAction(DISABLE_DIALOG_COMPONENTS) {
#Override
public void actionPerformed(ActionEvent evt) {
AbstractButton btn = (AbstractButton) evt.getSource();
if (btn.getText().equals(DISABLE_DIALOG_COMPONENTS)) {
btn.setText(ENABLE_DIALOG_COMPONENTS);
analyzer.setComponentEnabled(false);
} else {
btn.setText(DISABLE_DIALOG_COMPONENTS);
analyzer.setComponentEnabled(true);
}
}
}));
add(new JButton(new AbstractAction(DISABLE_DIALOG) {
#Override
public void actionPerformed(ActionEvent evt) {
AbstractButton btn = (AbstractButton) evt.getSource();
if (btn.getText().equals(DISABLE_DIALOG)) {
btn.setText(ENABLE_DIALOG);
analyzer.setEnabled(false);
} else {
btn.setText(DISABLE_DIALOG);
analyzer.setEnabled(true);
}
}
}));
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Disable Example");
DisableEg mainPanel = new DisableEg(frame);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class Analyzer extends JDialog {
public Analyzer(JFrame frame) {
super(frame, "Analyzer Dialog", false);
JButton but = new JButton("test");
setLayout(new FlowLayout());
add(but);
setPreferredSize(new Dimension(200, 200));
}
public void setComponentEnabled(boolean enabled) {
setComponentEnabled(enabled, getContentPane());
// !! if you have menus to disable, you may need instead
// setComponentEnabled(enabled, this); // !!
}
private void setComponentEnabled(boolean enabled, Component component) {
component.setEnabled(enabled);
if (component instanceof Container) {
Component[] components = ((Container) component).getComponents();
if (components != null && components.length > 0) {
for (Component heldComponent : components) {
setComponentEnabled(enabled, heldComponent);
}
}
}
}
}
The typical way to do this is to use a glassPane, but Java 7 introduced JLayer that should do the trick too.
Related
I am new to Java Swing and I am trying to learn how to close one frame without closing the other one using button. For example I have a frame1/window that just have a button called login. Once I click on login button, another window appear frame2. On frame2 I just have a sample JLabel "Hello And Welcome", button called Logout. I want to be able to click on the Logout button on frame2 and frame2 window should close, but frame1 window show still be open. I have try setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE), but it only work if I click on the x icon on the top right of the frame2 window. Does anyone know of a way to close a frame when you click on a button?
public class Frame1 extends JFrame implements ActionListener{
private static JButton login = new JButton("Login");
private static JFrame f = new JFrame("Login");
Frame1(){
f.setSize(1000,750);
f.setLocation(750, 250);
login.setBounds(250, 350, 150, 30);
f.add(login);
f.setLayout(null);
f.setVisible(true);
login.addActionListener(this);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == login){
Frame2.frame2windown();
}
}
public static void main(String [] args){
Frame1 login1 = new Frame1();
}
}
public class Frame2 extends JFrame implements ActionListener{
private static JButton logout = new JButton("Logout");
private static JLabel jb1 = new JLabel ("Hello And Welcome");
private static JFrame f = new JFrame("Log Out");
Frame2(){
f.setSize(1000,750);
f.setLocation(750, 250);
jb1.setBounds(250, 150, 350, 30);
logout.setBounds(250, 350, 150, 30);
f.add(logout);
f.add(jb1);
f.setLayout(null);
f.setVisible(true);
logout.addActionListener(this);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void actionPerformed(ActionEvent a){
if(a.getSource() == logout){
dispose();
WindowEvent closeWindow = new WindowEvent(this, JFrame.DISPOSE_ON_CLOSE);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(closeWindow);
}
}
public static void frame2windown(){
Frame2 f2 = new Frame2();
}
}
So, there are a whole bunch of concepts your need to try and learn.
It's generally recommended NOT to extend from top level containers (like JFrame). You're not adding any new functionality too them; they are complicated, compound components; you lock yourself into a single use case (what happens if you want to include the UI in another UI or use a dialog instead of frame?!)
Multiple frames aren't always a good idea and can be confusing to the user. Generally, with login workflows though, I might argue a login dialog is generally a better solution, but you need to understand the use cases to make those determinations.
Swing is a large, rich and diverse API, it has a LOT of inbuilt functionality, which you can use, to make your life easier (although it doesn't always seem this way)
Layout managers are an absolutely required feature and you really need to take the time to learn them, see Laying Out Components Within a Container for more details.
So, a really quick example of using a CardLayout and a basic "observer pattern", which decouples and separates responsibility.
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.EventListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new NavigationPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class NavigationPane extends JPanel {
protected enum NavigationTarget {
LOGIN, MAIN;
}
private LoginPane loginPane;
private MainPane mainPane;
private CardLayout cardLayout;
public NavigationPane() {
cardLayout = new CardLayout();
setLayout(cardLayout);
loginPane = new LoginPane();
loginPane.addLoginListener(new LoginPane.LoginListener() {
#Override
public void loginDidFail(LoginPane source) {
JOptionPane.showMessageDialog(NavigationPane.this, "You are not unauthroised", "Error", JOptionPane.ERROR_MESSAGE);
}
#Override
public void loginWasSuccessful(LoginPane source) {
navigateTo(NavigationTarget.MAIN);
}
});
mainPane = new MainPane();
add(loginPane, NavigationTarget.LOGIN.name());
add(mainPane, NavigationTarget.MAIN.name());
navigateTo(NavigationTarget.LOGIN);
}
protected void navigateTo(NavigationTarget target) {
cardLayout.show(this, target.name());
}
}
public static class LoginPane extends JPanel {
public static interface LoginListener extends EventListener {
public void loginDidFail(LoginPane source);
public void loginWasSuccessful(LoginPane source);
}
public LoginPane() {
setBorder(new EmptyBorder(10, 10, 10, 10));
setLayout(new GridBagLayout());
JButton btn = new JButton("Login");
btn.addActionListener(new ActionListener() {
private Random rnd = new Random();
#Override
public void actionPerformed(ActionEvent e) {
// Do some logic here
if (rnd.nextBoolean()) {
fireLoginWasSuccessful();
} else {
fireLoginDidFail();
}
}
});
add(btn);
}
public void addLoginListener(LoginListener listener) {
listenerList.add(LoginListener.class, listener);
}
public void removeLoginListener(LoginListener listener) {
listenerList.remove(LoginListener.class, listener);
}
protected void fireLoginDidFail() {
LoginListener[] listeners = listenerList.getListeners(LoginListener.class);
for (LoginListener listener : listeners) {
listener.loginDidFail(this);
}
}
protected void fireLoginWasSuccessful() {
LoginListener[] listeners = listenerList.getListeners(LoginListener.class);
for (LoginListener listener : listeners) {
listener.loginWasSuccessful(this);
}
}
}
public static class MainPane extends JPanel {
public MainPane() {
setLayout(new GridBagLayout());
setBorder(new EmptyBorder(10, 10, 10, 10));
add(new JLabel("Welcome"));
}
}
}
JDialog based login workflow
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
NavigationPane navigationPane = new NavigationPane();
JFrame frame = new JFrame();
frame.add(navigationPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
if (LoginPane.showLoginDialog(navigationPane)) {
navigationPane.didLogin();
} else {
frame.dispose();
}
}
});
}
public static class NavigationPane extends JPanel {
protected enum NavigationTarget {
SPLASH, MAIN;
}
private SplashPane splashPane;
private MainPane mainPane;
private CardLayout cardLayout;
public NavigationPane() {
cardLayout = new CardLayout();
setLayout(cardLayout);
mainPane = new MainPane();
splashPane = new SplashPane();
add(splashPane, NavigationTarget.SPLASH.name());
add(mainPane, NavigationTarget.MAIN.name());
navigateTo(NavigationTarget.SPLASH);
}
protected void navigateTo(NavigationTarget target) {
cardLayout.show(this, target.name());
}
public void didLogin() {
navigateTo(NavigationTarget.MAIN);
}
}
public static class LoginPane extends JPanel {
private Random rnd = new Random();
private boolean isAuthorised = false;
public LoginPane() {
setBorder(new EmptyBorder(10, 10, 10, 10));
setLayout(new GridBagLayout());
add(new JLabel("User name and password fields go here"));
}
protected void authenticate() {
// Authenticate
isAuthorised = rnd.nextBoolean();
if (!isAuthorised) {
JOptionPane.showMessageDialog(this, "You are not authorised", "Error", JOptionPane.ERROR_MESSAGE);
}
}
// So this should return some kind of "session" or something so
// can identify the user, but for now, we'll just use
// a boolean
public boolean isAuthorised() {
return isAuthorised;
}
public static boolean showLoginDialog(Component parent) {
LoginPane loginPane = new LoginPane();
JPanel panel = new JPanel(new BorderLayout());
JPanel buttonPane = new JPanel(new GridBagLayout());
JButton okayButton = new JButton("Login");
JButton cancelButton = new JButton("Cancel");
buttonPane.add(okayButton);
buttonPane.add(cancelButton);
panel.add(loginPane);
panel.add(buttonPane, BorderLayout.SOUTH);
JDialog dialog = new JDialog(SwingUtilities.windowForComponent(parent));
dialog.add(panel);
okayButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
loginPane.authenticate();
if (loginPane.isAuthorised()) {
dialog.dispose();
}
}
});
cancelButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
dialog.setModal(true);
dialog.pack();
dialog.setLocationRelativeTo(parent);
dialog.setVisible(true);
return loginPane.isAuthorised();
}
}
public static class SplashPane extends JPanel {
public SplashPane() {
setLayout(new GridBagLayout());
setBorder(new EmptyBorder(10, 10, 10, 10));
add(new JLabel("This is a splash panel, put some nice graphics here"));
}
}
public static class MainPane extends JPanel {
public MainPane() {
setLayout(new GridBagLayout());
setBorder(new EmptyBorder(10, 10, 10, 10));
add(new JLabel("Welcome"));
}
}
}
You duplicated the JFrame, created a JFrame field f inside the JFrame.
Do not use static components like the button.
public class Frame1 extends JFrame implements ActionListener {
private final JButton login = new JButton("Login");
Frame1() {
setTitle("Login");
setSize(1000, 750);
setLocation(750, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
login.setBounds(250, 350, 150, 30);
add(login);
login.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == login) {
Frame2.frame2windown();
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
Frame1 login1 = new Frame1();
}
}
}
Use the swing/awt event queue (invokeLater) as on this thread window events are handled and dispatched further.
And Frame2:
public class Frame2 extends JFrame implements ActionListener {
private JButton logout = new JButton("Logout");
private JLabel jb1 = new JLabel("Hello And Welcome");
Frame2() {
setTitle("Logout");
setSize(1000, 750);
setLocation(750, 250);
setLayout(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jb1.setBounds(250, 150, 350, 30);
logout.setBounds(250, 350, 150, 30);
add(logout);
add(jb1);
logout.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent a) {
if (a.getSource() == logout) {
setVisible(false); // <--- ALL
}
}
public static void frame2windown() {
Frame2 f2 = new Frame2();
}
}
JFrame.setVisible does it all. Especially setVisible(true) should maybe even done after the constructor is called, so it always is last.
Another remark, dive into layout managers fast. Absolute layouts (null) are a PITA.
I have a button. I want to change the background after I click on it. My problem here is the button auto call paintComponent(). How can prevent this? I expect after clicking the button the button will be blue, but it will still be red.
package test;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonDemo extends JButton implements ActionListener{
public ButtonDemo() {
this.setText("BUTTON TEXT");
this.addActionListener(this);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.RED);
}
public static void main(String[] args){
JFrame frame = new JFrame();
JPanel contentPane = new JPanel();
frame.setContentPane(contentPane);
contentPane.add(new ButtonDemo());
frame.setSize(500, 500);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
this.setBackground(Color.BLUE);
}
}
My personal gut feeling is that JButton is probably not suited to your desired goal.
Essentially, you want to control when and how the "selected" state of the piece is changed.
Personally, I would have some kind of controller which monitored the mouse events in some way (probably having the piece component delegate the event back to the controller) and some kind of model which control when pieces become selected, this would then notify the controller of the state change and it would make appropriate updates to the UI.
But that's a long process to setup. Instead, I'm demonstrating a simple concept where a component can be selected with the mouse, but only the controller can de-select. In this example, this will allow only a single piece to be selected
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridLayout(5, 5));
ChangeListener listener = new ChangeListener() {
private PiecePane selectedPiece;
#Override
public void stateChanged(ChangeEvent e) {
if (!(e.getSource() instanceof PiecePane)) { return; }
PiecePane piece = (PiecePane) e.getSource();
// Want to ignore events from the selected piece, as this
// might interfer with the changing of the pieces
if (selectedPiece == piece) { return; }
if (selectedPiece != null) {
selectedPiece.setSelecetd(false);
selectedPiece = null;
}
selectedPiece = piece;
}
};
for (int index = 0; index < 5 * 5; index++) {
PiecePane pane = new PiecePane();
pane.addChangeListener(listener);
add(pane);
}
}
}
public class PiecePane extends JPanel {
private boolean selecetd;
private Color selectedBackground;
private Color normalBackground;
private MouseListener mouseListener;
public PiecePane() {
setBorder(new LineBorder(Color.DARK_GRAY));
mouseListener = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
setSelecetd(true);
}
};
setNormalBackground(Color.BLUE);
setSelectedBackground(Color.RED);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(50, 50);
}
#Override
public void addNotify() {
super.addNotify();
addMouseListener(mouseListener);
}
#Override
public void removeNotify() {
super.removeNotify();
removeMouseListener(mouseListener);
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
public void removeChangeListener(ChangeListener listener) {
listenerList.remove(ChangeListener.class, listener);
}
protected void fireSelectionChanged() {
ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
if (listeners.length == 0) {
return;
}
ChangeEvent evt = new ChangeEvent(this);
for (int index = listeners.length - 1; index >= 0; index--) {
listeners[index].stateChanged(evt);
}
}
public boolean isSelected() {
return selecetd;
}
public void setSelecetd(boolean selecetd) {
if (selecetd == this.selecetd) { return; }
this.selecetd = selecetd;
updateSelectedState();
fireSelectionChanged();
}
public Color getSelectedBackground() {
return selectedBackground;
}
public void setSelectedBackground(Color selectedBackground) {
this.selectedBackground = selectedBackground;
updateSelectedState();
}
public Color getNormalBackground() {
return normalBackground;
}
public void setNormalBackground(Color normalBackground) {
this.normalBackground = normalBackground;
updateSelectedState();
}
protected void updateSelectedState() {
if (isSelected()) {
setBackground(getSelectedBackground());
} else {
setBackground(getNormalBackground());
}
}
}
}
I created a toggle button.
You set the primary color and the alternate color in the class constructor.
When you call the switchColors method, the JButton background changes from the primary color to the alternate color. When you call the switchColors method again, the JButton background changes from the alternate color to the primary color.
In the following example, I put the switchColors method in the actionListener so you can see the color change. Each time you left-click on the JButton, the background color changes.
You would call the switchColors method when you want the JButton background to change from blue to red, and again when you want the JButton background to change from red to blue. It's under your control.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ButtonDemo extends JButton
implements ActionListener {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Button Demo");
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
frame.setContentPane(contentPane);
contentPane.add(new ButtonDemo(Color.BLUE,
Color.RED));
frame.setSize(300, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
private boolean primaryBackground;
private Color primaryColor;
private Color alternateColor;
public ButtonDemo(Color primaryColor,
Color alternateColor) {
this.primaryColor = primaryColor;
this.alternateColor = alternateColor;
this.primaryBackground = true;
this.setText("BUTTON TEXT");
this.setBackground(primaryColor);
this.addActionListener(this);
}
public void switchColors() {
primaryBackground = !primaryBackground;
Color color = primaryBackground ? primaryColor :
alternateColor;
this.setBackground(color);
}
#Override
public void actionPerformed(ActionEvent e) {
switchColors();
}
}
If you want to change the background for a short while you can do it with swing Timer:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class ButtonDemo extends JButton implements ActionListener{
private static final int DELAY = 600; //milliseconds
private final Timer timer;
public ButtonDemo() {
this.setText("BUTTON TEXT");
this.addActionListener(this);
Color defaultCloor = getBackground();
timer = new Timer(DELAY, e-> setBackground(defaultCloor));
timer.setRepeats(false);
}
public static void main(String[] args){
JFrame frame = new JFrame();
JPanel contentPane = new JPanel();
frame.setContentPane(contentPane);
contentPane.add(new ButtonDemo());
frame.setSize(300, 200);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
timer.stop();
this.setBackground(Color.RED);
timer.start();
}
}
I came across problem of memory leak in Swing Application due to Swing Timer.
I have used Timer to display slideshow of images in Page1.
When I profiled the application, I noticed that when navigating to Page2, the Timer object, the Page1 object and any object within Page1 object were not Garbage Collected.
I came to know that stopping the Timer allows it to be garbage collected.
I was assuming that if any object is not being referenced, it is ready for garbage collection. But this assumption failed in this case.
The code below summarizes my application and does not have memory leak. To see memory leak, comment the line where I have called stopTimer method of Timer.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class TimerMemoryLeak {
public static void main(String[] args) {
TimerMemoryLeak timer = new TimerMemoryLeak();
timer.buildUI();
}
public void buildUI() {
showPanel1();
frame.setSize(600, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void showPanel1() {
Page1 page1 = new Page1();
if (currentPanel != null) {
pane.remove(((Page2) currentPanel).getPanel());
}
pane.add(page1.getPanel());
currentPanel = page1;
page1.startTimer();
page1.setNextAction(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
showPanel2();
}
});
pane.revalidate();
pane.repaint();
}
public void showPanel2() {
Page2 page2 = new Page2();
if (currentPanel != null) {
((Page1) currentPanel).stopTimer(); // Comment this for memory leak
pane.remove(((Page1) currentPanel).getPanel());
}
pane.add(page2.getPanel());
currentPanel = page2;
page2.setPreviousAction(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
showPanel1();
}
});
pane.revalidate();
pane.repaint();
}
private JFrame frame = new JFrame();
private Container pane = frame.getContentPane();
private Object currentPanel;
}
class Page1 {
public Page1() {
panel.add(title, BorderLayout.NORTH);
panel.add(textTimer);
panel.add(btnNext, BorderLayout.SOUTH);
}
public void setNextAction(ActionListener listener) {
btnNext.addActionListener(listener);
}
public JPanel getPanel() {
return panel;
}
public void startTimer() {
timer.setInitialDelay(0);
timer.start();
}
public void stopTimer() {
timer.stop();
}
private JPanel panel = new JPanel(new BorderLayout());
private JLabel title = new JLabel("Panel 1");
private JButton btnNext = new JButton("Next");
private JLabel textTimer = new JLabel();
private int timerInterval = 1000;
private ActionListener timerAction = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textTimer.setText(Math.random() + "");
}
};
private Timer timer = new Timer(timerInterval, timerAction);
}
class Page2 {
public Page2() {
panel.add(title, BorderLayout.NORTH);
panel.add(btnPrev, BorderLayout.SOUTH);
}
public void setPreviousAction(ActionListener listener) {
btnPrev.addActionListener(listener);
}
public JPanel getPanel() {
return panel;
}
private JPanel panel = new JPanel(new BorderLayout());
private JLabel title = new JLabel("Panel 2");
private JButton btnPrev = new JButton("Previous");
}
What could be the possible reason for this?
I profiled your example in an artificially small heap, as shown here. The profile showed the expected result: periodic garbage collection returns the used heap space to baseline, as shown here. Selecting page two for the last half of the profile resulted in smaller amplitude collections. Sampling memory showed that the Timer instance present on page one was collected promptly on page two; no instances proliferated. Some additional suggestions:
Construct and manipulate Swing GUI objects only on the event dispatch thread.
Consider using CardLayout to switch pages dynamically.
Comment [out] the line where I have called [the] stopTimer() method.
The same result prevails. Note that instances of Swing Timer "share the same, pre-existing timer thread." As the Timer runs, instances of the inner class DoPostEvent, appearing in the profiler with the name javax.swing.Timer$1, will accumulate transiently. They too will be collected, albeit eventually in a later phase of garbage collection. As suggested here, you can click the Perform GC button to effect a more aggressive collection. Click the Deltas button in the Sampler tab to see other instances that accumulate transiently in the course of executing the timer's ActionListener; click Perform GC again to see the effect.
Console:
$ jvisualvm &
$ java TimerMemoryLeak.java
$ java -Xms32m -Xmx32m TimerMemoryLeak
Code, as tested:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class TimerMemoryLeak {
public static void main(String[] args) {
TimerMemoryLeak timer = new TimerMemoryLeak();
timer.buildUI();
}
public void buildUI() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
showPanel1();
frame.setSize(600, 400);
frame.setVisible(true);
}
public void showPanel1() {
Page1 page1 = new Page1();
if (currentPanel != null) {
pane.remove(((Page2) currentPanel).getPanel());
}
pane.add(page1.getPanel());
currentPanel = page1;
page1.startTimer();
page1.setNextAction(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
showPanel2();
}
});
pane.revalidate();
pane.repaint();
}
public void showPanel2() {
Page2 page2 = new Page2();
if (currentPanel != null) {
((Page1) currentPanel).stopTimer();
pane.remove(((Page1) currentPanel).getPanel());
}
pane.add(page2.getPanel());
currentPanel = page2;
page2.setPreviousAction(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
showPanel1();
}
});
pane.revalidate();
pane.repaint();
}
private JFrame frame = new JFrame();
private Container pane = frame.getContentPane();
private Object currentPanel;
private static class Page1 {
public Page1() {
panel.add(title, BorderLayout.NORTH);
panel.add(textTimer);
panel.add(btnNext, BorderLayout.SOUTH);
}
public void setNextAction(ActionListener listener) {
btnNext.addActionListener(listener);
}
public JPanel getPanel() {
return panel;
}
public void startTimer() {
timer.setInitialDelay(0);
timer.start();
}
public void stopTimer() {
timer.stop();
}
private JPanel panel = new JPanel(new BorderLayout());
private JLabel title = new JLabel("Panel 1");
private JButton btnNext = new JButton("Next");
private JLabel textTimer = new JLabel();
private int timerInterval = 1000;
private ActionListener timerAction = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textTimer.setText(Math.random() + "");
}
};
private Timer timer = new Timer(timerInterval, timerAction);
}
private static class Page2 {
public Page2() {
panel.add(title, BorderLayout.NORTH);
panel.add(btnPrev, BorderLayout.SOUTH);
}
public void setPreviousAction(ActionListener listener) {
btnPrev.addActionListener(listener);
}
public JPanel getPanel() {
return panel;
}
private JPanel panel = new JPanel(new BorderLayout());
private JLabel title = new JLabel("Panel 2");
private JButton btnPrev = new JButton("Previous");
}
}
I want to display a normal JButton as disabled, without setting it to setEnabled(false)!
I just want to show that this button is not enabled, but if the user pushs the button it should call the actionlistener as normal.
So what I did is:
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class SwingTests {
private static void createWindow() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
MyButton button = new MyButton("Press");
button.setEnabled(false);
panel.add(button);
frame.add(panel);
frame.setSize(200, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createWindow();
}
});
}
}
class MyButton extends JButton {
private boolean enabled = false;
public MyButton(String text) {
super(text);
super.setEnabled(true);
}
#Override
protected void paintBorder(Graphics g) {
if (isEnabled())
super.paintBorder(g);
else
; // paint disabled button
}
#Override
protected void paintComponent(Graphics g) {
if (isEnabled())
super.paintComponent(g);
else
; // paint disabled button
}
#Override
public void setEnabled(boolean b) {
enabled = b;
}
#Override
public boolean isEnabled() {
return enabled;
}
}
I "just" need to know what to write in paintComponent(g) and paintBorder(g).
if it is disabled and a user pushs the button i display an alarm why this button is disabled!
If it looks disabled I am probably not going to push it in the first place. You could achieve this type of effect using tool tips.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
public class TestGUI {
public TestGUI() {
JFrame frame = new JFrame();
final JButton button = new JButton("Press Me");
final JToggleButton enable = new JToggleButton("Enable / Disable");
enable.setSelected(true);
button.setToolTipText("Enabled");
enable.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (enable.isSelected()) {
button.setEnabled(true);
button.setToolTipText("Enabled");
} else {
button.setEnabled(false);
button.setToolTipText("Not Enabled");
}
}
});
frame.add(button, BorderLayout.CENTER);
frame.add(enable, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TestGUI();
}
});
}
}
if it is disabled and a user pushs the button i display an alarm why this button is disabled!
Add a MouseListener to the button when it is disabled. Then you can handle the mouseClicked() event to display your "alarm".
I am using the following code:
class ButtonPanel extends JPanel implements ActionListener
{
public ButtonPanel()
{
yellowButton=new JButton("Yellow");
blueButton=new JButton("Blue");
redButton=new JButton("Red");
add(yellowButton);
add(blueButton);
add(redButton);
yellowButton.addActionListener(this);
blueButton.addActionListener(this);
redButton.addActionListener(this);
}
public void actionPerformed(ActionEvent evt)
{
Object source=evt.getSource();
Color color=getBackground();
if(source==yellowButton) color=Color.yellow;
else if (source==blueButton) color=Color.blue;
else if(source==redButton) color=Color.red;
setBackground(color);
repaint();
}
private JButton yellowButton;
private JButton blueButton;
private JButton redButton;
}
class ButtonFrame extends JFrame
{
public ButtonFrame()
{
setTitle("ButtonTest");
setSize(400,400);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
Container contentPane=getContentPane();
contentPane.add(new ButtonPanel());
}
}
public class ButtonTest
{
public static void main(String args[])
{
JFrame frame=new ButtonFrame();
frame.show();
}
}
In actionperformed() I want to modify my panel and add some more component, is there any way to do this?
Yes.
Just call add() for the panel and then revalidate() and repaint();
but in actionperformed() i want to modify my panel and want to add some more component... Is there any way to do this....
Yes, you can add the components to the JPanel or "this" via the add(...) method, and you'll need to call revalidate() and then sometimes repaint() (especially if you also remove components) on the JPanel (this). But before you do this, if you haven't already done so, I think that you'll want to read the tutorials on using the layout managers so you can add components that are well situated.
hmmm I hard to comment anything, there are lots of mistakes, please start with this code
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ButtonPanel extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton yellowButton;
private JButton blueButton;
private JButton redButton;
public ButtonPanel() {
yellowButton = new JButton("Yellow");
yellowButton.addActionListener(this);
blueButton = new JButton("Blue");
blueButton.addActionListener(this);
redButton = new JButton("Red");
redButton.addActionListener(this);
add(yellowButton);
add(blueButton);
add(redButton);
setPreferredSize(new Dimension(400, 400));
}
#Override
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
Color color = getBackground();
if (source == yellowButton) {
color = Color.yellow;
} else if (source == blueButton) {
color = Color.blue;
} else if (source == redButton) {
color = Color.red;
}
setBackground(color);
revalidate();
repaint();
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("ButtonTest");
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.add(new ButtonPanel());
frame.pack();
frame.setVisible(true);
}
});
}
}