【发布时间】:2014-08-23 17:42:10
【问题描述】:
我为我的作业编写了一个程序来使用 swing/awt 框架组成一个 GUI。到目前为止,我能够让这些部分一起工作,但是当我将它们全部放入 JFrame 时,它们并没有按预期出现。
我最近开始研究 Java GUI 框架,但不确定我的代码中缺少什么。我怎样才能让它正常工作?
我还附上了我得到的输出的屏幕截图(见底部)。
public class MainFrame extends JFrame {
public MainFrame() {
addComponentsToPane(this.getContentPane());
}
private void addComponentsToPane(Container pane) {
// Set layout
GridBagConstraints gbc = new GridBagConstraints();
this.setTitle("Test tool");
this.setSize(600, 650);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(2, 1));
// Add video JComponent
mMainPanel = new MainPanel();
pane.add(mMainPanel, 0);
// Add conference screen panel
mFeedPanel = new FeedPanel();
pane.add(mFeedPanel, 1);
// Add a button panel
mButtonPanel = new ButtonPanel();
pane.add(mButtonPanel, 2);
this.setResizable(true);
this.setVisible(true);
this.pack();
}
}
// In actual output, there is 1 screen in this panel.
// mScreen1 is derived from JComponent object.
public class MainPanel() extends JPanel {
public MainPanel() {
addMainPanelComponents();
}
private void addMainPanelComponents() {
this.setSize(352, 240);
setBackground(Color.yellow);
setLayout(new GridLayout(1, 2));
add(mScreen);
setVisible(true);
}
}
// In actual output, there are 3 screens in this panel. I have shown code for 1 screen only
// mScreen1 is derived from JComponent object.
public class FeedPanel extends JPanel {
public FeedPanel() {
addFeedPanelComponents();
}
private void addFeedPanelComponents() {
String img1 = "images/screen1.png";
setSize(352, 150);
setBackground(Color.yellow);
setLayout(new GridLayout(1, 3));
Image image1 = ImageIO.read(new File(img1));
mScreen1.setImage(image1);
add(mScreen1);
setVisible(true);
}
}
public class ButtonPanel extends JPanel {
public ButtonPanel() {
addButtonPanelComponents();
}
private void addButtonPanelComponents() {
this.setSize(352, 150);
this.setBackground(Color.yellow);
this.setLayout(new GridLayout(1,
5));
// Add Button to panel
mStartButton = new JButton("Start");
this.add(mStartButton);
mStartButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
StartButtonActionListener(ae);
}
});
mStopButton = new JButton("Stop");
this.add(mStopButton);
mStopButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
StopButtonActionListener(ae);
}
});
setVisible(true);
}
}
这是在运行代码时默认出现的。
这是在手动调整框架大小之后发生的。
【问题讨论】:
-
您确定您指定的帧大小正确吗?据我所知,图像大小超过了您指定的帧大小的 75%。
-
刚刚将我使用的实际帧大小添加到代码中,但结果仍然相同。 FeedPanel 在其网格布局中包含 3 个图像。那么这是否意味着帧宽度应该是图像大小的 3 倍?
-
请问您为什么不使用 GridLayout 并通过进行一些更改来降低代码的复杂性?
-
另外,在将 ButtonPanel 添加到大型机 (JFrame) 之前,我正在将按钮添加到它自己的面板中。然而,在调整窗口大小时,按钮也会调整大小。
-
我正在为 MainFrame 使用 GridLayout。如果您错过了这条线,请查看。 this.setLayout(new GridLayout(2, 1));
标签: java swing user-interface awt layout-manager