How do I make other jlabels stay in place when I scroll the main jlabel with the image? If I scroll down the labels don't stay, they move with the scroll. How do I solve this?
import java.awt.*;
import javax.swing.*;
public class NewJFrame extends javax.swing.JFrame {
JPanel pan = (JPanel) this.getContentPane();
public NewJFrame() {
initComponents();
pan.setLayout(null);
setSize(1050,700);
setTitle("Scroll Image");
setResizable(false);
JLabel background = new JLabel();
background.setIcon(new javax.swing.ImageIcon(getClass().getResource("Main.png")));
JLabel lab1 = new JLabel();
lab1.setBounds(new Rectangle(153, 350, 140, 200));
lab1.setText("Text1");
JLabel lab2 = new JLabel();
lab2.setBounds(new Rectangle(553, 350, 140, 200));
lab2.setText("Text2");
JScrollPane scroll = new JScrollPane(background);
scroll.setBounds(new Rectangle(0, 0, 1050, 690));
pan.add(lab1);
pan.add(lab2);
add(scroll);
}
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class Test extends javax.swing.JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
Test frame = new Test();
frame.setSize(250, 250);
frame.setVisible(true);
}
});
}
public Test() {
setTitle("Scroll Image");
BufferedImage img = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, 500, 500);
g2d.setColor(Color.RED);
g2d.drawLine(0, 0, 500, 500);
g2d.drawLine(500, 0, 0, 500);
g2d.dispose();
JLabel background = new JLabel();
background.setIcon(new ImageIcon(img));
JLabel lab1 = new JLabel();
lab1.setBounds(new Rectangle(153, 350, 140, 200));
lab1.setText("Text1");
JLabel lab2 = new JLabel();
lab2.setBounds(new Rectangle(553, 350, 140, 200));
lab2.setText("Text2");
JScrollPane scroll = new JScrollPane(background);
JPanel glassPane = new JPanel(null);
glassPane.setOpaque(false);
glassPane.add(lab1);
glassPane.add(lab2);
setGlassPane(glassPane);
glassPane.setVisible(true);
add(scroll);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.