размер и положение кнопки - PullRequest
1 голос
/ 21 мая 2011

Привет, я хочу поставить свою кнопку на южную позицию!Как я могу это сделать?Вот мой код:

import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.io.*;
import java.util.*;
import javax.swing.JButton;

public class TableDemo extends JPanel {
    private static Icon leftButtonIcon;
    private boolean DEBUG = false;
     // added static infront becuase got non static referencing error
static List<String[]> rosterList = new ArrayList<String[]>();

    public TableDemo() {
        super(new GridLayout(1,0));

        JTable table = new JTable(new MyTableModel());
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);

       JButton button=new JButton("Buy it");
       button.setSize(30,60);
        button.add(button);

        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        //Add the scroll pane to this panel.
        add(scrollPane);
         //create a button

    }

    class MyTableModel extends AbstractTableModel {
        private String[] columnNames = { "Κωδικός", "Ποσότητα", "Τιμή", "Περιγραφή", "Μέγεθος", "Ράτσα"};

        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return rosterList.size();
        }

        @Override
        public String getColumnName(int col) {
            return columnNames[col];
        }

     public Object getValueAt(int row, int col)
        {
            return rosterList.get(row)[col];

        }


    }


    private static void createAndShowGUI() {
        //Create and set up the window.

        JFrame frame = new JFrame("TableDemo");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        //Create and set up the content pane.
        TableDemo newContentPane = new TableDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);


        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

Ответы [ 4 ]

5 голосов
/ 21 мая 2011

Как-то так?

enter image description here

См. Комментарии в коде.

import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.border.EmptyBorder;
import java.awt.Dimension;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.io.*;
import java.util.*;
import javax.swing.JButton;

public class TableDemo extends JPanel {    
    private static Icon leftButtonIcon;
    private boolean DEBUG = false;
     // added static infront becuase got non static referencing error
static List<String[]> rosterList = new ArrayList<String[]>();

    public TableDemo() {
        super(new BorderLayout(3,3));

        JTable table = new JTable(new MyTableModel());
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);

       JButton button=new JButton("Buy it");
       // Rarely has the intended effect.
       // also best not to presume we can guess the size
       // a component needs to be.
       //button.setSize(30,60);
       // cannot add a button to itself!
        //button.add(button);
        JPanel buttonCenter = new JPanel( new FlowLayout(FlowLayout.CENTER) );
        // allow the button to be centered in buttonCenter,
        // rather than stretch across the width of the SOUTH
        // of the TableDemo
        buttonCenter.add(button);
        add(buttonCenter, BorderLayout.SOUTH);

        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        //Add the scroll pane to this panel.
        add(scrollPane, BorderLayout.CENTER);
         //create a button

        // add a nice border
        setBorder(new EmptyBorder(5,5,5,5));
    }

    class MyTableModel extends AbstractTableModel {
        // apologies about the column names
        private String[] columnNames = { "??d????", "??s?t?ta", "??µ?", "?e????af?", "???e???", "??tsa"};

        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return rosterList.size();
        }

        @Override
        public String getColumnName(int col) {
            return columnNames[col];
        }

     public Object getValueAt(int row, int col)
        {
            return rosterList.get(row)[col];

        }
    }


    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("TableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        TableDemo newContentPane = new TableDemo();
        // JPanels are opaque by default!
        //newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        // Should be done on the EDT.
        // Left as an exercise for the reader.
        TableDemo.createAndShowGUI();
    }
}
3 голосов
/ 21 мая 2011

Вы добавляете кнопку к себе, и вам следует использовать BorderLayout , если вы хотите разместить компоненты по центру / северу / югу / и т. Д.:

setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
3 голосов
/ 21 мая 2011

"Привет, я хочу поставить свою кнопку на юг! Как я могу?"

Если вы хотите поместить что-то в расположение BorderLayout, имеет смысл использовать контейнер ... BorderLayout, n'est-ce pas?

А если серьезно, большинство ваших недавних вопросов на этом форуме предполагают, что вы приходите сюда, прежде чем читать учебники. Вам уже несколько раз давали ссылки, поэтому, пожалуйста, сделайте себе одолжение и изучите Swing правильно - изучите учебники по макету и другие учебники, и вы избавите себя от большого количества горя и догадок.

0 голосов
/ 21 декабря 2014

попробуйте это:

JFrame frame = new JFrame();
frame.add(yourbutton,BORDERLAYOUT.SOUTH)

и для задания позиции и размера кнопки, сделайте это

yourbutton.setBounds(10,15,120,200) --> (x,y,height,width) , x , y set possition
...