• ベストアンサー

JButtonの配置

FlowLayoutによって、JFrameにボタン6個を2×3に配列するプログラムを考えています。ボタンを配置することはできたのですが、ウインドウの大きさを変えるとボタンが3×2になったりと変更してしまいます。 ウインドウの大きさを変えても、ボタンの大きさは変えず、ボタン6個が2×3配列になるプログラムはどうしたらよいのでしょうか?以下は、途中のプログラムです。 import java.awt.*; import javax.swing.*; public class sample { public static void main(String[] args){ MyFrame frame = new MyFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } public class MyFrame extends JFrame { public static final int WIDTH = 200; public static final int HEIGHT = 300; public MyFrame(){ setSize(WIDTH,HEIGHT); Container contentPane = getContentPane(); MyPanel panel = new MyPanel(); contentPane.add(panel); } } public class MyPanel extends JPanel{ public static final int MESSAGE_X = 200; public static final int MESSAGE_Y = 200; setLayout(new FlowLayout()); JButton button1 = new JButton("Button1"); contentPane.add(button1); JButton button2 = new JButton("Button2"); contentPane.add(button2); JButton button3 = new JButton("Button3"); contentPane.add(button3); JButton button4 = new JButton("Button4"); contentPane.add(button4); JButton button5 = new JButton("Button5"); contentPane.add(button5); JButton button6 = new JButton("Button6"); contentPane.add(button6); }

noname#38655
noname#38655
  • Java
  • 回答数2
  • ありがとう数0

質問者が選んだベストアンサー

  • ベストアンサー
  • koki_m
  • ベストアンサー率83% (45/54)
回答No.1

こんにちは。 BoxLayoutというレイアウトマネージャを使えばできると思います。 1.MyFrameのレイアウトマネージャをFlowLayoutに変更します。   contentPane.setLayout(new FlowLayout(FlowLayout.LEFT)); // 左上に表示される 2.MyPanelをさらに内部で「左ボタン3つ」と「右ボタン3つ」の2つのパネルに分割します。 3.MyPanelと、その内部の2つのパネルのレイアウトマネージャにBoxLayoutを使用します。 ================================================== class MyPanel extends JPanel{ public MyPanel() { setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); setBorder(BorderFactory.createLineBorder(Color.RED)); // 確認のため JPanel sub1 = new JPanel(); sub1.setLayout(new BoxLayout(sub1, BoxLayout.Y_AXIS)); JButton button1 = new JButton("Button1"); sub1.add(button1); sub1.add(Box.createVerticalStrut(5)); JButton button2 = new JButton("Button2"); sub1.add(button2); sub1.add(Box.createVerticalStrut(5)); JButton button3 = new JButton("Button3"); sub1.add(button3); JPanel sub2 = new JPanel(); sub2.setLayout(new BoxLayout(sub2, BoxLayout.Y_AXIS)); JButton button4 = new JButton("Button4"); sub2.add(button4); sub2.add(Box.createVerticalStrut(5)); JButton button5 = new JButton("Button5"); sub2.add(button5); sub2.add(Box.createVerticalStrut(5)); JButton button6 = new JButton("Button6"); sub2.add(button6); add(sub1); add(Box.createHorizontalStrut(10)); add(sub2); } } ================================================== sub1.add(Box.createVerticalStrut(5));などはコンポーネントの間隔です。 間隔もコンポーネントとして挿入するという感じです。

参考URL:
http://java.sun.com/j2se/1.5.0/ja/docs/ja/api/javax/swing/BoxLayout.html

その他の回答 (1)

  • msnc31
  • ベストアンサー率31% (7/22)
回答No.2

通りすがりなので適当な回答ご容赦ください。 ボタンを2*3で固定したい場合、ボタンを配置する専用のパネルを作って、それのレイアウトをGridLayoutにすると、格子状にコンポーネントを配置できます。 panelname.setLayout(new GridLayout(2,3)); ←例 ボタンの大きさを変えないようにする方法ですが、上記のパネルを貼り付けるコンポーネント(パネルかフレーム)のレイアウトをnullにして、すべて座標で指定するようにすることで解決できます。 いろいろ試してみてください。

関連するQ&A

  • ActionListener について

    JFrame の上に JPanel があり、JPanel の上に JButton があるとします。 JButton が押されたことを JFrame に知らせるにはどうしたらいいでしょうか。 わかるところまで書いてみました。 class MyFrame extends JFrame implements ActionListener { MyPanel myPanel = new MyPanel(); MyFrame() { myPanel.addActionListener(this); add(myPanel); } public void actionPerformed(ActionEvent e) { System.out.println("The button on the MyPanel was pressed!"); } public static void main(String[] args) { new MyFrame(); } } class MyPanel extends JPanel implements ActionListener { JButton button1 = new JButton(); MyPanel() { button1.addActionListener(this); add(button1); } public void actionPerformed(ActionEvent e) { } }

    • ベストアンサー
    • Java
  • finalの意味

    import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ExerciseD8L1{ public static void main(String args[]){ final JFrame myFrame = new JFrame(); myFrame.getContentPane().setLayout(new BorderLayout()); final JLabel myLabel = new JLabel(); JPanel myPanel = new JPanel(); myFrame.getContentPane().add(myLabel,BorderLayout.CENTER); myFrame.getContentPane().add(myPanel,BorderLayout.NORTH); JButton btn1 = new JButton("btn1"); btn1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ myLabel.setText("btn1がクリックされました"); } }); }); myPanel.add(btn1); myFrame.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); myFrame.setSize(400,100); myFrame.setVisible(true); } } これで、finalをつけないとコンパイルできません。 なぜ、fianlが必要なんでしょう。 どのようなときにfinalを用いるのでしょう。 お願いします。

    • ベストアンサー
    • Java
  • 「staticでない…」について

    今,下記のプログラムを実行させたいのですが,次のエラーが出て困っています。基本的なことだと思いますが,つまずいて修復できません。 どのような対処をすればよいでしょうか。 エラー:「staticでない変数thisをstaticコンテキストから参照することができません。」 プログラム import java.awt.*; import java.awt.geom.*; import javax.swing.*; import java.util.*; public class Test{ public static int R,G,B; public static void main (String[] args){ R = Integer.parseInt(args[0]); G = Integer.parseInt(args[1]); B = Integer.parseInt(args[2]); MyFrame frame = new MyFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } class MyFrame extends JFrame{ public static final int WIDTH = 400; public static final int HEIGHT = 400; public MyFrame(){ setTitle("Test"); setSize(WIDTH,HEIGHT); Container contentPane = getContentPane(); MyPanel panel = new MyPanel(); contentPane.add(panel);}} class MyPanel extends JPanel{ public void paintComponent(Graphics g){ super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; Rectangle2D rect = new Rectangle2D.Double(100,100,100,50); g2.setColor(new Color(R,G,B)); g2.fill(rect);}}}

    • ベストアンサー
    • Java
  • Jframeの中にJframeを表示させたい

    Jframeの中にボタンを作り、ボタンを押すとJInternalFrameではなくJframeを表示させるようにしたいんですが、なかなかできません。 検索したりしてサンプル探したんですが、 Jframeを表示させ、ラベルを貼ったりしたいんですが どなたかお願いします!! public class Browser extends JFrame{ public static void main(String args[]) { Browser frame = new Browser(); frame.setTitle(""); frame.setExtendedState(JFrame.MAXIMIZED_BOTH); frame.setVisible(true); } //ボタン private JButton bt = new JButton("~~"); public Browser() { bt.addActionListener(this); JToolBar tb = new JToolBar(); tb.setFloatable(false); getContentPane().add(tb, BorderLayout.NORTH); JPanel panel2 = new JPanel(); panel2.add(bt); panel2.setLayout(new FlowLayout(FlowLayout.LEFT)); tb.add(panel2); } //↓この辺りの処理の記述で頭が混乱してきました(泣 public class actionPerformed(ActionEvent e){ if(e.getSource() == bt){ Frame FW = new Frame(); FW.setSize(500,400); FW.setVisible(true); } } class Frame extends Frame{ public Frame(){ //コンストラクタの定義 } }

    • ベストアンサー
    • Java
  • java起動時にボタンが表示されない

    Javaの初心者です。以下のプログラムを起動するとJTextAreaとJLabel は、表示されるのですが、JButtonが表示されません。起動後にボタンの配置したところを触るとボタンが表示されるようになるのですが、ボタンのアクションリスナーが動作してしまいます。起動時にボタンも表示できるようにするには、どうしたらよいでしょうか? public class test_pro extends JFrame{ private static final long serialVersionUID = 1L; private JLabel label1;     JButton buton1,button2;     public JTextArea lt1; public test_pro() { this.setUndecorated(true);    GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); device.setFullScreenWindow(this); Container contentPane = getContentPane(); contentPane.setLayout(null); label1 = new JLabel("menu"); Font f1=new Font("Serif",1,22); label1.setFont(f1); label1.setForeground(Color.red);     contentPane.add(label1); lt1=new JTextArea(3,3); JScrollPane pane=new JScrollPane(lt1); pane.setBounds(new Rectangle(50,300,550,150)); contentPane.add(pane);     button1 = new JButton("SendRequestTest!"); button2 = new JButton("ReceiveResponseTest!"); label1.setBounds(new Rectangle(50,20,200,20)); button1.setBounds(new Rectangle(50,80,230,20)); button2.setBounds(new Rectangle(50,110,230,20));  contentPane.add(button1); contentPane.add(button2); button1.addActionListener(new MyJsendActionAdapter()); button2.addActionListener(new MyJreceiveActionAdapter());     this.setDefaultCloseOperation(EXIT_ON_CLOSE);     this.setVisible(true);    } /*以下省略*/

  • javaのボタン表示等に関する質問

    下記のコードはフォームをNORTH、CENTER、SOUTHEに分割して、それぞれのpaneに ラベルとボタンを表示するものです。 Q1)myFrame.setBounds(350,0, total_x, total_y)をコンストラクターの最初に記述しますと  フォームの表示が正常でなく、コンストラクターの最後では、正常に行なわれます。  この理由等について、コメント頂けますと有り難いです。 Q2)mainに記述してある、下記のコードは無くても、Xでクロースできますが,このコード  の記述は正しいでしょうか GridLayout_new frame = new GridLayout_new(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 以上お手数ですが、コメント頂けますと大変助かります。 //============================================= import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.LineBorder; public class GridLayout_new extends JFrame{ int panelA_x=200, panelA_y=50; int panelB_x=200, panelB_y=200; int panelC_x=200, panelC_y=50; int total_x=panelA_x; int total_y=panelA_y+panelB_y+panelC_y; public static void main(String[] args){ GridLayout_new frame = new GridLayout_new(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } GridLayout_new(){ JFrame myFrame=new JFrame(); myFrame.setTitle("panelA"); // myFrame.setBounds(350,0, total_x, total_y); //正常なformの表示が出来ない myFrame.setVisible(true); LineBorder border = new LineBorder(Color.BLACK, 1, true); //======================== JLabel button1=new JLabel("Label1"); GLabel_Layout(button1, border); JButton button2 = new JButton("button2"); button_Layout(button2, border); //======================== JLabel button3=new JLabel("Label3"); GLabel_Layout(button3, border); JButton button4 = new JButton("button4"); button_Layout(button4, border); //======================== JLabel button5=new JLabel("Label5"); GLabel_Layout(button5, border); JButton button6 = new JButton("button6"); //======================== JLabel button7=new JLabel("Label7"); GLabel_Layout(button7, border); JButton button8 = new JButton("button8"); //======================== JLabel button9=new JLabel("Label9"); GLabel_Layout(button9, border); JButton button10 = new JButton("button10"); button_Layout(button10, border); //======================== JLabel button11=new JLabel("Label11"); GLabel_Layout(button11, border); JButton button12 = new JButton("button12"); button_Layout(button12, border); //================================== JPanel p1 = new JPanel(); GridLayout layout1 = new GridLayout(2,2); //2行、2列の設定 layout1.setHgap(2); layout1.setVgap(10); p1.setLayout(layout1); p1.setBackground(Color.GREEN); p1.add(button1); p1.add(button2); p1.add(button3); p1.add(button4); myFrame.setSize(panelA_x, panelA_y); myFrame.getContentPane().add(p1, BorderLayout.NORTH); //============================== JPanel p2 = new JPanel(); GridLayout layout2 = new GridLayout(2,2); //2行、2列の設定 layout2.setHgap(2); layout2.setVgap(10); p2.setLayout(layout2); p2.setBackground(Color.GREEN); p2.add(button5); p2.add(button6); p2.add(button7); p2.add(button8); myFrame.setSize(panelB_x, panelB_y); myFrame.getContentPane().add(p2, BorderLayout.CENTER); //================================== JPanel p3 = new JPanel(); GridLayout layout3 = new GridLayout(2,2); //2行、2列の設定 layout3.setHgap(2); layout3.setVgap(10); p3.setLayout(layout3); p3.setBackground(Color.GREEN); p3.add(button9); p3.add(button10); p3.add(button11); p3.add(button12); myFrame.setSize(panelC_x, panelC_y); myFrame.getContentPane().add(p3, BorderLayout.SOUTH); myFrame.setBounds(350,0, total_x, total_y); //正常なformの表示 } //constructor void GLabel_Layout(JLabel label, LineBorder border){ label.setPreferredSize(new Dimension(80,20)); label.setBorder(border); label.setBackground(Color.lightGray); label.setOpaque(true); } void button_Layout(JButton button, LineBorder border){ button.setPreferredSize(new Dimension(80,20)); button.setBorder(border); } } //main class....GridLayout_new

    • ベストアンサー
    • Java
  • 上に色をつけるJPanelを作りたい

    つい先日も質問させていただきましたが、また分からないことがでてきたのでお聞きします。 JPanelのなかにOverlayLayoutで2枚のJPanel(上にglassPane、下にcontentPane)を配置し、overがtrueになったらglassPaneに色を書くようにしたいと思っています。 ですが、下のcontentPane部分にボタンなどがあると、その部分にうまく色がつきません。 どうすればいいのでしょうか。よろしくお願いします。 自分で組んでみたコードを示します。 ****** import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Test extends JLabel{ private JPanel glassPane; private JPanel contentPane = new JPanel(); private JButton button1 = new JButton("OverlayTest"); private boolean over = false; public Test(){ glassPane = new JPanel(){ @Override protected void paintComponent(final Graphics g) { super.paintComponent(g); if(!over)return; Graphics2D g2 = (Graphics2D) g; g2.setColor(new Color(Color.MAGENTA.getRed(), Color.MAGENTA.getGreen(), Color.MAGENTA.getBlue(), 150)); g2.fillRect(0, 0, this.getWidth(), this.getHeight()); } }; button1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setOver(!over); glassPane.repaint(); //glassPane.revalidate(); } }); contentPane.setLayout(new GridBagLayout()); contentPane.add(button1); glassPane.setOpaque(false); setLayout(new OverlayLayout(this)); add(glassPane); add(contentPane); } public void setOver(boolean over){ this.over = over; } public static void main(String[] args) { JFrame frame = new JFrame(); frame.add(new Test()); frame.setSize(500,400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }

    • ベストアンサー
    • Java
  • GUI入門書のサンプルコード

    JavaのGUIをやってみようと思い中古で本を買ってきたのですが、 その中のサンプルコードが意味がわからない上にコンパイルエラーを起こすので 誰か解説をお願いします。 OS:Win Vista、それとJDK7です。 以下がソースコードとコンパイルエラーになります。 import java.awt.*; import javax.swing.*; import java.awt.event.*;    //サンプルではActionListenerを使うのに抜けていた public class MyButton { ____JButton button; ________//※1 何故ここで宣言しているのか ____public static void main(String[] args) { ________JFrame frame = new JFrame("MyFrame"); ________Container pane = frame.getContentPane(); ________JButton button = new JButton("MyButton");________//※1 何故ここにもあるのか ________button.addActionListener(new MyActionListener()); //※2 MyActionListenerクラスはstaticでないので使用できない ________pane.add(button); ________frame.setBounds(100, 50, 300, 200); ________frame.setVisible(true); ________frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ____} ____class MyActionListener implements ActionListener { ________public void actionPerformed(ActionEvent e) ________//サンプルではpublicが抜けていた ____________if(e.getSource() == button) ________________System.out.println("button was pressed"); ________} ____} } /* MyButton.java:13: static でない 変数 this を static コンテキストから参照すること はできません。 button.addActionListener(new MyActionListener()); ^ エラー 1 個 */

    • ベストアンサー
    • Java
  • swingのJframeについて

    JFrameについて質問があるのですが import javax.swing.*; public class JFrameTest extends JFrame{ public static void main(String[] args){ JFrameTest frame = new JFrameTest(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(10, 10, 300, 200); frame.setTitle("タイトル"); frame.setVisible(true); } JFrameTest(){ JPanel p = new JPanel();   Container contentPane = getContentPane(); ContentPane.add(p);   pack(); } } このプログラムと import javax.swing.*; public class JFrameTest{ public static void main(String[] args){ JFrame frame = new JFrame("フレームのタイトル"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds( 10, 10, 300, 200); frame.setVisible(true); JPanel p = new JPanel();   Container contentPane = frame.getContentPane(); frame.ContentPane.add(p);   frame.pack(); } } このプログラムは何が違うのでしょう? やってることはまったく一緒だと思ってたのですが、全然違うみたいです。 上のプログラムの JFrameTest(){ はコンストラクタと呼ばれるものなのでしょうか? しょぼい質問で申し訳ないのですが誰か教えていただけないでしょうか。

    • ベストアンサー
    • Java
  • Swing自作コンポーネントをadd出来るように、

    JTextFieldやJButtonなどを一つにまとめたコンポーネントを自作し、それをadd()出来るようにしたいです。frame.add(自作のクラスのインスタンス)を可能にしたいです。 調べて、paintComponent()を使えば良いということはわかったのですが、Graphicsのインスタンス(?)に線を描いたり、円を描いたりする方法はわかりましたが、JButtonやJTextFieldなどをGraphicsのインスタンス(?)に追加する方法はわからず、paintComponent()を使うやり方はできませんでした。 paintComponent()も使わずに、自分のできる方法で、組んだものを一応載せます。 import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class MyComponentTest{ public static void main(String[] args){ JFrame frame = new JFrame("タイトル"); frame.setSize(400, 300); frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS)); // 2つのテキストフィールドと一つのボタンを4つ追加する frame.add(new TwoTextFieldsAndOneButton().getContent()); frame.add(new TwoTextFieldsAndOneButton().getContent()); frame.add(new TwoTextFieldsAndOneButton().getContent()); frame.add(new TwoTextFieldsAndOneButton().getContent()); frame.setVisible(true); } } //2つのテキストフィールドと一つのボタンを一つの部品にしたい class TwoTextFieldsAndOneButton{ JTextField textField1 = new JTextField("テキストフィールド1"); JTextField textField2 = new JTextField("テキストフィールド2"); JButton button = new JButton("ボタン"); // こんなメソッドを使わずに、再現したい JPanel getContent(){ JPanel panel = new JPanel(); panel.add(textField1); panel.add(textField2); panel.add(button); return panel; } }

    • ベストアンサー
    • Java

専門家に質問してみよう