我正在努力使用Swing中的FlowLayout管理器放置一些简单的对象。
基本上我已经创建了一个小程序,我已经设置了框架的大小,然后创建了一些JLabel,然后是一个JPanel。
我已经将JPanel的setSize设置为300x300,并将其颜色更改为红色以便直观地看到它。然而,它占用了JFrame的整个空间,似乎setize对它没有影响。
我做错了什么?我尝试使用Google搜索并多次更改代码,但没有运气。我甚至读过,但显然没有正确理解,oracle上的代码...... 请帮忙。到目前为止,下面是我的代码。
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();
}
});
}
}
答案 0 :(得分:1)
JFrame
使用BorderLayout
作为默认LayoutManager
。因此,您需要隐式设置JFrame
到FlowLayout
的布局:
this.setLayout(new FlowLayout());
您还需要在setPreferredSize()
上使用setSize()
而不是panel
,因为setSize()
对panel
的容器无效JFrame
LayoutManager
}})具有非空char
。