JButton() 只在鼠标悬停时工作 [英] JButton() only working when mouse hovers
本文介绍了JButton() 只在鼠标悬停时工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.imageio.*;
import java.lang.*;
import java.io.*;
import javax.swing.*;
public class MainClass extends Component{
private Image bg;
private ImageIcon newgame;
private ImageIcon quit;
private ImageIcon options;
private JButton bquit;
private JButton boptions;
private JButton bnewgame;
private static Container pane; //Container
public void loadImage() {
try {
bg=ImageIO.read(new File("bg1.png"));
} catch (Exception e) {
}
if(bg!=null)
repaint();
}
public void paint(Graphics g) {
g.drawImage(bg,0,0,null);
}
public void imageButtons(JFrame f) {
try {
quit= new ImageIcon("quit.png");
options=new ImageIcon("options.png");
newgame= new ImageIcon("newgame.png");
}catch(Exception e){}
bnewgame= new JButton(newgame);
boptions= new JButton(options);
bquit= new JButton(quit);
bnewgame.setBounds(150,100,400,89);
boptions.setBounds(150,200,400,89);
bquit.setBounds(150,300,400,89);
pane.add(bquit);
pane.add(boptions);
pane.add(bnewgame);
}
public static void main(String args[]) {
MainClass o=new MainClass();
FullScreen fs=new FullScreen();
JFrame f1=new JFrame("TITLE");
pane=f1.getContentPane();
fs.fullScreenIt(f1);
pane.add(o);
f1.setVisible(true);
o.loadImage();
o.imageButtons(f1);
}
}
全屏是另一个提供全屏框架的类.JButton 上有 ImageIcon.bg1.png 是背景图片问题是这些 JButton 仅在鼠标悬停时才可见,否则它们不会出现.
The Fullscreen is another class which gives a full screen Frame. JButton have ImageIcon on them. bg1.png is a background image Problem is these JButton become visible only when mouse hovers else they do not appear.
推荐答案
您可能遇到了布局问题,您试图将具有绝对边界的 JButton 添加到使用非空布局管理器的容器中.建议
Likely you have a layout problem where you're trying to add JButtons with absolute bounds into a container that uses a non-null layout manager. Suggestions
- 不要使用 setBounds 和绝对定位来调整和放置组件.
- 阅读并使用布局管理器为您完成这项繁重的工作:课程:在容器内布置组件
- 不要忘记在添加所有组件后在 JFrame 上调用
pack()
- 在调用
pack()
后调用setVisible(true)
并在添加所有组件后再次调用 both到您的 GUI. - 如果您绝对需要使用组件的绝对定位,则可以使用空布局,但无论如何,您应该尽量避免使用它.
- Do not use setBounds and absolute positioning to size and place your components.
- Read up on and use the layout managers to do this heavy lifting for you: Lesson: Laying Out Components Within a Container
- Don't forget to call
pack()
on your JFrame after adding all components - Call
setVisible(true)
after callingpack()
and again call both only after adding all components to your GUI. - A null layout is available if you absolutely need to use absolute positioning of components, but regardless, you should strive to avoid using it.
这篇关于JButton() 只在鼠标悬停时工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文