我试图打开同时具有image
和它buttons
一个窗口。但我似乎无法弄清楚如何添加按钮。图像显示大和菜单工作正常,但不管我在哪里添加按钮(进入JLabel
,JPanel
,或JFrame
),它不会永远显示...的Java GUI - JPanels,JFrames,Jbutton将
主营:
public static void main(String[] args) {
GUI myGUI = new GUI();
myGUI.show();
}
GUI类: openImage使用菜单时调用。然后图像显示,但没有按钮。
private JFrame myFrame;
private JPanel myPanel;
private JLabel myLabel;
public GUI()
{
myFrame = new JFrame();
initializePanel();
}
public void show()
{
myFrame.setSize(600,600);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.addMouseListener(this);
setupMenu(myFrame);
myFrame.setVisible(true);
}
private void initializePanel()
{
myPanel = new JPanel();
myPanel.setPreferredSize(new Dimension(500,500));
//myPanel.setLayout(new BorderLayout());
}
private void openImage(String fileName)
{
try {
myImage = ImageIO.read(new File(fileName));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myLabel = getJLabel();
JButton button = new JButton("ButtonClick");
button.addActionListener(this);
myFrame.setContentPane(myLabel);
myPanel.add(button);
myFrame.getContentPane().add(myPanel);
myFrame.pack();
myFrame.setSize(600,600);
}
private void setupMenu(JFrame window) {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem open = new JMenuItem("Open");
open.addActionListener(this);
file.add(open);
menubar.add(file);
window.setJMenuBar(menubar);
}
'myFrame.setSize(600600);'是多余的。 'pack()'方法将帧设置得足够大,以保持帧内每个组件的首选大小(但不会更大)。另外,'setupMenu()'方法在哪里?这可能是一个促成因素。 – fireshadow52
@ fireshadow52 - 感谢您的回复。如果我在'myFrame.pack()'之后取出'myFrame.setSize(600,600)',则它只能调整为图像尺寸。我还在我的帖子中添加了'setupMenu'方法。 – RedLeader
我想你应该切换'myPanel.add(button)'和'button.addActionListener(this);'语句。如果不这样做,请检查你的代码,看看你是否有任何可能会弄乱它的行或语句。 – fireshadow52