I'm trying to add 2 images inside the JScrollPane. the first image is a background and the second one overlap the first one. The problem shows only the second image when i run my program!
please help
ImageIcon ii = new ImageIcon("mini_map.png");
JLabel label1=new JLabel(ii);
Icon icon = new ImageIcon("Mg.gif");
JLabel label2 = new JLabel(icon);
JScrollPane jsp=new JScrollPane();
jsp.getViewport().add(label1);
jsp.getViewport().add(label2 );
JViewport is a single-child container, you can't add two components.
To achieve an overlap (that is stack components in z-direction) in any container, you'r mostly on your own, the built-in support is poor. Either have to manage them in LayeredPane (as mentioned already) or try OverlapLayout
Put both labels in the same panel and add it to the JScrollPane:
ImageIcon ii = new ImageIcon("mini_map.png");
JLabel label1=new JLabel(ii);
Icon icon = new ImageIcon("Mg.gif");
JLabel label2 = new JLabel(icon);
JPanel pContainer = new JPanel();
pContainer.add(label1);
pContainer.add(label2);
JScrollPane jsp=new JScrollPane(pContainer);
If you want to have components on top of each other use a layered pane.
This is how I would do it for your particular problem.
Since you say you have one image which serves the role of a background, thus I would override paintComponent() like in BackgroundPanel below.
This way you have a panel which serves as a background only. To it you can add any type of component, in your case a JLabel with an ImageIcon.
This way you have an effect of one being over another and you are still able to use layout manager to control where your components are.
If your problem is more complex or you want to generally set Components one over another then do as all are saying here ---> use JLayeredPane. Note that if you use JLayeredPane sadly layout managers will not help you since it doesn't respects them. You will have to proceed similarly to a situation when you use a null manager, i.e. setBounds() for components.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class PaintInScroll
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
try
{
Image backgroundImage = new ImageIcon(new URL(
"http://www.jvsearch.com/adidocs7_images/JAVAORANGE.JPG")).getImage();
BackgroundPanel bP = new BackgroundPanel(backgroundImage);
bP.setLayout(new BorderLayout());
bP.setPreferredSize(new Dimension(500, 500));
JLabel label = new JLabel(new ImageIcon(new URL(
"https://blogs.oracle.com/theplanetarium/resource/thumb-java-duke-guitar.png")));
bP.add(label, BorderLayout.CENTER);
JScrollPane scrollPane = new JScrollPane(bP);
scrollPane.setPreferredSize(new Dimension(300, 400));
JPanel contentPane = new JPanel();
contentPane.add(scrollPane);
JFrame f = new JFrame();
f.setContentPane(contentPane);
f.setSize(800, 600);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}catch(MalformedURLException ex)
{
Logger.getLogger(PaintInScroll.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
class BackgroundPanel extends JPanel
{
private Image image;
public BackgroundPanel(Image image)
{
this.image = image;
}
private static final long serialVersionUID = 1L;
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
}
}
NOTE: Images are URLs thus i-net connection is required to run the example.
EDIT1: Example showing how to use JLayeredPane with use of layout managers for each layer.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class PaintInScrollRespectingLayoutManagers extends JPanel
{
private static final long serialVersionUID = 1L;
private JLayeredPane layeredPane;
private JLabel imageContainer = new JLabel();
private JButton infoB = new JButton("i");
private JScrollPane scrollPane;
public PaintInScrollRespectingLayoutManagers(ImageIcon image)
{
super();
this.imageContainer.setIcon(image);
scrollPane = new JScrollPane(imageContainer);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(125, 90));
JPanel iSPP = new JPanel();//image scroll pane panel
iSPP.setOpaque(false);
iSPP.add(scrollPane);
JPanel iBP = new JPanel();//info button panel
iBP.setOpaque(false);
iBP.add(infoB);
this.layeredPane = new JLayeredPane();
layeredPane.add(iSPP, new Integer(50));
layeredPane.add(iBP, new Integer(100));
this.setLayout(new BorderLayout());
this.add(layeredPane, BorderLayout.CENTER);
this.add(new JButton("A button"), BorderLayout.SOUTH);
layeredPane.addComponentListener(layeredPaneCL);
setPreferredSize(new Dimension(300, 300));
}
private ComponentListener layeredPaneCL = new ComponentAdapter()
{
#Override
public void componentResized(ComponentEvent e)
{
super.componentResized(e);
System.out.println("componentResized");
for(Component c : layeredPane.getComponents())
c.setSize(layeredPane.getSize());
}
};
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
try
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new PaintInScrollRespectingLayoutManagers(new ImageIcon(new URL(
"http://www.prodeveloper.org/wp-content/uploads/2008/10/stackoverflow-logo-250.png"))));
frame.pack();
frame.setVisible(true);
}catch(MalformedURLException ex)
{
Logger.getLogger(PaintInScrollRespectingLayoutManagers.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
NOTE 2: The only reason that the scroll panes have setPrefferedSize is so you can see the scrollbars. Otherwise do not use it let the layout take care of controlling scroll pane.
Related
*edited so it might be helpful to others:
I was struggling with why an ImageIcon was being padded in a JPanel, but not in a JToolBar even though they were added in the same way, using the same file (see the folder icon):
Cutting down the code to an sscce has shown that VGR's answer below is right - it's has to be how each component deals with JButtons, rather than the layout.
This code should run, but you'll have to have "images/open.png" in the source folder.
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.border.Border;
class CandidatePanel extends JPanel{
private JPanel panel = new JPanel();
private JToolBar tb = new JToolBar();
private JButton tbButton = new JButton();
private JButton cvButton = new JButton();
public static void main(String[] args){
JFrame frame = new JFrame();
frame.add(new CandidatePanel());
frame.pack();
frame.setVisible(true);
}
public CandidatePanel(){
setLayout(new GridBagLayout());
tbButton.setIcon(new PanelHelper().createIcon("images/open.png", ""));
tb.add(tbButton);
cvButton.setIcon(new PanelHelper().createIcon("images/open.png", ""));
cvButton.setFocusPainted(false);
cvButton.setContentAreaFilled(false);
cvButton.setBorderPainted(true);
addComponents();
add(tb);
add(panel);
}
private void addComponents(){
panel.setLayout(new GridBagLayout());
int row =0;
//new row
JPanel cvButtonPanel = (JPanel)PanelHelper.addTestBorder(new JPanel(),Color.BLUE);
cvButtonPanel.add(cvButton);
cvButtonPanel.add(PanelHelper.addTestBorder(new JPanel(), Color.RED));
panel.add(tb, new GBC(1,row));
panel.add(cvButtonPanel, new GBC(1,++row));
}
}
class PanelHelper{
public static JComponent addTestBorder(JComponent comp, Color color){
Border border = BorderFactory.createLineBorder(color);
comp.setBorder(border);
return comp;
}
public ImageIcon createIcon(String path, String btnName){
URL url = getClass().getResource(path);
if(url == null)
System.err.println("\nThe "+btnName+" Icon Path Cannot Be Found: "+path);
return new ImageIcon(url);
}
}
it was just as simple as setting the button margin, as mentioned in the comments below.
button.setMargin(new Insets(0,0,0,0))
I failed to change the height of JPanel or JScrollPane to make more lines to appear, I used GridLayout. It seems that, every component in it should have the same size even when I use setSize(). Should I use another layout?
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class Main {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private imagePanel image;
JTextField textField = new JTextField(20);
public Main() throws IOException{
prepareGUI();
}
class imagePanel extends JPanel {
private static final long serialVersionUID = 1L;
public void paint(Graphics g) {
try {
BufferedImage image = ImageIO.read(new File("file.jpg"));
g.drawImage(image, 170, 0, null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException{
Main swingControlDemo = new Main();
swingControlDemo.showEventDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
mainFrame.setSize(400,500);
GridLayout gridlayout = new GridLayout(4, 1);
gridlayout.setVgap(1);
mainFrame.setLayout(gridlayout);
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
JScrollPane scroller = new JScrollPane(statusLabel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
image = new imagePanel();
image.setLayout(new FlowLayout());
// mainFrame.add(headerLabel);
mainFrame.add(image);
mainFrame.add(controlPanel);
mainFrame.add(scroller);
mainFrame.setVisible(true);
}
private void showEventDemo(){
headerLabel.setText("Control in action: Button");
JButton okButton = new JButton("reload");
JButton submitButton = new JButton("Submit");
JButton cancelButton = new JButton("Cancel");
okButton.setActionCommand("reload");
submitButton.setActionCommand("Submit");
cancelButton.setActionCommand("Cancel");
okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
controlPanel.add(okButton);
controlPanel.add(submitButton);
//controlPanel.add(cancelButton);
controlPanel.add(textField);
System.out.println("---------------------");
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if( command.equals( "reload" )) {
statusLabel.setText(convertToMultiline("Line1\nLine2\nLine3\nLine4\nLine5\nLine6\nLine7\nLine8\nLine9\nLine2\nLine3\nLine\nLine2\nLine3\nLine\nLine2\nLine3\nLine\nLine2\nLine3\nLine\nLine2\nLine3\nLine\nLine2\nLine3\nLine\nLine2\nLine3\nLine"));
}
else {
statusLabel.setText("Submit Button clicked.");
}
}
}
public static String convertToMultiline(String orig)
{
return "<html>" + orig.replaceAll("\n", "<br>");
}
}
The GUI need to look like this
I want to remove the large vertical gaps between the componets, and the jLabel should use that space
Well in your comment you say you want the label to use the space. But in your picture you show the text area with all the space. How can we answer a question when you give us conflicting requirements? Be specific and accurate when describing a problem.
In any case, the default layout of a JFrame is a BorderLayout so you would probably start with that.
Then the component that you want to grow/shrink as the frame is resized should be added to the CENTER of the frame.
Then you create a second panel to contain your other components. This panel would then be added to either the PAGE_START or PAGE_NORTH of the frame depending on your exact requirement.
The layout manager of this panel can then be whatever your want. Maybe a GridLayout, or a GridBagLayout or a vertical BoxLayout.
Read the section from the Swing tutorial on Layout Managers for more information and working examples. The key point is you create nest panels each with a different layout manager to achieve your layout.
I have a JFrame. In that i have used:
JTabbed panes.
JButton.
background images in a Jlabel which is added in JPanel.
Nimbus look and feel.
My problem is that whenever i use Nimbus look and feel the JButton vanishes only if there is a background image added. But this doesn't happen with other look and feel. Can anyone help me in getting the button visible?
Here is my code:
import javax.swing.ImageIcon;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.*;
import java.awt.event.*;
class ImageTest
{
JTabbedPane tp;
JLabel lab1;
JPanel welcome;
JFrame frame;
ImageIcon image2;
JButton b1;
public void createUI()
{
frame=new JFrame("JTabbedPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1=new JButton();
welcome= new JPanel(null);
welcome.setPreferredSize(new Dimension(1366,786));
ImageIcon icon = new ImageIcon(ImageTest.class.getResource("icloud.jpg"));
tp=new JTabbedPane();
Container pane = frame.getContentPane();
pane.add(tp);
tp.addTab("Welcome", welcome);
lab1=new JLabel();
lab1.setIcon(icon);
b1.setBounds(100,100,100,100);
lab1.setBounds(0,0,1500,700);
welcome.add(lab1);
welcome.add(b1);
b1.setVisible(true);
frame.setSize(500,500);
frame.setVisible(true);
frame.setTitle("I-Cloud");
}
public static void main(String[] args)
{
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
}
ImageTest w = new ImageTest();
w.createUI();
}
}
EDIT:
import javax.swing.ImageIcon;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.*;
import java.awt.event.*;
class ImageTest
{
JTabbedPane tp;
JLabel lab1;
JPanel welcome,w;
JFrame frame;
ImageIcon image2;
JButton b1;
public void createUI()
{
frame=new JFrame("JTabbedPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1=new JButton();
welcome= new JPanel(new GridLayout(1,1,15,15));
w=new JPanel (new GridLayout(1, 1, 15, 15));
welcome.setPreferredSize(new Dimension(1366,786));
ImageIcon icon = new ImageIcon(ImageTest.class.getResource("icloud.jpg"));
tp=new JTabbedPane();
Container pane = frame.getContentPane();
pane.add(tp);
lab1=new JLabel();
lab1.setIcon(icon);
w.setOpaque(false);
w.add(b1);
b1.setVisible(true);
welcome.add(lab1);
welcome.add(w);
tp.addTab("Welcome", welcome);
frame.setSize(500,500);
frame.pack();
frame.setVisible(true);
frame.setTitle("I-Cloud");
}
public static void main(String[] args)
{
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
}
ImageTest w = new ImageTest();
w.createUI();
}
}
Thanks.
Your use of Swing GUI is out of kilter by use of null layouts and then adding one component on top of another, essentially covering up one of the components (the JButton) with another (the JLabel with the image).
Don't use null layout like you're doing. While to a newbie using null layout and setBounds seems the best way to create complex GUI's, the more you deal with Swing GUI creation, the more you will find that doing this will put your GUI in a straight-jacket, painting it in a very tight corner and making it very hard to extend or enhance. Just don't do this.
Don't add one component on top of another in the same container.
Instead give your JLabel with the image a layout manager.
Then add the JButton to the JLabel.
Then add the JLabel to the JTabbedPane.
Edit
Your latest edit did not use the JLabel as the container as suggested above. So if you use a separate container, then the button and the label will be shown side by side. To solve this, you either need to give the JLabel a layout manager, and then add the button to it as suggested above, or draw directly in a JPanel's paintComponent(...) method, and add the button to the JPanel.
For an example of the latter:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
public class MyImageTest extends JPanel {
// public static final String SPEC = "https://duke.kenai.com/SunRIP/.Midsize/SunRIP.jpg.png";
public static final String SPEC = "http://upload.wikimedia.org/wikipedia/commons/3/37/"
+ "Mandel_zoom_14_satellite_julia_island.jpg";
private static final int PREF_H = 786;
private static final int GAP = 100;
private BufferedImage img;
public MyImageTest() {
try {
URL imgUrl = new URL(SPEC);
img = ImageIO.read(imgUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
setLayout(new FlowLayout(FlowLayout.LEADING));
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
JButton b = new JButton();
b.setPreferredSize(new Dimension(GAP, GAP));
add(b);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
#Override
public Dimension getPreferredSize() {
if (img == null) {
return super.getPreferredSize();
} else {
int width = (img.getWidth() * PREF_H) / img.getHeight();
return new Dimension(width, PREF_H);
// return new Dimension(img.getWidth(), img.getHeight());
}
}
private static void createAndShowGui() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
MyImageTest mainPanel = new MyImageTest();
JFrame frame = new JFrame("MyImageTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I think setting a background image in JLabel and then adding buttons even after adding containers is a very complex issue. Believe me tried it and it was a very complex task. you can do it by directly drawing as Hovercraft suggested, but remember you would get not so much good image quality with that method. :-|
I know a lot of people asked this question, but i still can't resolve this problem.
I have a JPanel inside a JScrollPane. JPanel contains six panels that are loaded dynamically.
After the panels are loaded the system makes a vertical autoscroll to the middle of the panel.
I have to avoid this, so I tried with this:
panel.scrollRectToVisible(scrollPane.getBounds());
But it doesn't work.
My scrollPane has been created in this way
JScrollPane scrollPane= new JScrollPane();
scrollPane.setBounds(panel.getBounds());
scrollPane.setViewportView(panel);
Can you help me?
panel.scrollRectToVisible(scrollPane.getBounds()); should be panel.scrollRectToVisible(JPanelAddedOnRuntime.getBounds());
rest of code (posted here) coudn't be works,
for better help sooner post an SSCCE, short, runnable, compilable
EDIT
works, again you would need to re_read my above 3rd. point
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class ScrollTesting {
private JPanel panel = new JPanel();
private JScrollPane scrollPane = new JScrollPane(panel);
private Vector<JTextField> fieldsVector = new Vector<JTextField>();
private Dimension preferredSize = new Dimension(400, 40);
private Font font = new Font("Tahoma", 1, 28);
public ScrollTesting() {
panel.setLayout(new GridLayout(100, 1));
for (int i = 0; i < 100; i++) {
fieldsVector.addElement(new JTextField());
fieldsVector.lastElement().setPreferredSize(preferredSize);
fieldsVector.lastElement().setFont(font);
panel.add(fieldsVector.lastElement());
}
JFrame frame = new JFrame();
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane);
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JTextField tf = (JTextField) fieldsVector.lastElement();
panel.scrollRectToVisible(tf.getBounds());
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ScrollTesting scrollTesting = new ScrollTesting();
}
});
}
}
I have a question about resizing a JPanel.
I have a JSlider, which resize a JPanel dynamycly. When i change the value Height() of JPanel, size of panel decreases or increases, from top to down, effect as the curtain, but when I change a value Width(), it does not effect curtain, Panel resizes from Center, and decreases or increases in both sides at the same time.
Dear experts, tell please how can I resize a Panel width from left to right, or backward?
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JToolBar;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Swipe extends JFrame {
static JPanel panel = null;
static JPanel panel2 = null;
static JPanel panel3 = null;
static JLabel label1 = null;
static JLabel label2 = null;
static JSlider slider = null;
static JToolBar bar = null;
ImageIcon img;
public Swipe(ImageIcon img1, ImageIcon img2) {
JFrame frame = new JFrame();
bar = new JToolBar();
bar.add(slider(img1));
frame.add(bar, BorderLayout.NORTH);
label1 = new JLabel();
label1.setLayout(null);
label1.setMaximumSize(new Dimension(img2.getIconWidth(), img2.getIconHeight()));
label1.setIcon(img1);
panel = new JPanel();
panel.add(label1, new GridBagConstraints());
label2 = new JLabel();
label2.setPreferredSize(new Dimension(img2.getIconWidth(), img2.getIconHeight() + 20));
label2.setMaximumSize(new Dimension(img2.getIconWidth(), img2.getIconHeight()));
label2.setIcon(img2);
frame.setLayout(new FlowLayout());
label2.setLayout(new FlowLayout());
label2.add(panel);
frame.add(label2);
frame.setSize(img2.getIconWidth() + 50, img2.getIconHeight() + 50);
frame.setVisible(true);
frame.pack();
}
public JSlider slider(final ImageIcon im) {
slider = new JSlider();
slider.setMaximum(im.getIconHeight());
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
// TODO Auto-generated method stub
int value = slider.getValue();
//panel.setPreferredSize(new Dimension(im.getIconWidth(),value));
panel.setPreferredSize(new Dimension(value, im.getIconHeight()));
panel.repaint();
panel.updateUI();
}
});
return slider;
}
}
While it is surely possible to do your way, it is much simpler and easier to use JSplitPane to achieve I think the comparable goal:
new JSplitPane(JSplitPane.VERTICAL_SPLIT,
componentOnLeft, Component componentOnRight);
JSplitPane also has the setDividerLocation methods (one absolute, one proportional) if you need to resize the two components programmatically.