本文主要是介绍【好文章】JScrollPane JPanel FlowLayout自动换行,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
今天上午没什么事儿,打开CSDN的BBS,发现有人在问一个关于布局管理器的问题,请看:关于布局的一个问题 。说实话,开始我并不相信楼主说的这句话“然后我在JPanel外面套了一个JScrollPane,却发现图片会一直往右边加,超出JPanel的宽度则出现横向的滚动条,与预想的效果相差较大。”
于是写下下面的代码:
view plaincopy to clipboardprint?
01.import java.awt.*;
02.import java.awt.event.*;
03.import javax.swing.*;
04.
05.
06.public class SimpleTest extends JFrame{
07. private ImageIcon image;
08. private JLabel label;
09. private JButton button;
10. private JPanel buttonPanel, imagePanel;
11. private JScrollPane scrollPane;
12. private Container container;
13.
14. public SimpleTest(int xPixels, int yPixels){
15. super("Add Image");
16.
17. button = new JButton("Add Image");
18. image = new ImageIcon("C:/1.jpg");
19. imagePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
20. scrollPane = new JScrollPane(imagePanel);
21.
22. button.addActionListener(new ActionListener(){
23. public void actionPerformed(ActionEvent e){
24. label = new JLabel(image);
25. imagePanel.add(label);
26. validate();
27. }
28. });
29.
30. buttonPanel = new JPanel(new GridLayout(1, 5));
31. buttonPanel.add(button);
32.
33. container = getContentPane();
34. container.setLayout(new GridLayout(2, 1));
35.
36. container.add(buttonPanel);
37. container.add(scrollPane);
38.
39. setSize(xPixels, yPixels);
40. setVisible(true);
41. }
42.
43. public static void main(String[] args) {
44. new SimpleTest(400, 400);
45. }
46.}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimpleTest extends JFrame{
private ImageIcon image;
private JLabel label;
private JButton button;
private JPanel buttonPanel, imagePanel;
private JScrollPane scrollPane;
private Container container;
public SimpleTest(int xPixels, int yPixels){
super("Add Image");
button = new JButton("Add Image");
image = new ImageIcon("C:/1.jpg");
imagePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
scrollPane = new JScrollPane(imagePanel);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
label = new JLabel(image);
imagePanel.add(label);
validate();
}
});
buttonPanel = new JPanel(new GridLayout(1, 5));
buttonPanel.add(button);
container = getContentPane();
container.setLayout(new GridLayout(2, 1));
container.add(buttonPanel);
container.add(scrollPane);
setSize(xPixels, yPixels);
setVisible(true);
}
public static void main(String[] args) {
new SimpleTest(400, 400);
}
}
输出请看图:
这篇关于【好文章】JScrollPane JPanel FlowLayout自动换行的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!