[英]JComponent background color using null layout?
just a short question: Is it possible to add a background color to a JComponent when it is added directly onto a JFrame using null layout? 只是一个简短的问题:使用空布局将背景色直接添加到JFrame时,是否可以向JComponent添加背景色? The size and position of the component are set by setBounds() and i know that the background color will not be displayed using this setup.
组件的大小和位置由setBounds()设置,我知道使用此设置将不会显示背景色。 (I know you should always use layout managers, but in this case i want to prevent this).
(我知道您应该始终使用布局管理器,但是在这种情况下,我想避免这种情况)。
JComponent
is transparent by default, you'd either need to change its opaque
state or use a JPanel
默认情况下,
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
layouts are bad news, I don't condone them and you should avoid using them, the example above simply proves the point that it's the JComponent
s opaque
state which needs to be changed null
布局是个坏消息,我不容忍它们,您应该避免使用它们,上面的示例只是证明了需要更改的是JComponent
的opaque
状态
Why is it frowned upon to use a null layout in SWING? 为什么不赞成在SWING中使用空布局? is a nice read about why you should avoid using
null
layouts. 很好地说明了为什么应避免使用
null
布局。
If you want more control, write your own. 如果需要更多控制,请编写自己的控件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.