Trying to put button and using center mode

2019-08-23 10:12发布

问题:

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.



标签: java swing awt