不一定是重复的问题
我正在尝试将我的面板设置为透明。但是,我的“应用程序”是更大应用程序的一部分,我需要找出“什么”包含我的面板。
getRoot() gives a null pointer.
这可行,但让一切变得透明 - 有没有办法判断哪个是我的父容器?
JFrame.setDefaultLookAndFeelDecorated(true);
Frame[] Frs = JFrame.getFrames();
int n=-1;
for (Frame f : Frs) {
f.setOpacity(0.55f);
}
我不确定我的父母是框架还是面板。
有没有办法说“我被包含在什么之中?”
EDIT1
我知道有类似的问题有答案,但它们似乎对我不起作用。我也试过这个:
Container c = SwingUtilities.getAncestorOfClass(getClass(), this);
JOptionPane.showMessageDialog(null,"Container "+ c.getName());
我再次得到一个空指针
完整代码
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JLabel;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
public class HelloWorldModule extends JPanel implements WorkspaceModule{
private static final long serialVersionUID = 1L; //change this number to something more sensible
private JLabel lblHelloWorld;
public HelloWorldModule() {
setLayout(null);
setSize(647, 623);
setPreferredSize(new Dimension(900, 840));
this.setOpaque(true);
JFrame.setDefaultLookAndFeelDecorated(true);
try {
this.setBackground(new java.awt.Color(150,50,50,100));
Container c = SwingUtilities.getAncestorOfClass(this.getClass(), this);
JOptionPane.showMessageDialog(null,"Container "+ c.getName());
//this. setBackground(new java.awt.Color(150,50,50,100));
} catch (Exception e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null,"Factory "+ e);
}
lblHelloWorld = new JLabel("HelloWorld");
lblHelloWorld.setBounds(33, 53, 78, 28);
add(lblHelloWorld);
setModuleTitle("Hello world!");
}
@Override
public JComponent getVisualComponent() {
return this;
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public PersistedStateHolder getPersistedState() {
// TODO Auto-generated method stub
return null;
}
@Override
public void loadPersistedState(PersistedStateHolder state) {
// TODO Auto-generated method stub
}
protected void setModuleTitle(String title) {
putClientProperty(WorkspaceModuleProperties.COMPONENT_TITLE, title);
}
}
编辑2
JButton b = new JButton();
b.setVisible(true);
b.setOpaque(true);
b.setText("PRESS");
b.setPreferredSize(new Dimension(100,100));
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Container c = SwingUtilities.getAncestorOfClass(P.getClass(), P);
JOptionPane.showMessageDialog(null,"Container " + c.getName());
}
});