Trying to put button and using center mode

一个人想着一个人 提交于 2020-01-25 07:29:49

问题


Im trying to make a option menu to be able to choose flags to be displayed, Im trying to put the tailand button on the left down corner and it seems it does not want to budge.

import java.awt.*;
import javax.swing.*;

public class Flags {
public static void startup() {
    Dimension d = new Dimension(400,300);
    JFrame menu = new JFrame("Flag Menu");
    menu.setResizable(true);
    JButton tailand = new JButton("Tailand");
    JPanel tailandPanel = new JPanel();
    tailand.setLayout(null);
    tailandPanel.setLayout(null);


    tailand.setBounds(300,100,100,600);
    tailandPanel.add(tailand);
    menu.add(tailandPanel);
    tailandPanel.setBackground(Color.LIGHT_GRAY);
    tailand.setBackground(Color.WHITE);
    tailandPanel.setPreferredSize(d);
    tailand.setPreferredSize(d);
    tailandPanel.setLocation(1, 1);
    tailand.setLocation(1, 1);
    menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    menu.setLocationRelativeTo(null);
    menu.setSize(600, 400);
    menu.setResizable(false);
    menu.setVisible(true);
    menu.setLocationRelativeTo(null);
}
}

I have tried tailand.setPreferredSize(d); and tailandpanel.setPreferredSize(d); but no luck. Also Is their a way to use center mode? (Eg. Give 300,200 and the center of the button would be their?)


回答1:


  1. Don't use null layouts
  2. Don't use setPreferredSize(...)

Swing was designed to be used with layout managers

For example:

JButton button = new JButton( "Tailand" );

JPanel left = new JPanel( new BorderLayout() );
left.setBackground( Color.WHITE );
left.add(button, BorderLayout.PAGE_END);

JFrame frame = new JFrame("Flag Menu");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frane.setLocationRelativeTo(null);
frame.add(left, BorderLayout.LINE_START);
frame.setSize(600, 400);
frame.setVisible(true);

Read the section from the Swing tutorial on Layout Manager for more information and example of using each layout manager.



来源:https://stackoverflow.com/questions/53416295/trying-to-put-button-and-using-center-mode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!