gpt4 book ai didi

java 对象在窗口大小调整时调整大小

转载 作者:行者123 更新时间:2023-12-01 11:18:07 25 4
gpt4 key购买 nike

我必须在窗口大小调整时调整一些元素的大小,例如 JTable。我一直在尝试这段代码,但它无法正常工作:

    table.setLocation(0, 23);
Dimension siz = contentPane.getMaximumSize();
table.setSize(siz.height, siz.width - 46);

它调整了我的 table 大小,但它使它变得无休止,这是我不想要的。另外我想将滚动条连接到该表,如果可能的话 - 以百分比设置列宽

最佳答案

您的主要问题(调整大小)更多地与您对表单编辑器的依赖有关,而不是与 Swing 或 Java 有关

看看Laying Out Components Within a Container了解更多详情。

您似乎也没有使用 JScrollPane 来容纳 JTable。看看 How to Use TablesHow to Use Scroll Panes了解更多详情

Sizing

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

public class ResizeTest {

public static void main(String[] args) {
new ResizeTest();
}

public ResizeTest() {
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 {

private JTable table;
private JButton historyButton;
private JButton otherButton;

public TestPane() {

table = new JTable(new DefaultTableModel(10, 10));
historyButton = new JButton("History");
otherButton = new JButton("Other");

setLayout(new BorderLayout());
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.LEFT));
buttons.add(historyButton);
buttons.add(otherButton);
add(buttons, BorderLayout.NORTH);

add(new JScrollPane(table));

JPanel footers = new JPanel(new GridLayout(1, 2));
JLabel left = new JLabel("Left");
left.setHorizontalAlignment(JLabel.LEFT);
JLabel right = new JLabel("Right");
right.setHorizontalAlignment(JLabel.LEFT);
footers.add(left);
footers.add(right);

add(footers, BorderLayout.SOUTH);
}

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}

}

}

关于java 对象在窗口大小调整时调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31552320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com