我是java swing gui的新手,我无法弄清楚这个问题 假设我的Jframe大小为100,100,我有4个按钮位置
left top widht height
button1 0 0 10 10 // left up
button2 90 0 10 10 // right up
button3 45 45 10 10 // middle
button4 0 90 10 10 // left down
button5 90 90 10 10 // right down
所有左上角宽度高度的大小从100,100开始缩放。
我需要使用绝对定位(因为我的实际情况是左,上,宽,高不同),但我认为响应能力可能是我可以使用乘以左,右,宽,高值的因素
例如,运行gui后,如果我将框架更改为400,200,则新位置应为
button1 0 0 40 20 // left up
button2 360 0 40 20 // right up
button3 180 90 40 20 // middle
button4 0 180 40 20 // left down
button5 360 180 40 20 // right down
x因子= 400/100 = 4和y因子= 200/100 = 2
我如何聆听Jframe从100,100到400,200的变化并开发上述方法。任何信息表示赞赏。
编辑
我从不同的服务获得左上角宽度高度,我的示例可能像
left top widht height
button1 01 04 11 14
button2 91 0 10 10
button3 44 45 9 14
button4 0 90 10 10
button5 90 90 1 1
答案 0 :(得分:3)
我需要使用绝对定位
只要您认为需要“绝对定位”,就不需要。认真地说,我从来不需要使用一种无法通过其他方式解决的方法,无论是现有布局还是自定义布局。
布局管理API旨在完全满足您的要求,更好地利用它并节省头发。
这是一个使用GridBagLayout
的非常简单的示例,是的,如果按钮的高度不同,它仍然可以应付
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
// Common properties...
gbc.weightx = 0.5;
gbc.weighty = 0.333;
// Top/left
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.NORTHWEST;
add(new JButton("Top left is all mine"), gbc);
// Top/right
gbc.gridx = 2;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.NORTHEAST;
add(new JButton("Top right mine, keep out"), gbc);
// middle
gbc.gridx = 1;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.CENTER;
add(new JButton("My precious"), gbc);
// bottom/left
gbc.gridx = 0;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.SOUTHWEST;
add(new JButton("Got this space covered"), gbc);
// bottom/right
gbc.gridx = 2;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.SOUTHEAST;
add(new JButton("Why is every one so unfriendly?"), gbc);
}
}
}
有高按钮...
自动覆盖的