我正在努力使用Swing中的FlowLayout管理器放置一些简单的对象。
基本上我已经创建了一个小程序,我设置了框架的大小,然后装箱了一些JLabels,然后是一个JPanel。
我给 JPanel 放了一个 300x300 的 setSize,并将其颜色更改为红色以直观地看到它。但是,它占用了 JFrame 的整个空间,并且似乎设置大小对它没有影响。
我做错了什么?我尝试在谷歌上搜索它并多次更改代码,但没有运气。我什至阅读了,但显然没有正确理解,预言机上的代码...... 请帮忙。下面是我到目前为止的代码。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Main extends JFrame{
public String frameTitle, projectNameString, countryNameString, projectDetailString, requestDateString;
private int offerRevisionVal;
private Toolkit toolkit;
// UPPER OBJECTS
//private JLabel projectLabel, countryLabel, projectDetailLabel, offerLabel, requestDateLabel, emptyLabel;
public Main(){
frameTitle = "CRANES QUOTATIONS";
// MAIN INSTANCE VARIABLES DEFINITION
projectNameString = "Project Title"; // TO ADD LATER
countryNameString = "Brazil"; // TO ADD LATER
projectDetailString = "32 Cranes biTravi"; // TO ADD LATER
offerRevisionVal = 01; // TO ADD LATER
requestDateString = "20-April-2017"; // tTO ADD LATER
this.setTitle(frameTitle);
JPanel panel = new JPanel();
panel.setBackground(Color.red);
panel.setSize(new Dimension(300,300));
//projectLabel = new JLabel(projectNameString);
//countryLabel = new JLabel(countryNameString);
//projectDetailLabel = new JLabel(projectDetailString);
//offerLabel = new JLabel(String.valueOf(offerRevisionVal));
//requestDateLabel = new JLabel(requestDateString);
this.add(panel);
// ===========================================================================
this.setSize(800, 300); // set the height and width of my window
this.centerToScreen ();
this.setVisible(true); // set visibility
this.setDefaultCloseOperation(EXIT_ON_CLOSE); // sets up what it does when I close the App.
}
// Method to center to screen
public void centerToScreen (){
toolkit = getToolkit();
Dimension size = toolkit.getScreenSize(); // gets the screen size
setLocation(size.width / 2 - getWidth() / 2, size.height / 2 - getHeight() / 2); // sets the location
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
new Main();
}
});
}
}
JFrame
使用BorderLayout
作为默认LayoutManager
。因此,您需要将JFrame
的布局隐式设置为FlowLayout
:
this.setLayout(new FlowLayout());
你还需要在panel
上使用setPreferredSize()
而不是setSize()
,因为如果你panel
(JFrame
)的容器具有非空LayoutManager
setSize()
则不起作用。