【发布时间】:2017-08-14 00:09:07
【问题描述】:
我最近开始使用 JComponents 创建 GUI 系统。一切正常,但 JFrame 的底部和右侧没有被涂漆并保持白色。
运行界面截图:
在屏幕截图中,您可以看到“drknBtn”正确显示;这是因为我在拍照之前用鼠标悬停在它上面。将鼠标悬停在按钮上会刷新它们,它们会正常显示。因此,我假设包含它们的面板“bottomPnl”覆盖了该空白区域,但该面板背景未显示在底部。关于可能导致这种情况的任何想法?我曾尝试在调用 pack() 之前直接调用 'bottomPnl.repaint()',但没有任何变化。
我的代码如下。 注意:对于每个 JComponent,我创建了一个扩展该组件的类。这样我就可以在这些类的构造函数中为组件设置默认值,而不是单独做每一个。我将列出框架和面板的相关属性。 框架:setSize(宽度,高度);可调整大小(假); setLocationRelativeTo(null); 面板:setLayoutManager(来自建造者); setPreferredSize(new Dimension(width,height)); setMinimumSize 和 setMaximumSize 相同。
public Display(String title, int w, int h){
width=w;
height=h;
frame = new FrameUI(title,w,h);
//parent panel
parentPnl= new PanelUI(width,height, new FlowLayout(FlowLayout.CENTER,0,0));
parentPnl.setBackground(new Color(100,175,175));
//top panel
topPnl= new PanelUI(width,(int)(height*.15), new FlowLayout(FlowLayout.CENTER,0,0));
topPnl.setBackground(new Color(100,175,175));
chooseFileBtn = new ButtonUI("Browse...",topPnl.getWidth()/4,(int)(topPnl.getHeight()*.9),new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
fc = new FileChooserUI();
fc.setFileFilter(new FileNameExtensionFilter("Image files", ImageIO.getReaderFileSuffixes()));
int result = fc.showOpenDialog(null);
try {
if (result == JFileChooser.APPROVE_OPTION) {
picture.setIcon(new ImageIcon(ImageIO.read(fc.getSelectedFile()).getScaledInstance(picture.getWidth(),picture.getHeight(), 0)));
}
} catch (Exception iOException) {
}
}
});
//middle panel
midPnl= new PanelUI((int)(width*.85),(int)(height*.7), new FlowLayout(FlowLayout.CENTER,0,0));
midPnl.setBackground(new Color(75,125,125));
picture = new LabelUI("",midPnl.getWidth(),midPnl.getHeight());
picture.setBackground(new Color(75,125,125));
picture.setVisible(true);
picture.setOpaque(true);
picture.setIcon(null);
//bottom panel
bottomPnl= new PanelUI(width,(int)(height*.15), new FlowLayout(FlowLayout.CENTER,0,0));
bottomPnl.setBackground(new Color(100,175,175));
ltnBtn = new ButtonUI("Lighten Picture",bottomPnl.getWidth()/3,(int)(bottomPnl.getHeight()*.9),new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
}
});
ltnBtn.setBackground(Color.LIGHT_GRAY);
ltnBtn.setForeground(Color.BLACK);
drknBtn = new ButtonUI("Darken Picture",bottomPnl.getWidth()/3,(int)(bottomPnl.getHeight()*.9),new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
}
});
drknBtn.setBackground(Color.DARK_GRAY);
drknBtn.setForeground(Color.WHITE);
//add UI Objects
topPnl.add(chooseFileBtn);
midPnl.add(picture);
bottomPnl.add(ltnBtn);
bottomPnl.add(drknBtn);
parentPnl.add(topPnl);
parentPnl.add(midPnl);
parentPnl.add(bottomPnl);
Container contentPane = frame.getContentPane();
contentPane.add(parentPnl);
frame.pack();
frame.setVisible(true);
}
}
【问题讨论】:
-
我的第一个猜测是你正在使用
null布局,我的第二个猜测是你已经覆盖了paint或paintComponent并且未能调用他们的super方法
标签: java swing jcomponent