私は3つのボタンを作成しました。それらはそれぞれJFrameに2回表示されます。フレームの背景を変更するのに問題があります。 ActionListenersを設定しましたが、クリックすると何も変わりません。私はいくつかの助けを求めることができます。アクションリスナーの設定と背景の変更
public class MyButtons extends JPanel {
public static JFrame frame;
private JButton Red = new JButton("Red");
private JButton Green = new JButton("Green");
private JButton Blue = new JButton("Blue");
public void InitializeButton()
{
Blue.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.setBackground(Color.BLUE);
}
});
Green.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.setBackground(Color.GREEN);
}
});
Red.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.setBackground(Color.RED);
}
});
}
public MyButtons() {
InitializeButton();
add(Red);
add(Green);
add(Blue);
}
public static void main(String[] args) {
frame = new JFrame();
JPanel row1 = new MyButtons();
JPanel row2 = new MyButtons();
row1.setPreferredSize(new Dimension(250, 100));
row2.setPreferredSize(new Dimension(250, 100));
frame.setLayout(new GridLayout(3,2));
frame.add(row1);
frame.add(row2);
frame.pack();
frame.setVisible(true);
}
}
1)フレームがパネルで完全に覆われているか、2) 'setBackground(..) 'の呼び出しがフレームのコンテンツペインに渡されていないようです。 - 2つのパネルを参照を保持し、BGを変更する3番目のパネルに追加する方がよいでしょう。 –
ActionListenersに間違いありません。問題は、ContentPaneの背景がGridLayoutで覆われていることにあります。プログラムを実行し、任意のボタンを押してからJFrameのサイズを変更して試してみてください。サイズ変更するまでの時間の一部の間、背景色が表示されます。あなたのグラフィックスカードが速すぎる場合は、次のようなものを追加してください:System.out.println(frame.getBackground()。getBlue());あなたの青いActionListenerに。 Blueを押すたびに255が出力されます。 空の第3パネルをGridLayoutに追加し、フレームの代わりに色を変更します。 –