【发布时间】:2017-10-11 17:33:24
【问题描述】:
不确定我是否将其添加到错误的图层。可能不止一些错误。我将它添加到小程序中,因为我将删除 JFrame。 JFrame 仅用于测试目的。我不知道我是否设置了滚动窗格错误或什么。最终目标是通过按钮将图片添加到jpanel,并且如果它大于面板,则能够滚动。
public class main {
public static JFrame f = new JFrame();
public static JApplet a = new JApplet();
public static JPanel p = new JPanel();
public static JButton b = new JButton();
public static JScrollPane pane = new JScrollPane(p, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
public static JLabel gameimage;
public static void main(String[] args) {
f.setSize(1000,800);
a.setBounds(0,0,1000,800);
a.setVisible(true);
a.setBackground(Color.WHITE);
p.setBounds(0, 0, 1000, 800);
p.setVisible(true);
p.setBackground(Color.WHITE);
p.setLayout(null);
p.setOpaque(true);
pane.getVerticalScrollBar();
pane.getHorizontalScrollBar();
pane.setVisible(true);
b.setBounds(955, 0, 40, 30);
b.setText("+");
b.setFont(new Font("Times Roman", Font.BOLD, 30));
b.setVisible(true);
b.setBorder(javax.swing.BorderFactory.createLineBorder(Color.WHITE));
b.setBackground(Color.WHITE);
b.setForeground(Color.GREEN);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JFileChooser file = new JFileChooser();
file.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
file.setAcceptAllFileFilterUsed(true);
if(file.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
int width;
int height;
File f = file.getSelectedFile();
try {
BufferedImage bimg = ImageIO.read(new File(f.getAbsolutePath()));
width = bimg.getWidth();
height = bimg.getHeight();
String fname = f.getAbsolutePath();
gameimage = new JLabel("", new ImageIcon(fname), JLabel.CENTER);
gameimage.setSize(width,height);
gameimage.setOpaque(true);
a.revalidate();
a.repaint();
p.removeAll();
p.revalidate();
p.repaint();
pane.revalidate();
pane.repaint();
p.setSize(width,height);
p.add(gameimage);
p.add(b);
//p.add(pane);
a.getContentPane().add(pane);
}catch(IOException ioe) {
}
}else {
System.out.println("not working");
}
}
});
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.setResizable(false);
f.add(a);
a.add(p);
p.add(b);
}
}
【问题讨论】:
-
请创建一个minimal reproducible example。目前有很多东西可能不会导致问题。程序越小,人们就越有可能尝试使用它来解决问题。另一个建议:通过tour 稍微了解一下该网站。欢迎来到 SO
-
不要使用
null布局。 -
最后调用
f.setVisible(true);- 另外,仅在更改后对您实际更改的容器调用revalidate/repaint -
“我将它添加到小程序中是因为我将删除 JFrame” - 这似乎毫无意义,因为小程序不再受支持并且已被弃用
-
JScrollPanes 在视口组件上中继,通过preferred/minimum/maximum属性提供大小提示,通常由LayoutManagers 提供,通过使用您已有效删除的null布局支持