How to move JButtons and JLabels position in a JPanel, JFrame

瘦欲@ 提交于 2019-12-23 03:38:15

问题


I am creating a simple lottery as a practice, I am a beginner of Java. I have achieved almost everything that I want apart from one thing: Moving the different texts and buttons to the position that I'd like them to be.

Here is a picture edited in Photoshop describing how I would like it to be:

The Lottery currently looks like this after you press the Play button:

(As you can see the buttons get shifted to the right in order to make space for the text that is squished in to the left of the buttons)

What I'm looking to achieve is for the buttons position to never move, and to put the text under the buttons.

I would also like to add a table that describes your potential winnings and what number will give you what winnings.

The code consists of 2 Java Classes, and please remember that I am a beginner and if you see any simple room for improvement (I know there must be plenty) I would be glad if you gave me a tips or anything :)

So this is the code:

LotteryMain.Java

public class LotteryMain {
/**
 **@author Samy
 */
public static void main(String[] args) {

    TheLottery n = new TheLottery();
    n.TheLottery();

}
}

TheLottery.java

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EtchedBorder;

public class TheLottery extends JFrame implements ActionListener {
/**
 **author Samy
 */

JFrame frame = new JFrame("The Lottery");
JPanel panel = new JPanel(new FlowLayout());
JButton play = new JButton("Play");
JButton exit = new JButton("Exit");
JLabel label = new JLabel();

private static final long serialVersionUID = 1L;



public void TheLottery() {


    panel.add(label);

    int width = 720;
    int height = width/16*9;

    frame.setSize(width,height);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setUndecorated(true);
    frame.add(panel);

    panel.setBackground(new Color(0x222222));
    panel.setBorder(new EtchedBorder(new Color(0xAAAAAA),new Color(0x666666)));
    panel.add(play);
    panel.add(exit);



    play.addActionListener(this);
    exit.addActionListener(this);

    play.setToolTipText("Click me to play the lottery!");
    exit.setToolTipText("Click me to exit.");

    frame.setVisible(true);

}



@Override
public void actionPerformed(ActionEvent e) {

    Object action = e.getSource();

    String winnings = null;
    double lotteryChance = Math.random()*100;

    if(action == play) {

        if (lotteryChance > 80) {
            winnings = ("You lost! Luckily this lottery is free to play.");
        } else if (lotteryChance < 80 && lotteryChance > 50) {
            winnings = ("You've won $100!");
        } else if (lotteryChance < 50 && lotteryChance > 20) {
            winnings = ("You've won $500!");
        } else if (lotteryChance < 20 && lotteryChance > 5) {
            winnings = ("You've won $2,000!");
        } else if (lotteryChance < 5 && lotteryChance > 1) {
            winnings = ("You've won $5,000!");
        } else if (lotteryChance < 1 && lotteryChance > 0.1) {
            winnings = ("You've won $25,000!");
        } else if (lotteryChance < 0.1 && lotteryChance > 0.01) {
            winnings = ("You've won $50,000!");
        } else if (lotteryChance < 0.01 && lotteryChance > 0.001) {
            winnings = ("You've won $250,000!");
        } else if (lotteryChance < 0.001 && lotteryChance > 0) {
            winnings = ("YOU'VE WON THE JACKPOT OF $1,000,000!");
        } else winnings = ("Something went wrong, no winnings this round.");


        System.out.println("Your number is: "+lotteryChance);
        System.out.println(winnings);   
    }   
    if(action == exit) {
        System.exit(1);
    }
    label.setText("<html><font color='white'>Your number is: "+lotteryChance+" -                                               "+winnings+"</font></html>");

}
}

回答1:


Instead of using a FlowLayout, which rearranges items automatically based on their sizes and the window size, you can use a BorderLayout or GridLayout. A BorderLayout basically splits the window into 5 areas, each border is a separate area identified with a cardinal direction (north, east, etc.), and the center is it's own area as well. A GridLayout allows you to specify if you want a particular number of rows/columns, while letting the other expand as necessary (n elements into 2 columns, for example).

From the look of your photoshopped desired outcome, you can use a BorderLayout for the main frame, with the buttons in the north, the number/results in the center, and the table in the south. Also remember that you can put a panel in a layout area, with that panel having its own layout, such as a GridLayout for the buttons in the north, or even better, for the table in the south. Hope that helps!

Some code to assist you:

JFrame frame = new JFrame("The Lottery");
JPanel mainPanel = new JPanel(new BorderLayout());

JPanel northPanel = new JPanel();
JButton play = new JButton("Play");
JButton exit = new JButton("Exit");
northPanel.add(play);
northPanel.add(exit);
mainPanel.add(northPanel, BorderLayout.NORTH);



回答2:


What I'm looking to achieve is for the buttons position to never move, and to put the text under the buttons.

JPanel by default use FlowLayout that adds the component one after another. You can use multiple JPanel as well and add in another ``JPanel`.

If you want to display text below the button then use BorderLayout or GridBagLayout.

It's worth reading Swing Tutorial on How to Use Various Layout Managers

Sample code:

JPanel topPanel = new JPanel();
topPanel.add(new JButton("Play"));
topPanel.add(new JButton("Exit"));

JPanel panel = new JPanel(new BorderLayout());
panel.add(topPanel, BorderLayout.NORTH);
panel.add(new JLabel("Hello", JLabel.CENTER));

snapshot:



来源:https://stackoverflow.com/questions/24843611/how-to-move-jbuttons-and-jlabels-position-in-a-jpanel-jframe

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