[英]JComponent background color using null layout?
只是一個簡短的問題:使用空布局將背景色直接添加到JFrame時,是否可以向JComponent添加背景色? 組件的大小和位置由setBounds()設置,我知道使用此設置將不會顯示背景色。 (我知道您應該始終使用布局管理器,但是在這種情況下,我想避免這種情況)。
默認情況下, JComponent
是透明的,您需要更改其opaque
狀態或使用JPanel
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;
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();
}
TestPane pane = new TestPane();
pane.setBounds(10, 10, 100, 100);
JFrame frame = new JFrame("Testing");
frame.setLayout(null); // This is bad, but it proofs my point
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JComponent {
public TestPane() {
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
setOpaque(!isOpaque());
repaint();
}
});
setBackground(Color.BLUE);
setBorder(new LineBorder(Color.RED));
}
}
}
null
布局是個壞消息,我不容忍它們,您應該避免使用它們,上面的示例只是證明了需要更改的是JComponent
的opaque
狀態
為什么不贊成在SWING中使用空布局? 很好地說明了為什么應避免使用null
布局。
如果需要更多控制,請編寫自己的控件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.