【发布时间】:2016-07-30 20:56:56
【问题描述】:
我正在使用溢出的面板,其中包含可以在左侧单击然后在右侧显示的图像列表,我的图像有些大。我想让图像可以随窗口大小缩放。因此,如果我将鼠标拖到 EXIT 按钮附近并使窗口变大,则图片会变大,反之亦然。目前我的 JFrame 是 FIXED 默认窗口大小,但即便如此,图像也太大而无法完全看到。
这是我的代码:
驱动类:
import java.awt.*;
import javax.swing.*;
public class PickImage
{
//-----------------------------------------------------------------
// Creates and displays a frame containing a split pane. The
// user selects an image name from the list to be displayed.
//-----------------------------------------------------------------
public static void main(String[] args)
{
JFrame frame = new JFrame("Pick Image");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(500, 300);
JLabel imageLabel = new JLabel();
JPanel imagePanel = new JPanel();
imagePanel.add(imageLabel);
imagePanel.setBackground(Color.white);
ListPanel imageList = new ListPanel(imageLabel);
JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
imageList, imagePanel);
sp.setOneTouchExpandable(true);
frame.getContentPane().add(sp);
frame.setVisible(true);
}
}
ListPanel 类:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class ListPanel extends JPanel
{
private JLabel label;
private JList list;
public ListPanel(JLabel imageLabel)
{
label = imageLabel;
String[] fileNames = { "Denali2.jpg",
"denali.jpg",
"MauiLaPerouseBay.jpg",
};
list = new JList(fileNames);
list.addListSelectionListener(new ListListener());
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
add(list);
setBackground(Color.white);
}
private class ListListener implements ListSelectionListener
{
public void valueChanged(ListSelectionEvent event)
{
if (list.isSelectionEmpty())
label.setIcon(null);
else
{
String fileName = (String)list.getSelectedValue();
ImageIcon image = new ImageIcon(fileName);
label.setIcon(image);
}
}
}
}
【问题讨论】:
标签: java swing user-interface jframe jpanel