JPanelの目に見えないJButton
-
21-12-2019 - |
質問
これが私のJPanel
です。最初のボタンは常に表示されていますが、上にカートを配置したときにのみ有線が表示されます。問題がある場合は?
p.S。私は英語がよく話さないので、簡単な英語を使ってください。
public class GamePanel extends JPanel implements KeyListener{
GamePanel(){
setLayout(null);
}
public void paint(Graphics g){
JButton buttonShip1 = new JButton();
buttonShip1.setLocation(10, 45);
buttonShip1.setSize(40, 40);
buttonShip1.setVisible(true);
add(buttonShip1);
JButton buttonShip2 = new JButton();
buttonShip2.setLocation(110, 145);
buttonShip2.setSize(440, 440);
buttonShip2.setVisible(true);
add(buttonShip2);
}
}
. 解決
問題を避けてJava Swingを正しく学習したい場合は、そのチュートリアルをチェックアウトしてください。こちら
ここで議論するための問題が多すぎるので、それを簡単に保つようにします。
-
null
レイアウトを使用しています。通常あなたが望むものを正確にするレイアウトがあるので、null
レイアウトはほとんどの部分で避けられます。それを働くのに時間がかかりますが、デフォルトがいくつかありますが、いくつかのデフォルトがありますそれはかなり簡単で使いやすいチュートリアル。それぞれのレイアウトで何ができるかをあなたに示すのはそこにいくつかの素晴らしい写真があります。レイアウトマネージャを使用する場合は、一般的にJButtonsのようなほとんどのコンポーネントでsetLocation, setSize
またはsetVisible
を使用する必要はありません。 -
Swingアプリケーションで
paint
メソッドを呼び出しています。あなたはSWINGを使っていないので、paintComponent
を呼び出します。他のsuper.paintComponent(g)
メソッドを正しく上書きするために、paintComponent
メソッドの最初の行でpaintComponent
メソッドを呼び出す必要があります。 -
paint
/paintComponent
関連メソッドは非常に頻繁に呼び出されます。オブジェクトを作成/初期化したくない。paint
/paintComponent
メソッドは、サウンドが起こるような1回の方法ではありません。彼らは継続的に呼ばれ、あなたはこれを中心にあなたのGUIをデザインするべきです。 順次ではなく、イベント駆動になるようにpaint
関連のメソッドを設計します。言い換えれば、は、GUIが通常のプログラムのように順次順序で実行されるのではなく、GUIが継続的に反応しているというpaintComponent
メソッドをプログラムします。それはそれへの非常に基本的なアプローチです、そしてうまくいけば混同しないあなたは、しかしあなたがチュートリアルであることをチェックアウトするなら、あなたは私が最終的に私が何を意味するのかを見るでしょう。
JavaにはGUIが2つの基本タイプがあります。 1つはSwing
です
その他はAwt
です。チェックアウト StackOverflow でのこの回答
2つの素晴らしい説明
JPanelの2つのボタンがどのように見えるかの例です。
public class Test
{
public static void main(String[] args)
{
JFrame jframe = new JFrame();
GamePanel gp = new GamePanel();
jframe.setContentPane(gp);
jframe.setVisible(true);
jframe.setSize(500,500);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static class GamePanel extends JPanel{
GamePanel() {
JButton buttonShip1 = new JButton("Button number 1");
JButton buttonShip2 = new JButton("Button number 2");
add(buttonShip1);
add(buttonShip2);
//setLayout(null);
//if you don't use a layout manager and don't set it to null
//it will automatically set it to a FlowLayout.
}
public void paintComponent(Graphics g){
super.paintComponent(g);
// ... add stuff here later
// when you've read more about Swing and
// painting in Swing applications
}
}
}
.他のヒント
- Don't use a null layout
- Don't create components in a painting method. The paint() method is for custom painting only. There is no need for you to override the paint() method.
Read the section from the Swing tutorial How to Use FlowLayout for a simple example that uses buttons and a layout manager.