我下面的Java代码应该只放置一个图像和一个按钮,现在此代码可以编译,但是该按钮是唯一显示的东西。我看不到图像。我希望图像覆盖屏幕的90%,按钮覆盖屏幕的另外10%。
import java.awt.BorderLayout;
import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
class Main extends JFrame {
public static void main(String[] args0) {
try {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg");
ImageIcon image= new ImageIcon(url);
JLabel imageLabel = new JLabel(image);
frame.add(imageLabel);
JButton b=new JButton("Click Here");
frame.add(b);
b.setBounds(50,100,95,30);
b.add.setSize(400,400);
frame.pack();
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}}
首先读取Laying Out Components Within a Container和How to Use BorderLayout,这是JFrame
使用的默认布局
例如,我会考虑使用GridBagLayout
(作为起点)...
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
class Main extends JFrame {
public static void main(String[] args0) {
try {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 0.9;
gbc.weighty = 0.9;
gbc.fill = GridBagConstraints.BOTH;
URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg");
ImageIcon image = new ImageIcon(url);
JLabel imageLabel = new JLabel(image);
frame.add(imageLabel, gbc);
gbc.weightx = 0.9;
gbc.weighty = 0.1;
gbc.fill = GridBagConstraints.NONE;
JButton b = new JButton("Click Here");
frame.add(b, gbc);
frame.pack();
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
}
但是,您会发现调整框架大小时,图像没有,这是因为JLabel
不支持此功能
个人,我将滚动自己的组件,该组件可以按照我想要的方式调整图像的大小。例如,请参见Java: maintaining aspect ratio of JPanel background image