Home > Net >  Java how to bottom align button and filter label to right
Java how to bottom align button and filter label to right

Time:11-11

Hi I am trying to make a GUI using Javax to look something like this. enter image description here

But currently it looks like this enter image description here

This is my code

class Intro extends JFrame implements ActionListener
{
    JFrame frame = new JFrame();
    JButton ok;
    JLabel background;
    JLabel demo;
    
    public Intro()
    {
        
        frame.setTitle("Let us start");
        frame.setSize(600,300);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        frame.setContentPane(new JLabel(new ImageIcon("welcome.gif")));
        frame.setLayout(new FlowLayout());
        background = new JLabel();
        frame.add(background);
        frame.setSize(500,400);
        ok = new JButton("OK");
        demo = new JLabel("CSIT 121 Demo System", SwingConstants.RIGHT);
        frame.add(demo);
        ok.setHorizontalTextPosition(JButton.CENTER);
        ok.setVerticalTextPosition(JButton.BOTTOM);
        frame.add(ok);
        
        
        
    }

}

What do i need to modify?

CodePudding user response:

You should use another layout. Here is the correct example:

public class Intro extends JFrame {
    JFrame frame = new JFrame();

    JButton ok;

    JLabel background;

    JLabel demo;

    public Intro() {

        frame.setTitle("Let us start");
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel contentPane = new JLabel(new ImageIcon("welcome.gif"));
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        frame.setContentPane(contentPane);
        frame.setLayout(new BorderLayout());
        background = new JLabel();
        frame.add(background); // why you need it??? it has no visual effect here
        frame.setSize(500, 400);
        ok = new JButton("OK");
        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.add(ok);
        frame.add(buttonPanel, BorderLayout.PAGE_END);
        demo = new JLabel("CSIT 121 Demo System"); // probably you need to change foreground of label to fit your background image
        frame.add(demo, BorderLayout.LINE_END);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(Intro::new);
    }
}
  • Related