我试图用java创建一个GUI。我的gui会很简单。你可以在这里看到我想要的东西:http://sketchtoy.com/64839370
为了做到这一点,我决定按照网络上的建议使用BorderLayout。我有两个Jpanel对象,我已将它们放入jFrame,其布局为borderlayout。您可以在下面看到我的简化代码:
private Display display= new Display(); // Display extends JPanel
public Simulation()
{
super();
// frame settings
setTitle("Label of JFrame ");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBounds(100,100,1094,560);
contentPane=this.getContentPane();
setResizable(false);
contentPane.setLayout(new BorderLayout());
try {
LeftPanelLogo=ImageIO.read(new File("logo.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// generate left panel (information panel)
leftPanel=new JPanel(){
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
g2d.drawImage(LeftPanelLogo, 10, 250, null);
}
};
//leftPanel.setLayout(null);
// add panels to contentPane
leftPanel.setBackground(Color.WHITE);
display.setBackground(Color.BLACK);
contentPane.add(leftPanel,BorderLayout.WEST);
contentPane.add(display,BorderLayout.CENTER);
}
在Display类构造函数中,我只有以下代码:
try
{
bgPicture = ImageIO.read(new File("bg.jpg"));
}
catch (IOException e)
{
e.printStackTrace();
}
当我运行代码时,我看到几乎所有的屏幕都在中心的面板上完成,我看不到左侧面板(换句话说,所有屏幕都是黑色的,因为我设置了背景显示面板为黑色)
那么,我该怎么办呢?
答案 0 :(得分:1)
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class LogoLayout {
private JComponent ui = null;
LogoLayout() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
BufferedImage logo = new BufferedImage(
276,560,BufferedImage.TYPE_INT_RGB);
/* All that's needed */
ui.add(new JLabel(new ImageIcon(logo)), BorderLayout.LINE_START);
ui.add(new JTextArea("Display", 3, 44));
/* All that's needed */
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
LogoLayout o = new LogoLayout();
JFrame f = new JFrame("Logo Layout");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}