初始化執行後如圖1
拖動之後如圖2
為什麼不能初始化顯示成圖2的樣子
代碼如下:
package com.yeeda.pollyover;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
public class PollyoverFrame extends JFrame{
static final int WIDTH=1000;
static final int HEIGHT=800;
JPanel jpanelMain = new JPanel();
PollyoverFrame(){
super("測試");
setSize(WIDTH,HEIGHT);
//激活窗體的關閉按鈕
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//設置窗體的初始化位置(屏幕中央)
Toolkit kit=Toolkit.getDefaultToolkit();
Dimension screenSize=kit.getScreenSize();
int width=screenSize.width;
int height=screenSize.height;
int x=(width-WIDTH)/2;
int y=(height-HEIGHT)/2;
setLocation(x,y);
setVisible(true);
//setResizable(false);
//設置窗體分割
final JSplitPane hSplitPane = new JSplitPane();
JPanel leftPanel = new LeftPanel();
JPanel mainPanel = new MainPanel();
hSplitPane.setLeftComponent(leftPanel);
hSplitPane.setRightComponent(mainPanel);
hSplitPane.setDividerLocation(200);
hSplitPane.setOneTouchExpandable(false);
getContentPane().add(hSplitPane);
}
public static void main(String[] args) {
PollyoverFrame pollyoverFrame = new PollyoverFrame();
}
}
package com.yeeda.pollyover;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class LeftPanel extends JPanel {
LeftPanel() {
//獲取圖片並設置圖片的大小
ImageIcon image = new ImageIcon(
LeftPanel.class.getResource("butterfly.jpg"));
image.setImage(image.getImage().getScaledInstance(40, 40,
Image.SCALE_DEFAULT));
//將圖片添加到JLabel
JLabel picLabel = new JLabel(image);
JLabel picLabel2 = new JLabel("測試");
add(picLabel);
add(picLabel2);
}
}
package com.yeeda.pollyover;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainPanel extends JPanel {
MainPanel(){
JButton ok=new JButton("搭配");
JButton cancel=new JButton("混搭");
add(ok);
add(cancel);
}
}
解決方案:
//在這裡添加
pollyoverFrame.setVisible(true);
public static void main(String[] args) {
PollyoverFrame pollyoverFrame = new PollyoverFrame();
//在這裡添加
pollyoverFrame.setVisible(true);
}