![](/img/trans.png)
[英]Java swing, JButton does not get re-sized on first button press, but does in on second press
[英]Java swing - Repaint is duplicating components (JButtons and JLabels) when re-sized
我有这个奇怪的问题。 我的教授似乎无法复制它,他提供的帮助充其量是最小的。 所以说到这一点。 此代码在面板上生成JButton并添加到JFrame的内容窗格中:
public myPanel extends JPanel {
static final long serialVersionUID = 1;
public myPanel() {
this.setPreferredSize(new Dimension(600, 40));
}
public void paintComponent(Graphics graphicsDrawer) {
super.paintComponent(graphicsDrawer);
this.add(new JButton("A Button"));
}
}
这是GUI代码
public class myGUI {
public myGUI() {
}
public void showGUI() {
JFrame frame = new JFrame("Issues!!!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new myPanel());
frame.pack();
frame.setVisible(true);
}
}
然后由该类运行GUI
// It is unnecessary to show here but I made a class that
// implements runnable that creates a myGUI object and calls
// showGUI
public static void main(String[] args) {
RunnableGUI runGUI = new RunnableGUI();
javax.swing.SwingUtilities.invokeLater(runGUI);
}
这是我最起码的代码。 但是我已经把它隔离了,即使有了必需品,这个问题仍然存在。 下面是我遇到问题的照片。
我已经尝试过所有我能找到并想到的东西。
我认为每次重新调整大小时,框架都会重新绘制按钮。 但是,由于分配要求,必须能够重新调整框架的大小。
运行Windows 8 w / JRE 7,8(我将下载6但我不认为这会有所帮助)
永远不要这样做:
public void paintComponent(Graphics graphicsDrawer) {
super.paintComponent(graphicsDrawer);
this.add(new JButton("A Button")); // ***** yikes! ****
}
该方法的paintComponent是只画。 您不必在是否或者即使它会被称为完全控制,并且可以多次调用,这意味着大量的添加按钮。 此外,您希望避免组件创建代码或任何减慢绘制方法中的程序流的代码,因为这些方法部分地决定了GUI的感知响应性,因此您将希望绘制方法( paint
和paintComponent
)是精简的,意味着快速 。
在构造函数或初始化方法中添加按钮,以便控制调用代码的频率。
public myPanel extends JPanel {
static final long serialVersionUID = 1;
public myPanel() {
this.setPreferredSize(new Dimension(600, 40));
this.add(new JButton("A Button"));
}
public void paintComponent(Graphics graphicsDrawer) {
super.paintComponent(graphicsDrawer);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.