Adding new shortcuts in java

Hi fellow programmers! I am trying to add two JLabel to a JFrame, but the second add method that added the label seems to overwrite my first add method. I tried to solve this problem using two different label variables and using the setLocation method, which provides different coordinates for each label. But I can’t solve it. Why can't I add two tags to my program? By the way, I am not getting any errors. It seems more like a logical mistake that I cannot solve.

Here is my current code:

import javax.swing.*; public class test { private static JLabel label; private static JLabel label1; public static void main(String[] args){ initializeLabel(); initializeImage(); initializeFrame(); } private static void initializeLabel(){ label = new JLabel(); label.setText("hi"); label.setLocation(54,338); } private static void initializeImage(){ label1 = new JLabel(); label1.setText("sss"); label1.setLocation(55, 340); } private static void initializeFrame(){ JFrame frame = new JFrame(); frame.add(label1); frame.add(label); frame.setVisible(true); } }// class 
+4
source share
4 answers

Change your code as follows.

 private static void initializeFrame(){ JFrame frame = new JFrame(); frame.setLayout(new FlowLayout()); // <-- you need this for now frame.add(label1); frame.add(label); frame.setVisible(true); // optional, but nice to have. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); } 

Read more about swing layout here: Visual Guide for Layout Managers

Read more: Creating a GUI with JFC / Swing

+7
source

Read in Layout Managers . The default layout manager for the frame is BorderLayout. Your code adds both labels to the CENTER layout. It's impossible. Each place on BorderLayout can contain only one component (this can be a JPanel with other components).

You need to use a different layout manager. Without knowing your exact requirements, it is difficult to suggest which layout manager to use.

Also get rid of all these static methods. There are many examples in the Swing tutorial to help you better structure your program.

+4
source

The default JFrame BorderLayout , and the default position is BorderLayout.CENTER .

As a convenience, BorderLayout interprets the lack of a string specification in the same way as the CENTER constant.

In fact, the second label replaces the first.

+3
source

Add frame.setLayout(new FlowLayout()); after building the frame.

0
source

Source: https://habr.com/ru/post/1380123/


All Articles