开发者

How to Set Multiple Components Visible on a JFrame?

When I add more than one component on the JFrame , only the component which was added last is displayed , rest are not displayed , what is the issue with their visibility ?

import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
public class CenteringaWindow {
public static void main(String[] args) {
 JFrame aWindow = new JFrame("This is the Window Title");
 Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
 int windowWidth = 400;
 int win开发者_如何学JAVAdowHeight = 150;
 JButton item1=new JButton("hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii");
 JButton item2=new JButton("how are you ?");
 aWindow.add(item1);
 aWindow.add(item2);
 JLabel label1=new JLabel("Label 1");
 aWindow.add(label1);
 JLabel label2=new JLabel("Label 2");
 aWindow.add(label2);
 //center align the JFrame
 aWindow.setLocationRelativeTo(null);
 aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 aWindow.setVisible(true); // Display the window

} }


You should be declaring a JPanel, adding the JPanel to the JFrame, then adding the items to the JPanel.

Example:

JPanel pnl = new JPanel();

public static void main(String[] args) {
     aWindow.add(pnl);
         pnl.add(item1);
         pnl.add(item2);
         pnl.add(label1);
         pnl.add(label2);
}


You need to set a LayoutManager appropriate to your needs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜