I'm quite new to java here , and right now i'm working on a program which involves the following actions. Lets say i have a 3 X 3 grid of JLabel. How do i load an ImageIcon and then move it from on label to another. For example, say each label is named as label_1 to label_9, and the imageicon is on label_2 . When i click on label_3,imageicon it should go to label_3
Very quick example which you can adapt to your needs.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Test extends JFrame {
public Test() {
JPanel container = new JPanel(new GridLayout(3, 3));
for (int i = 0; i < 9; i++) {
JLabel label = new JLabel("Label" + i);
label.setPreferredSize(new Dimension(100, 100));
label.setBorder(BorderFactory.createLineBorder(Color.black));
label.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
Icon icon = UIManager.getIcon("OptionPane.informationIcon");
JLabel clickedLabel = (JLabel) e.getSource();
Container parent = clickedLabel.getParent();
clearIcons(parent);
clickedLabel.setIcon(icon);
}
private void clearIcons(Container parent) {
Component[] components = parent.getComponents();
for (Component component : components) {
((JLabel) component).setIcon(null);
}
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
container.add(label);
}
add(container);
}
public static void main(String[] args) {
Test frame = new Test();
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
}
}
Result should be following:
Related
so I created a 2 JLabels which display an icon but now I want that if you click on of the JLabels it produces a text which is displayed on the JFrame. What I know is that you can add some kind of Listener, but the ActionListener doesnt work, so I searched more and came to the MouseListener but I don't understand the explanations and the projects are way more complicated to my. Everthing Im copy pasting is underlined in red.
void mouseClicked(MouseEvent e){}
So i came to this method and it looks kinda similar to the ActionListener method, but again, i dont know which correct Java class i should import or should i "classname implement MouseListener"?
import javax.swing.*;
import java.awt.*;
public class Main1{
public static void main(String[] args){
ImageIcon frameBG = new ImageIcon("res/bg.png");
ImageIcon dogIcon = new ImageIcon("res/dog.png");
ImageIcon catIcon = new ImageIcon("res/cat.png");
JLabel bgLabel = new JLabel();
JLabel dogLabel = new JLabel();
JLabel catLabel = new JLabel();
bgLabel.setBounds(0, 0, 400, 250);
bgLabel.setIcon(frameBG);
dogLabel.setBounds(50, 30, 150, 150);
dogLabel.setIcon(dogIcon);
catLabel.setBounds(210, 30, 150, 150);
catLabel.setIcon(catIcon);
JFrame frame = new JFrame("Cat and Dog Clicker");
frame.setSize(400, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(dogLabel);
frame.add(catLabel);
frame.add(bgLabel);
frame.setVisible(true);
}
}
You can try:
bgLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
bgLabel.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("click");
}
#Override
public void mousePressed(MouseEvent e) {
System.out.println("press");
}
#Override
public void mouseReleased(MouseEvent e) {
System.out.println("released");
}
#Override
public void mouseEntered(MouseEvent e) {
System.out.println("entered");
}
#Override
public void mouseExited(MouseEvent e) {
System.out.println("exit");
}});
Steffi
I'm currently trying to create a GUI for a game. I have a JFrame with a first panel with multiples button. After a click I'm supposed to change the panel. It works I created the first class which is a Frame
public class FirstWindow extends JFrame implements ActionListener
this class contains buttons which make us change panels. For this I created the panels in different classes which extends JPanel. It worked but I am blocked because once in the second panels I still have to refer to other panels but I no longer have access to my initial JFrame.
To illustrate: This is how I switch from different JPanel. The "this" refers to the frame which I can't use in the other class
public void actionPerformed(ActionEvent e) {
if ( "START".equals(e.getActionCommand())){
this.setContentPane(new PanelHello());
this.invalidate();
this.validate();
}else if ("EXIT".equals((e.getActionCommand()))) {
this.dispose();
this.invalidate();
this.validate();
}else if (!( usernameText.getText().equals(""))){
this.setContentPane(new PanelHello());
this.invalidate();
this.validate();public void actionPerformed(ActionEvent e) {
if ( "START".equals(e.getActionCommand())){
this.setContentPane(new PanelHello());
this.invalidate();
this.validate();
}else if ("EXIT".equals((e.getActionCommand()))) {
this.dispose();
this.invalidate();
this.validate();
}else if (!( usernameText.getText().equals(""))){
this.setContentPane(new PanelHello());
this.invalidate();
this.validate();
CardLayout
The CardLayout layout manager is an extremely useful layout manager, which can be used to switch between different containers.
For me, one of its limiting factors is the need to, generally, have every container you want to switch to, instantiated and added. This can make it "heavy", in terms of memory usage and difficult when it comes to passing information between panels - as its hard abstract the workflow, not impossible, just problematic.
One of the nice features, is till automatically determine the required size of the UI based all the other containers.
See How to Use CardLayout
Custom navigation
One of the things I often finding myself needing to do, is have some kind none-linear progression through the UI, and needing the ability to effectively pass information back and forward to different containers.
The can be accomplished through the use the delegation, observer pattern and dependency injection.
The basic principle here is, you might have a number of navigation controllers, each one managing a particular workflow, independently of all the others. This kind of separation simplifies the needs of the application and makes it easier to move things around, should the need to be, as any one workflow isn't coupled to another.
Another aspect, which isn't demonstrated here, is the ability to return information to the navigation controller, for example, if you have a login/register workflow, the workflow could end by returning an instance of the "user" to the controller which would then be able to make determinations about which workflow they needed to go through next (admin/moderator/basic/etc)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
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.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 MasterPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MasterPane extends JPanel {
private MenuPane menuPane;
public MasterPane() {
setLayout(new BorderLayout());
presentMenu();
}
protected void presentMenu() {
removeAll();
if (menuPane == null) {
menuPane = new MenuPane(new MenuPane.NavigationListener() {
#Override
public void presentRedPane(MenuPane source) {
RedPane redPane = new RedPane(new ReturnNavigationListener<RedPane>() {
#Override
public void returnFrom(RedPane source) {
presentMenu();
}
});
present(redPane);
}
#Override
public void presentGreenPane(MenuPane source) {
GreenPane greenPane = new GreenPane(new ReturnNavigationListener<GreenPane>() {
#Override
public void returnFrom(GreenPane source) {
presentMenu();
}
});
present(greenPane);
}
#Override
public void presentBluePane(MenuPane source) {
BluePane bluePane = new BluePane(new ReturnNavigationListener<BluePane>() {
#Override
public void returnFrom(BluePane source) {
presentMenu();
}
});
present(bluePane);
}
});
}
add(menuPane);
revalidate();
repaint();
}
protected void present(JPanel panel) {
removeAll();
add(panel);
revalidate();
repaint();
}
}
public class MenuPane extends JPanel {
public static interface NavigationListener {
public void presentRedPane(MenuPane source);
public void presentGreenPane(MenuPane source);
public void presentBluePane(MenuPane source);
}
private NavigationListener navigationListener;
public MenuPane(NavigationListener navigationListener) {
this.navigationListener = navigationListener;
setBorder(new EmptyBorder(16, 16, 16, 16));
setLayout(new GridBagLayout());
JButton red = new JButton("Red");
red.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getNavigationListener().presentRedPane(MenuPane.this);
}
});
JButton green = new JButton("Green");
green.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getNavigationListener().presentGreenPane(MenuPane.this);
}
});
JButton blue = new JButton("Blue");
blue.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getNavigationListener().presentBluePane(MenuPane.this);
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.BOTH;
add(red, gbc);
add(green, gbc);
add(blue, gbc);
}
protected NavigationListener getNavigationListener() {
return navigationListener;
}
}
public interface ReturnNavigationListener<T> {
public void returnFrom(T source);
}
public class RedPane extends JPanel {
private ReturnNavigationListener<RedPane> navigationListener;
public RedPane(ReturnNavigationListener<RedPane> navigationListener) {
this.navigationListener = navigationListener;
setBackground(Color.RED);
setLayout(new BorderLayout());
add(new JLabel("Roses are red", JLabel.CENTER));
JButton back = new JButton("Back");
back.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getReturnNavigationListener().returnFrom(RedPane.this);
}
});
add(back, BorderLayout.SOUTH);
}
public ReturnNavigationListener<RedPane> getReturnNavigationListener() {
return navigationListener;
}
}
public class BluePane extends JPanel {
private ReturnNavigationListener<BluePane> navigationListener;
public BluePane(ReturnNavigationListener<BluePane> navigationListener) {
this.navigationListener = navigationListener;
setBackground(Color.BLUE);
setLayout(new BorderLayout());
add(new JLabel("Violets are blue", JLabel.CENTER));
JButton back = new JButton("Back");
back.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getReturnNavigationListener().returnFrom(BluePane.this);
}
});
add(back, BorderLayout.SOUTH);
}
public ReturnNavigationListener<BluePane> getReturnNavigationListener() {
return navigationListener;
}
}
public class GreenPane extends JPanel {
private ReturnNavigationListener<GreenPane> navigationListener;
public GreenPane(ReturnNavigationListener<GreenPane> navigationListener) {
this.navigationListener = navigationListener;
setBackground(Color.GREEN);
setLayout(new BorderLayout());
add(new JLabel("Kermit is green", JLabel.CENTER));
JButton back = new JButton("Back");
back.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getReturnNavigationListener().returnFrom(GreenPane.this);
}
});
add(back, BorderLayout.SOUTH);
}
public ReturnNavigationListener<GreenPane> getReturnNavigationListener() {
return navigationListener;
}
}
}
Hi I've there a little problem: What I want is to delay the appearance of JLabels in a JDialog-Window, in terms of that the first line of JLabels shoud come out and then two seconds later the second line of Jlabels etc.
I've tried something with Windowlistener,the doClick()-Method etc., bu every time the Jdialog revalidates all of its panels AT ONCE and shows them without any delaying!
Please help me(Just copy the code below and try out)!
package footballQuestioner;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public class attempter {
public static void main(String[] args) throws InterruptedException {
JDialog dialog = new Punkte();
}
}
class Punkte extends JDialog {
private JPanel screenPanel = new JPanel(new GridLayout(4, 1));
private JButton button = new JButton();
private int i = 1;
private class WindowHandler implements WindowListener {
#Override
public void windowActivated(WindowEvent e) {
}
#Override
public void windowClosed(WindowEvent e) {
}
#Override
public void windowClosing(WindowEvent e) {
}
#Override
public void windowDeactivated(WindowEvent e) {
}
#Override
public void windowDeiconified(WindowEvent e) {
}
#Override
public void windowIconified(WindowEvent e) {
}
#Override
public void windowOpened(WindowEvent e) {
button.doClick(1000);
button.doClick(1000);
button.doClick(1000);
button.doClick(); // here im trying to delay the appearance of the
// JLabels....
}
}
private class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
switch (i) {
case 1:
settingUpPanel(getPanelFromScreenPanel(i), "Right", new Color(
102, 205, 0));
settingUpPanel(getPanelFromScreenPanel(i), "Wrong", Color.RED);
break;
case 2:
settingUpPanel(getPanelFromScreenPanel(i), "Trefferquote",
Color.YELLOW);
break;
case 3:
settingUpPanel(getPanelFromScreenPanel(i), "Ausgezeichnet",
Color.BLUE);
break;
}
System.out.println(i);
i++;
}
}
public Punkte() {
button.addActionListener(new ButtonHandler());
addWindowListener(new WindowHandler());
setModal(true);
setResizable(true);
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
settingUpScreenPanel();
add(screenPanel);
setSize(1200, 1000);
centeringWindow();
setVisible(true);
}
private void settingUpScreenPanel() {
JPanel titlePanel = new JPanel(new GridBagLayout());
JPanel rightWrongCountPanel = new JPanel(new GridLayout(1, 2));
JPanel shareOfRightQuestions = new JPanel(new GridBagLayout());
JPanel grade = new JPanel(new GridBagLayout());
settingUpPanel(titlePanel, "Result", Color.BLACK);
// settingUpPanel(rightWrongCountPanel,
// "Right: "+numberOfRightAnsers+"/6",new Color(102,205,0));
// settingUpPanel(rightWrongCountPanel,
// "Wrong: "+(6-numberOfRightAnsers)+"/6", Color.RED);
// settingUpPanel(shareOfRightQuestions,
// "Trefferquote: "+(numberOfRightAnsers*100/6)+"%",Color.YELLOW);
// settingUpPanel(summaSummarum,
// getBufferedImage("footballQuestioner/Strich.png"));
// settingUpPanel(grade,"Aushezeichnet", Color.BLUE);
borderingJPanel(screenPanel, null, null);
titlePanel.setOpaque(false);
rightWrongCountPanel.setOpaque(false);
shareOfRightQuestions.setOpaque(false);
grade.setOpaque(false);
screenPanel.add(titlePanel);
screenPanel.add(rightWrongCountPanel);
screenPanel.add(shareOfRightQuestions);
screenPanel.add(grade);
}
private void settingUpPanel(JComponent panel, String string, Color color) {
Font font = new Font("Rockwell Extra Bold", Font.PLAIN, 65);
JPanel innerPanel = new JPanel(new GridBagLayout());
JLabel label = new JLabel(string);
label.setForeground(color);
label.setFont(font);
innerPanel.add(label);
innerPanel.setOpaque(false);
panel.add(innerPanel);
panel.validate();
panel.repaint();
}
public JPanel getPanelFromScreenPanel(int numberOfPanel) {
JPanel screenPanel = (JPanel) getContentPane().getComponent(0);
JPanel labelPanel = (JPanel) screenPanel.getComponent(numberOfPanel);
return labelPanel;
}
public void centeringWindow() {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x;
int y;
x = (int) (dimension.getWidth() - getWidth()) / 2;
y = (int) (dimension.getHeight() - getHeight()) / 2;
setLocation(x, y);
}
public void borderingJPanel(JComponent panel, String jPanelname,
String fontStyle) {
Font font = new Font(fontStyle, Font.BOLD + Font.ITALIC, 12);
if (jPanelname != null) {
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(EtchedBorder.LOWERED, Color.GRAY,
Color.WHITE), jPanelname,
TitledBorder.DEFAULT_JUSTIFICATION,
TitledBorder.DEFAULT_POSITION, font));
} else if (jPanelname == null || fontStyle == null) {
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(EtchedBorder.LOWERED, Color.BLACK,
Color.WHITE)));
}
panel.setOpaque(false);
}
}
This is a really good use case for javax.swing.Timer...
This will allow you to schedule a callback, at a regular interval with which you can perform an action, safely on the UI.
private class WindowHandler extends WindowAdapter {
#Override
public void windowOpened(WindowEvent e) {
System.out.println("...");
Timer timer = new Timer(2000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPanel panel = getPanelFromScreenPanel(1);
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
for (int index = 0; index < 100; index++) {
panel.add(new JLabel(Integer.toString(index)), gbc);
}
panel.revalidate();
}
});
timer.start();
timer.setRepeats(false);
}
}
Now, if you wanted to do a series of actions, separated by the interval, you could use a counter to determine the number of "ticks" that have occurred and take appropriate action...
private class WindowHandler extends WindowAdapter {
#Override
public void windowOpened(WindowEvent e) {
System.out.println("...");
Timer timer = new Timer(2000, new ActionListener() {
private int counter = 0;
private int maxActions = 10;
#Override
public void actionPerformed(ActionEvent e) {
switch (counter) {
case 0:
// Action for case 0...
break;
case 1:
// Action for case 1...
break;
.
.
.
}
counter++;
if (counter >= maxActions) {
((Timer)e.getSource()).stop();
}
}
});
timer.start();
}
}
Take a look at How to use Swing Timers for more details
This is my button Code onclick i want my program to wait for the user to click one JPanel and as the user clicks the JPanel it should print its name on console.
This button code is not showing the output
JPopupMenu popupMenu_1 = new JPopupMenu();
JMenuItem mntmOneToOne = new JMenuItem("One to One");
mntmOneToOne.setIcon(new ImageIcon("C:\\Users\\Ashad\\Desktop\\oneToone.png"));
popupMenu_1.add(mntmOneToOne);
OneToOne.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent arg0)
{
MouseListener Listen= new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
String name=new String();
JPanel panel = (JPanel) me.getSource();
// name = panel.getName();
System.out.println(panel.getName());
}
};
}
});
for better help sooner post an SSCCE, short,
runnable, compilable,
because works in my SSCCE, and the answer to
This is my button Code onclick i want my program to wait for the user
to click one JPanel and as the user clicks the JPanel it should print
its name on console.
issue must be in rest of your code,
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class MyGridLayout {
public MyGridLayout() {
JPanel bPanel = new JPanel();
bPanel.setLayout(new GridLayout(10, 10, 2, 2));
for (int row = 0; row < 10; row++) {
for (int col = 0; col < 10; col++) {
JPanel b = new JPanel() {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(20, 20);
}
};
b.putClientProperty("column", row);
b.putClientProperty("row", col);
b.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
JPanel btn = (JPanel) e.getSource();
System.out.println("clicked column " + btn.getClientProperty("column")
+ ", row " + btn.getClientProperty("row"));
}
});
b.setBorder(new LineBorder(Color.blue, 1));
bPanel.add(b);
}
}
JFrame frame = new JFrame("PutClientProperty Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(bPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MyGridLayout myGridLayout = new MyGridLayout();
}
});
}
}
You declared a MouseAdapter in your MouseListener mouseClicked method which just sits there and does exactly nothing because nothing is done with it. If you want to add a MouseListener to a panel do the following:
panel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
JPanel panel = (JPanel) arg0.getSource();
System.out.println(panel.getName());
}
});
I'm attempting to overlap JPanel instances. Put a panel directly on another, in the exact same position and exact size. Every time I do this it moves the other panel to the other side or underneath, the previous panel is inside another much larger one and has buttons in it.
How would I do this? Keep in mind it's using the Window Builder tool.
You might also want to look at OverlayLayout, seen here. It's not included in the conventional gallery, but it may be of interest.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.OverlayLayout;
/** #see http://stackoverflow.com/a/13437388/230513 */
public class OverlaySample {
public static void main(String args[]) {
JFrame frame = new JFrame("Overlay Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new OverlayLayout(panel));
panel.add(create(1, "One", Color.gray.brighter()));
panel.add(create(2, "Two", Color.gray));
panel.add(create(3, "Three", Color.gray.darker()));
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private static JLabel create(final int index, String name, Color color) {
JLabel label = new JLabel(name) {
private static final int N = 64;
#Override
public boolean isOpaque() {
return true;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(index * N, index * N);
}
#Override
public Dimension getMaximumSize() {
return new Dimension(index * N, index * N);
}
};
label.setHorizontalAlignment(JLabel.RIGHT);
label.setVerticalAlignment(JLabel.BOTTOM);
label.setBackground(color);
label.setAlignmentX(0.0f);
label.setAlignmentY(0.0f);
return label;
}
}
I'm attempting to overlap JPanels
Use a JLayeredPane (image below from the linked tutorial).
Put a JPanel directly on another,
..or a CardLayout as shown here..
..depending on which of those two you mean, since I understand them as quite different effects.
Use a JDesktopPane (or its superclass JLayeredPane) as its content, adding to the pane.
See How to Use Internal Frames for examples.
Here you can see a nice way of letting components overlay, and pop up when the cursor rests on it:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ShiftedStackPanel extends JPanel implements MouseListener,
ActionListener {
private static final long serialVersionUID = 1988454751139668485L;
private int layer;
private JDesktopPane desktopPane;
private Timer timer;
private Component currentComponent;
private int layerOfCurrent;
private int shiftDivision;
public ShiftedStackPanel() {
this(4);
}
public ShiftedStackPanel(int shift) {
shiftDivision = shift;
setLayout(new BorderLayout(0, 0));
desktopPane = new JDesktopPane();
desktopPane.setBackground(SystemColor.window);
super.add(desktopPane);
timer = new Timer(1000, this);
timer.setRepeats(false);
}
public Component add(Component c) {
Dimension dim = c.getPreferredSize();
c.setBounds(
(desktopPane.getComponentCount() * (dim.width / shiftDivision)),
0, dim.width, dim.height);
desktopPane.add(c, new Integer(++layer));
c.addMouseListener(this);
return c;
}
public void remove(Component c) {
throw new IllegalArgumentException(
"Removal of component, not yet supported.");
// FIXME: allow removal, and shift all latter comps, to left
}
public void removeAll() {
desktopPane.removeAll();
}
public static void main(String[] args) {
JFrame f = new JFrame("JFrame Wrapper");
ShiftedStackPanel p;
f.setContentPane(p = new ShiftedStackPanel(4));
p.add(new JTextField("ABCDEFGHI"));
p.add(new JTextField("DEFGHIJKL"));
p.add(new JTextField("GHIJKLMNO"));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.setMinimumSize(new Dimension(400, 200));
f.setLocationRelativeTo(null);
}
#Override
public void mouseClicked(MouseEvent evt) {
if (currentComponent != null) {
Component c = (Component) evt.getSource();
currentComponent = c;
layerOfCurrent = desktopPane.getLayer(c);
desktopPane.remove(c);
desktopPane.add(c, new Integer(100));
}
}
#Override
public void mouseEntered(MouseEvent evt) {
timer.start();
Component c = (Component) evt.getSource();
currentComponent = c;
layerOfCurrent = desktopPane.getLayer(c);
}
#Override
public void mouseExited(MouseEvent evt) {
if ((currentComponent != null) && currentComponent == evt.getSource()) {
desktopPane.remove(currentComponent);
desktopPane.add(currentComponent, new Integer(layerOfCurrent));
currentComponent = null;
timer.stop();
}
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent arg0) {
desktopPane.remove(currentComponent);
desktopPane.add(currentComponent, new Integer(100));
}
}
Still has some problems, when using components that require focus, but should work well with JLabel, and JPanel.