how to make a jscrollpane scroll from the start to the end? - java

I'm trying to make a jscorllpane automatic scroll from the start to the end. I use set value method for verticalbar but it's doesn't work. How can i make it scroll ?
Here is my code: When i run this code it just jump to the end of the jscorllpane instead of scorlling step by step
import java.awt.event.*;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class JScrollPaneToTopAction implements ActionListener {
JScrollPane scrollPane;
public JScrollPaneToTopAction(JScrollPane scrollPane) {
if (scrollPane == null) {
throw new IllegalArgumentException("JScrollPaneToTopAction: null JScrollPane");
}
this.scrollPane = scrollPane;
}
public void actionPerformed(ActionEvent actionEvent) {
run();
}
public void run() {
JScrollBar verticalBar = scrollPane.getVerticalScrollBar();
int i = verticalBar.getMinimum();
while (i < verticalBar.getMaximum()) {
verticalBar.setValue(verticalBar.getMinimum()+i);
i += 50;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
scrollPane.getParent().invalidate();
scrollPane.repaint();
scrollPane.invalidate();
System.out.println("changing " + i);
}
}
}
public class Draft20 {
public static void main(String args[]) {
JFrame frame = new JFrame("Tabbed Pane Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea tr = new JTextArea();
JLabel label = new JLabel("Label");
label.setPreferredSize(new Dimension(1000, 1000));
JScrollPane jScrollPane = new JScrollPane(label);
JButton bn = new JButton("Move");
bn.addActionListener(new JScrollPaneToTopAction(jScrollPane));
frame.add(bn, BorderLayout.SOUTH);
frame.add(jScrollPane, BorderLayout.CENTER);
frame.setSize(400, 150);
frame.setVisible(true);
}
}

I think the problem is your calls to repaint are queued for computation by EDT, but EDT is busy executing your actionPerformed. EDT will execute your repaint requests only after your run() completes. That's why you can see only the final result.
I'm not sure I can make it clear... check this code, it works for me:
import java.awt.BorderLayout;
import java.awt.Dimension;
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.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
class JScrollPaneToTopAction implements ActionListener, Runnable {
JScrollPane scrollPane;
public JScrollPaneToTopAction(JScrollPane scrollPane) {
if (scrollPane == null) {
throw new IllegalArgumentException("JScrollPaneToTopAction: null JScrollPane");
}
this.scrollPane = scrollPane;
}
#Override
public void actionPerformed(ActionEvent actionEvent) {
new Thread(this).start();
}
#Override
public void run() {
JScrollBar verticalBar = scrollPane.getVerticalScrollBar();
int i = verticalBar.getMinimum();
while (i < verticalBar.getMaximum()) {
verticalBar.setValue(verticalBar.getMinimum() + i);
i += 50;
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
scrollPane.getParent().invalidate();
scrollPane.repaint();
scrollPane.invalidate();
}
});
System.out.println("changing " + i);
}
}
}
public class Draft20 {
public static void main(String args[]) {
JFrame frame = new JFrame("Tabbed Pane Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea tr = new JTextArea();
JLabel label = new JLabel("Label");
label.setPreferredSize(new Dimension(1000, 1000));
JScrollPane jScrollPane = new JScrollPane(label);
JButton bn = new JButton("Move");
bn.addActionListener(new JScrollPaneToTopAction(jScrollPane));
frame.add(bn, BorderLayout.SOUTH);
frame.add(jScrollPane, BorderLayout.CENTER);
frame.setSize(400, 150);
frame.setVisible(true);
}
}
I hope it helps.

Related

how to set semi-transparent jframe when "submit" button is clicked?

loadingLab=new JLabel("The name is being saved..");
loadPanel.add(loadingLab);
submitBttn=new JButton("Submit");
submitBttn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Submit Button Clicked!!");
try {
//something is wrong in here as it throws an exception
//what is wrong?
frame.setUndecorated(false);
frame.setOpacity(0.55f);
//when above both lines are commented, the code works fine
//but doesnt have transparency
frame.add(loadPanel,BorderLayout.SOUTH);
frame.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
I am trying to display transparent JFrame when "submit" button is clicked which displays panel with a JLabel...
I have tried using setOpacity(0.55f), but it throws exception.. what am i doing wrong?
Unfortunately I think there's no way to keep the system window decoration, you will probably have to go with the default one. Since I'm not 100% sure if you want to toggle the opacity of the whole frame or just the frame's background, I've included both functions in my example. (mKorbels answer help you more if you don't want to have a decoration)
Code:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
public class TransparentExample extends JFrame {
public TransparentExample() {
super("TransparentExample");
Color defaultBackground = getBackground();
float defaultOpacity = getOpacity();
JToggleButton button1 = new JToggleButton("Toggle background transparency");
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (button1.isSelected()) {
setBackground(new Color(defaultBackground.getRed(), defaultBackground.getGreen(),
defaultBackground.getBlue(), 150));
} else {
setBackground(defaultBackground);
}
}
});
JToggleButton button2 = new JToggleButton("Toggle opacity of whole frame");
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
if (button2.isSelected()) {
setOpacity(0.55f);
} else {
setOpacity(defaultOpacity);
}
setVisible(true);
}
});
getContentPane().setLayout(new FlowLayout());
getContentPane().add(button1);
getContentPane().add(button2);
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame.setDefaultLookAndFeelDecorated(true);
TransparentExample frame = new TransparentExample();
frame.setVisible(true);
}
});
}
}
Picture of frame with no togglebutton selected:
Picture of frame with the first togglebutton selected:
Picture of frame with the second togglebutton selected:
#Programmer007 wrote - the exception is "
java.awt.IllegalComponentStateException: The frame is displayable."
please where I can't see any, for more info about the possible exceptions to read,
as mentioned no idea, everything is about your effort, transformed to the SSCCE / MCVE, short, runnable, compilable
.
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JDialog;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class GenericForm extends JDialog {
private static final long serialVersionUID = 1L;
private Timer timer;
private JDialog dialog = new JDialog();
private int count = 0;
public GenericForm() {
dialog.setSize(400, 300);
dialog.setUndecorated(true);
dialog.setOpacity(0.5f);
dialog.setName("Toggling with opacity");
dialog.getContentPane().setBackground(Color.RED);
dialog.setLocation(150, 150);
dialog.setVisible(true);
timer = new javax.swing.Timer(1500, updateCol());
timer.setRepeats(true);
timer.start();
}
private Action updateCol() {
return new AbstractAction("Hello World") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
boolean bol = dialog.getOpacity() < 0.55f;
count += 1;
if (count < 10) {
if (bol) {
dialog.setOpacity(1.0f);
dialog.getContentPane().setBackground(Color.WHITE);
} else {
dialog.setOpacity(0.5f);
dialog.getContentPane().setBackground(Color.RED);
}
} else {
System.exit(0);
}
}
};
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new GenericForm();
}
});
}
}

GUI Animation: Slider Value between Action and Change classes?

My GUI frame comes up now but the slider value (speed) I get from my slider doesn't appear in my ActionLlistener class where I need use it as a delay in my timer. How do I bring that value over? The point is to run 12 images, like frames, at a speed that is determined by the value they slide on. Like if they slide to 12, there will be 12 milliseconds between each image.
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.awt.*;
public class SliderGUI {
public static JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 1);
public static JLabel label = new JLabel ();
public static JPanel panel = new JPanel();
public static int delay;
public static int speed;
public static ImageIcon imageIcon;
public static Timer timer = new Timer (delay, new SliderListener());
public static void main(String[] args) {
JFrame frame = new JFrame("Legend Of Zelda");
panel.setLayout(new GridLayout(5, 5, 5, 25));
slider.setPaintLabels(true);
slider.addChangeListener(new SliderListener());
System.out.println (speed);
timer.addActionListener (new SliderListener());
frame.setVisible(true);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(label);
panel.add(slider);
frame.setContentPane(panel);
frame.pack();
}
private static class SliderListener implements ChangeListener, ActionListener {
public void stateChanged(ChangeEvent e) {
speed = slider.getValue();
slider.setMajorTickSpacing(25);
}
public void actionPerformed (ActionEvent e) {
for (int i = 1; i < 13; i++) {
if (i == 12){
i = 1;
}
imageIcon = new ImageIcon(i + ".jpg");
label.setIcon(imageIcon);
}
System.out.println ("Hi");
timer = new Timer(speed, new SliderListener());
timer.start();
}
}
}
Don't rely on static, it will blow up in your face...
You are creating multiple instances SliderListener when you really should be only creating one and applying it to the JSlider (and in your case) the Timer.
Having said that, I'd (personally) separate them...
You're also creating a new Timer each time the ActionListener is called (so like a thousand times a second! So after 1 second, you could have 1001 Timers running!) all of which are going to be calling SliderListener at the same time, and because it's all linked via global variables...face in explosion...
But I didn't actually see any where you were stating the Timer to start with...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SliderGUI {
public static void main(String[] args) {
new SliderGUI();
}
public SliderGUI() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public JSlider slider = new JSlider(JSlider.HORIZONTAL, 10, 100, 10);
public JLabel label;
public int delay;
public int speed;
public ImageIcon imageIcon;
public Timer timer;
public TestPane() {
setLayout(new GridLayout(5, 5, 5, 25));
slider.setPaintLabels(true);
label = new JLabel();
try {
BufferedImage frameImage = ImageIO.read(getClass().getResource("/Run-0.png"));
label.setIcon(new ImageIcon(frameImage));
} catch (IOException ex) {
ex.printStackTrace();
}
SliderListener sliderListener = new SliderListener();
timer = new Timer(delay, sliderListener);
slider.addChangeListener(sliderListener);
System.out.println(speed);
timer.addActionListener(sliderListener);
timer.start();
setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(label);
add(slider);
}
private class SliderListener implements ChangeListener, ActionListener {
public void stateChanged(ChangeEvent e) {
int value = slider.getValue();
timer.setDelay(value);
}
private int frame = 0;
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Tick " + ((Timer) e.getSource()).getDelay());
try {
BufferedImage frameImage = ImageIO.read(getClass().getResource("/Run-" + frame + ".png"));
label.setIcon(new ImageIcon(frameImage));
} catch (IOException exp) {
exp.printStackTrace();
}
frame++;
if (frame > 11) {
frame = 0;
}
}
}
}
}
Also, remember, a Timer is like a loop, each time the ActionListener is called, you should treat it as an iteration of a loop and update the state accordingly...

switching between a gif and a png on a JLabel

I'm trying to make a Russian Roulette game and I'm trying to change the JLabel to the gif of the revolver spinning. However, I can change it from the gif but not back to the picture of the revolver. Or is there a way to play the gif only once and have it stop then change it to another gif?
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class RussianRoulette extends JFrame {
private int Chamber;
private int BulletPos;
private boolean ButtonToggle;
JButton Fire = new JButton("Fire");
JButton Spin = new JButton("Spin");
JLabel Gun = new JLabel();
public RussianRoulette() {
ButtonToggle = true;
Chamber = (int) (Math.random() * 6 + 1);
BulletPos = 0;
JFrame frame = new JFrame();
frame.getContentPane().setLayout(null);
Gun.setBounds(0, 0, 500, 375);
Fire.setBounds(25, 375, 100, 100);
Spin.setBounds(350, 375, 100, 100);
ImageIcon imgThisImg = new ImageIcon("Revolver2.png");
Gun.setIcon(imgThisImg);
Spin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
spinGun();
sleep(600);
}
});
Fire.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
fireGun();
}
});
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.add(Gun);
frame.add(Fire);
frame.add(Spin);
frame.setResizable(true);
frame.setSize(500, 500);
Image im = Toolkit.getDefaultToolkit().getImage("icon.png");
frame.setIconImage(im);
frame.setVisible(true);
frame.setResizable(false);
frame.setTitle("Russian Roulette");
}
public void spinGun() {
ImageIcon imgThisImg = new ImageIcon("SpinRevolver.gif");
Gun.setIcon(imgThisImg);
sleep(600);
AudioPlayer player3 = new AudioPlayer("Spin.wav");
player3.play();
BulletPos = (int) (Math.random() * 6 + 1);
}
public void fireGun() {
if (ButtonToggle == false) {
AudioPlayer player5 = new AudioPlayer("Click.wav");
player5.play();
}
if (Chamber == BulletPos && ButtonToggle == true) {
AudioPlayer player2 = new AudioPlayer("Shot.wav");
player2.play();
ButtonToggle = false;
} else {
Chamber++;
CheckNum();
AudioPlayer player = new AudioPlayer("Click.wav");
player.play();
}
}
public void CheckNum() {
if (Chamber > 6) {
Chamber = 1;
}
}
public void reload()
{
//play reload animation
ButtonToggle = true;
}
public void sleep(int ammount)
{
try {
Thread.sleep(ammount);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
So, based on feedback, you want the animation to start running on a button click and stop automatically after a given period of time...
Probably the simplest solution would be to use a javax.swing.Timer, otherwise you'll need to set yourself up as some kind of ImageObserver and interrupt the various events coming from the image...like I said, simpler...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SpiningLabel {
public static void main(String[] args) {
new SpiningLabel();
}
public SpiningLabel() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private ImageIcon spin;
private ImageIcon still;
private JLabel label;
private Timer timer;
private JButton button;
public TestPane() {
spin = new ImageIcon("spin.gif");
still = new ImageIcon("still.png");
label = new JLabel(still);
button = new JButton("Allons-y!");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label.setIcon(spin);
button.setEnabled(false);
timer.restart();
}
});
timer = new Timer(2000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label.setIcon(still);
button.setEnabled(true);
}
});
timer.setRepeats(false);
setLayout(new BorderLayout());
add(label);
add(button, BorderLayout.SOUTH);
}
}
}

Swing - Allowing JButton to always stay on page when scrolling in application

I have this application that I am working on, I have a JFrame that uses a BorderLayout. In the JFrame is a JPanel, the JPanel is using a MigLayout.I am trying to make a JButton stay on the bottom left hand side of the screen , achieving a similar effect as the "position:fixed" property in CSS.
Any tips on how I can achieve this effect by code?
Tried JLayeredPane code from a few other sources, but still doesn't work somehow.
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if (info.getName().equals("Nimbus")) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
MainFrame frame = new MainFrame();
ForumMainPage panel = new ForumMainPage(frame);
panel.setFocusable(true);
panel.requestFocusInWindow();
frame.add(jLabelOnJButton());
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainFrame() {
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension dim = tk.getScreenSize();
this.setSize(dim);
this.setUndecorated(true);
this.setExtendedState(Frame.MAXIMIZED_BOTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
this.add(jLabelOnJButton(),BorderLayout.CENTER);
}
private static JComponent jLabelOnJButton(){
JLayeredPane layers = new JLayeredPane();
JLabel label = new JLabel("label");
JButton button = new JButton("button");
label.setBounds(40, 20, 100, 50);
button.setBounds(100, 20, 150, 75);
layers.add(label, new Integer(200));
layers.add(button, new Integer(100));
return layers;
}
}
Thanks in advance!
You could add the button to the frame's glass pane. This takes a little bit of work to make happen, as you need to keep track of the scroll pane relative to the glass pane, but it should achieve the desired effect
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class OverlayButton {
public static void main(String[] args) {
new OverlayButton();
}
public OverlayButton() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JScrollPane sp;
private JButton btn;
private JTextArea ta;
private JPanel glassPane;
public TestPane() {
setLayout(new BorderLayout());
btn = new JButton("Print");
ta = new JTextArea(10, 20);
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File("Script.txt")));
String text = null;
while ((text = br.readLine()) != null) {
ta.append(text + "\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (Exception e) {
}
}
ta.setCaretPosition(0);
sp = new JScrollPane(ta);
glassPane = new JPanel() {
#Override
public void doLayout() {
Point p = sp.getLocation();
Dimension dim = sp.getSize();
p = SwingUtilities.convertPoint(sp, p, this);
btn.setSize(btn.getPreferredSize());
int barWidth = sp.getVerticalScrollBar().getWidth();
int barHeight = sp.getHorizontalScrollBar().getHeight();
int x = p.x + (dim.width - btn.getWidth()) - barWidth;
int y = p.y + (dim.height - btn.getHeight()) - barHeight;
btn.setLocation(x, y);
}
};
glassPane.setOpaque(false);
glassPane.add(btn);
glassPane.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
e.getComponent().doLayout();
}
});
add(sp);
}
#Override
public void addNotify() {
super.addNotify();
SwingUtilities.getRootPane(this).setGlassPane(glassPane);
glassPane.setVisible(true);
glassPane.revalidate();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.dispose();
}
}
}
Take a look at How to use Root Panes for more details
Try using the OverlayLayout:
JPanel contentPane = new JPanel();
contentPane.setLayout( new OverlayLayout(ContentPane) );
frame.setContentPane( panel );
JButton button = new JButton(...);
button.setAlignmentX(0.0f);
button.setAlignmentY(1.0f);
contentPane.add( button );
ForumMainPage panel = new ForumMainPage(frame);
contentPane.add( panel );

JLayeredPane formatting issue

I have a problem with my JLayeredPane, I am probably doing something incredibly simple but I cannot wrap my head around it. The problem i have is that all the components are merged together and have not order. Could you please rectify this as I have no idea. The order I am trying to do is have a layout like this
output
label1 (behind)
input (in Front)
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class window extends JFrame implements KeyListener {
/**
*
*/
private static final long serialVersionUID = 7092006413113558324L;
private static int NewSize;
public static String MainInput;
public static JLabel label1 = new JLabel();
public static JTextField input = new JTextField(10);
public static JTextArea output = new JTextArea(main.Winx, NewSize);
public window() {
super("Satine. /InDev-01/");
JLabel label1;
NewSize = main.Winy - 20;
setLayout(new BorderLayout());
output.setToolTipText("");
add(input, BorderLayout.PAGE_END);
add(output, BorderLayout.CENTER);
input.addKeyListener(this);
input.requestFocus();
ImageIcon icon = new ImageIcon("C:\\Users\\" + System.getProperty("user.name") + "\\AppData\\Roaming\\.Satine\\img\\textbox.png", "This is the desc");
label1 = new JLabel(icon);
add(label1, BorderLayout.PAGE_END);
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
try {
MainMenu.start();
} catch (IOException e1) {
System.out.print(e1.getCause());
}
}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
}
And the main class.
import java.awt.Container;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
public class main {
public static int Winx, Winy;
private static JLayeredPane lpane = new JLayeredPane();
public static void main(String[] args) throws IOException{
Winx = window.WIDTH;
Winy = window.HEIGHT;
window Mth= new window();
Mth.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Mth.setSize(1280,720);
Mth.setVisible(true);
lpane.add(window.label1);
lpane.add(window.input);
lpane.add(window.output);
lpane.setLayer(window.label1, 2, -1);
lpane.setLayer(window.input, 1, 0);
lpane.setLayer(window.output, 3, 0);
Mth.pack();
}
}
Thank you for your time and I don't expect the code to be written for me, all I want is tips on where I am going wrong.
I recommend that you not use JLayeredPane as the overall layout of your GUI. Use BoxLayout or BorderLayout, and then use the JLayeredPane only where you need layering. Also, when adding components to the JLayeredPane, use the add method that takes a Component and an Integer. Don't call add(...) and then setLayer(...).
Edit: it's ok to use setLayer(...) as you're doing. I've never used this before, but per the API, it's one way to set the layer.
e.g.,
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class LayeredPaneFun extends JPanel {
public static final String IMAGE_PATH = "http://duke.kenai.com/" +
"misc/Bullfight.jpg";
public LayeredPaneFun() {
try {
BufferedImage img = ImageIO.read(new URL(IMAGE_PATH));
ImageIcon icon = new ImageIcon(img);
JLabel backgrndLabel = new JLabel(icon);
backgrndLabel.setSize(backgrndLabel.getPreferredSize());
JPanel forgroundPanel = new JPanel(new GridBagLayout());
forgroundPanel.setOpaque(false);
JLabel fooLabel = new JLabel("Foo");
fooLabel.setFont(fooLabel.getFont().deriveFont(Font.BOLD, 32));
fooLabel.setForeground(Color.cyan);
forgroundPanel.add(fooLabel);
forgroundPanel.add(Box.createRigidArea(new Dimension(50, 50)));
forgroundPanel.add(new JButton("bar"));
forgroundPanel.add(Box.createRigidArea(new Dimension(50, 50)));
forgroundPanel.add(new JTextField(10));
forgroundPanel.setSize(backgrndLabel.getPreferredSize());
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(backgrndLabel.getPreferredSize());
layeredPane.add(backgrndLabel, JLayeredPane.DEFAULT_LAYER);
layeredPane.add(forgroundPanel, JLayeredPane.PALETTE_LAYER);
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(new JScrollPane(new JTextArea("Output", 10, 40)));
add(layeredPane);
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("LayeredPaneFun");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new LayeredPaneFun());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Categories