[英]Swing showing white box when I try to add more than one component on frame
我正在開發java swing應用程序。 我嘗試在主JFrame上添加2個JPanels。
我的主要JPanel類別:
public class DrawingPanel extends JPanel {
//mouse variables here
//Point mPt = new Point(0,0);
public DrawingPanel() {
setBackground(COLOURBACK);
MyMouseListener ml = new MyMouseListener();
addMouseListener(ml);
}
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
....
....
....
}
當我添加為主框架上的唯一組件時,它工作正常。 但是,當我嘗試在框架上添加另一個JPanel時,我的DrawingPanel顯示為小白框。
private void createAndShowGUI()
{
DrawingPanel panel = new DrawingPanel();
JFrame frame = new JFrame("Hex Testing 4");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
Container content = frame.getContentPane();
JPanel aggregationFrame = new JPanel(new GridBagLayout());
aggregationFrame.add(panel);
aggregationFrame.add(new JLabel("Enter username:"));
content.add(aggregationFrame);
//this.add(panel); -- cannot be done in a static context
//for hexes in the FLAT orientation, the height of a 10x10 grid is 1.1764 * the width. (from h / (s+t))
frame.setSize( (int)(SCRSIZE/1.23), SCRSIZE);
frame.setResizable(false);
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
看起來像這樣
我試圖將getPreferredSize()方法添加到DrawingPanel中,如在JPanel中建議的那樣,它顯示為一個小白盒問題,但效果不佳。
你能幫我解決這個問題嗎?
更新:
我已經更改了布局,現在我看到了我的JPanel的一半。 我認為問題與JPanels和JFrame的固定大小有關。 會調查的。
因此,我拿走了您的上下文外代碼,將一個可運行的變體弄亂了,……沒有問題。 這表明問題出在您未向我們顯示的代碼中。 與其發布不完整代碼的“片段”(這會引發更多問題), 不如發布一個“ 最小,完整和可驗證”的示例 ,該示例可以編譯並運行,以演示您遇到的問題
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
DrawingPanel panel = new DrawingPanel();
JFrame frame = new JFrame("Hex Testing 4");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = frame.getContentPane();
JPanel aggregationFrame = new JPanel(new GridBagLayout());
aggregationFrame.add(panel);
aggregationFrame.add(new JLabel("Enter username:"));
content.add(aggregationFrame);
//this.add(panel); -- cannot be done in a static context
//for hexes in the FLAT orientation, the height of a 10x10 grid is 1.1764 * the width. (from h / (s+t))
frame.pack();
//frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DrawingPanel extends JPanel {
//mouse variables here
//Point mPt = new Point(0,0);
private int width = 200;
private int height = 200;
public DrawingPanel() {
setBackground(Color.BLACK);
// MyMouseListener ml = new MyMouseListener();
// addMouseListener(ml);
}
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
}
}
問題出在我的零件尺寸上。 好像它不適合主機架並被切割了。 我設置了動態幀大小,現在效果很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.