BorderLayout Manager でサイズ変更時に GUI コンポーネントが縮小しないようにするにはどうすればよいですか? コンポーネントがそれ以上縮小しないように最小サイズを設定することはできますか?
私にとっての問題は、私が望むようにLayoutManagerMaximumSize
の大部分を設定することですが、期待どおりに機能します。基本的な例ですMinimum & PreferredSize
CENTER 領域を期待して、 BorderLayoutによって配置されます
import java.awt.*;
import javax.swing.*;
public class CustomComponent extends JFrame {
private static final long serialVersionUID = 1L;
public CustomComponent() {
setTitle("Custom Component Test / BorderLayout");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void display() {
add(new CustomComponents(), BorderLayout.NORTH);
add(new CustomComponents(), BorderLayout.CENTER);
add(new CustomComponents(), BorderLayout.SOUTH);
add(new CustomComponents(), BorderLayout.EAST);
pack();
// enforces the minimum size of both frame and component
setMinimumSize(getMinimumSize());
setPreferredSize(getPreferredSize());
setVisible(true);
}
public static void main(String[] args) {
CustomComponent main = new CustomComponent();
main.display();
}
}
class CustomComponents extends JLabel {
private static final long serialVersionUID = 1L;
@Override
public Dimension getMinimumSize() {
return new Dimension(200, 100);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
@Override
public void paintComponent(Graphics g) {
int margin = 10;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
}
}
GridLayoutによって配置
import java.awt.*;
import javax.swing.*;
public class CustomComponent1 extends JFrame {
private static final long serialVersionUID = 1L;
public CustomComponent1() {
setTitle("Custom Component Test / GridLayout");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void display() {
setLayout(new GridLayout(0, 1));
add(new CustomComponents());
add(new CustomComponents());
add(new CustomComponents());
add(new CustomComponents());
pack();
// enforces the minimum size of both frame and component
setMinimumSize(getMinimumSize());
setPreferredSize(getPreferredSize());
setVisible(true);
}
public static void main(String[] args) {
CustomComponent1 main = new CustomComponent1();
main.display();
}
}
class CustomComponents extends JLabel {
private static final long serialVersionUID = 1L;
@Override
public Dimension getMinimumSize() {
return new Dimension(200, 100);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
@Override
public void paintComponent(Graphics g) {
int margin = 10;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
}
}
Just one more question: If I used nested panels, is it possible to assign
them fixed positions and let the layout manager takes care of the components
inside these panels?
はい、ほとんどの完全な GUI に問題は見られません。問題は、いくつかの JComponents を GUI に正しくレイアウトすることですが、そのためには本当の質問をする必要があります。