Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

java - How to put component in bottom-right corner with GridBagLayout?

I need to display a single component within a JPanel, and I want to keep that component in bottom right corner at all times. I tried to do it with GridBagLayout:

val infoArea = new TextArea {
  text = "Hello!"
  border = Swing.EmptyBorder(30)
  background = Color.RED
  editable = false
}
val p = new JPanel
p.setLayout(new GridBagLayout)
val c = new GridBagConstraints
c.gridx = 0
c.gridy = 0
c.anchor = GridBagConstraints.LAST_LINE_END
p.add(infoArea.peer,c)
val f = new JFrame
f.setContentPane(p)
f.setVisible(true)

But the text area is at the center for some reason:

enter image description here

What am I doing wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For example:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.*;

public class LayoutDemo {
   private static void createAndShowGui() {
      JLabel label = new JLabel("Hello");
      label.setOpaque(true);
      label.setBackground(Color.red);

      JPanel bottomPanel = new JPanel(new BorderLayout());
      bottomPanel.add(label, BorderLayout.LINE_END);

      JPanel mainPanel = new JPanel(new BorderLayout());
      mainPanel.add(bottomPanel, BorderLayout.PAGE_END);
      mainPanel.setPreferredSize(new Dimension(400, 400));


      JFrame frame = new JFrame("LayoutDemo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...