полоса прокрутки вертикальная полоса прокрутки не показывает ручку прокрутки - PullRequest
0 голосов
/ 01 февраля 2019

Я создал JScrollPane и добавил к нему JTable.Я хочу иметь возможность прокручивать до нижней части таблицы, используя вертикальную полосу прокрутки.Панель прокрутки отображается вместе с таблицей init, однако нажатие на верхнюю или нижнюю стрелки не перемещает представление вверх или вниз соответственно.Кроме того, в вертикальной дорожке прокрутки отсутствует отображение полосы прокрутки.

Я попытался установить область просмотра для разных размеров, также используя разные конструкторы для создания jscrollpane, т.е.);но ни один не сработал.

public class test {
JFrame f;
int myMonth, myDay, myYear;
private JTable tblAppts;

private String[] colTimes = { "Time", "Test 1", "Test 2", "Test 3" };
private Object[][] myTimes = { { "Time", "Test 1", "Test 2", "Test 3" }, { 
"00:30", "", "", "" },
        { "01:00", "", "", "" }, { "01:30", "", "", "" }, { "02:00", "", 
 "", "" }, { "02:30", "", "", "" },
        { "03:00", "", "", "" }, { "03:30", "", "", "" }, { "04:00", "", 
 "", "" }, { "04:30", "", "", "" },
        { "05:00", "", "", "" }, { "05:30", "", "", "" }, { "06:00", "", 
"", "" }, { "06:30", "", "", "" },
        { "07:00", "", "", "" }, { "07:30", "", "", "" }, { "08:00", "", 
"", "" }, { "08:30", "", "", "" },
        { "09:00", "", "", "" }, { "09:30", "", "", "" }, { "10:00", "", 
"", "" }, { "10:30", "", "", "" },
        { "11:00", "", "", "" }, { "11:30", "", "", "" }, { "12:00", "", 
"", "" }, { "12:30", "", "", "" },
        { "13:00", "", "", "" }, { "13:30", "", "", "" }, { "14:00", "", 
"", "" }, { "14:30", "", "", "" },
        { "15:00", "", "", "" }, { "15:30", "", "", "" }, { "16:00", "", 
"", "" }, { "16:30", "", "", "" },
        { "17:00", "", "", "" }, { "17:30", "", "", "" }, { "18:00", "", 
"", "" }, { "18:30", "", "", "" },
        { "19:00", "", "", "" }, { "19:30", "", "", "" }, { "20:00", "", 
"", "" }, { "20:30", "", "", "" },
        { "21:00", "", "", "" }, { "21:30", "", "", "" }, { "22:00", "", 
"", "" }, { "22:30", "", "", "" },
        { "23:00", "", "", "" }, { "23:30", "", "", "" } };
private JTable tblTime;
private JTable table_1;
private JTable table_2;
private JTable table_3;

// set the table widths method
public static void setJTableColumnsWidth(JTable table, int 
tablePreferredWidth, double... percentages) {
    double total = 0;
    for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
        total += percentages[i];
    }

    for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
        TableColumn column = table.getColumnModel().getColumn(i);
        column.setPreferredWidth((int) (tablePreferredWidth 
             (percentages[i] / total)));
    }
}

test() {

    f = new JFrame("WSDP");// creating instance of JFrame#
    // open the frame in a maximized state ie max vert and horizontal
    f.setSize(1000, 1000);
    f.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().setLayout(null);

    // menus
    JPanel panel = new JPanel();
    panel.setBounds(0, 0, 982, 27);

    // create border
    Border blackline = BorderFactory.createLineBorder(Color.black);
    panel.setBorder(blackline);
    f.getContentPane().add(panel);

    // icon buttons panel
    JPanel panel_1 = new JPanel();
    panel_1.setBounds(0, 26, 109, 593);
    panel_1.setBorder(blackline);
    f.getContentPane().add(panel_1);

    JScrollPane scrollPane = new JScrollPane();
    // scrollPane.setBounds(107, 78, 475, 875);
    scrollPane.setBounds(107, 78, 475, 500);
    // scrollPane.setPreferredSize(new Dimension(450, 110));
    scrollPane.setBorder(blackline);
    scrollPane.setViewportBorder(blackline);



    scrollPane.setVerticalScrollBarPolicy
                     (JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

    table_3 = new JTable(myTimes, colTimes);
    scrollPane.setRowHeaderView(table_3);
    table_3.setFillsViewportHeight(true);
    scrollPane.setVerticalScrollBarPolicy
              (JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    table_3.setRowHeight(20);
    table_3.setFont(new Font("Courier", Font.BOLD, 14));
    setJTableColumnsWidth(table_3, 480, 10, 30, 30, 30);
    f.getContentPane().add(scrollPane);
    f.setVisible(true);

}

public static void main(String[] args) {

    test t = new test();
}

}

1 Ответ

0 голосов
/ 01 февраля 2019

Вы серьезно должны прочитать Как использовать таблицы и Как использовать панели прокрутки , поскольку у вас есть некоторые фундаментальные недоразумения о том, как работает API.

Вы никогда не устанавливаете представление JScrollPane в окне просмотра ...

Я сократил ваш "пример" до полного и проверяемого примера, который демонстрирует немедленное решение ваших проблем...

Example

import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    private String[] colTimes = {"Time", "Test 1", "Test 2", "Test 3"};
    private Object[][] myTimes = {{"Time", "Test 1", "Test 2", "Test 3"}, {
        "00:30", "", "", ""},
    {"01:00", "", "", ""}, {"01:30", "", "", ""}, {"02:00", "",
        "", ""}, {"02:30", "", "", ""},
    {"03:00", "", "", ""}, {"03:30", "", "", ""}, {"04:00", "",
        "", ""}, {"04:30", "", "", ""},
    {"05:00", "", "", ""}, {"05:30", "", "", ""}, {"06:00", "",
        "", ""}, {"06:30", "", "", ""},
    {"07:00", "", "", ""}, {"07:30", "", "", ""}, {"08:00", "",
        "", ""}, {"08:30", "", "", ""},
    {"09:00", "", "", ""}, {"09:30", "", "", ""}, {"10:00", "",
        "", ""}, {"10:30", "", "", ""},
    {"11:00", "", "", ""}, {"11:30", "", "", ""}, {"12:00", "",
        "", ""}, {"12:30", "", "", ""},
    {"13:00", "", "", ""}, {"13:30", "", "", ""}, {"14:00", "",
        "", ""}, {"14:30", "", "", ""},
    {"15:00", "", "", ""}, {"15:30", "", "", ""}, {"16:00", "",
        "", ""}, {"16:30", "", "", ""},
    {"17:00", "", "", ""}, {"17:30", "", "", ""}, {"18:00", "",
        "", ""}, {"18:30", "", "", ""},
    {"19:00", "", "", ""}, {"19:30", "", "", ""}, {"20:00", "",
        "", ""}, {"20:30", "", "", ""},
    {"21:00", "", "", ""}, {"21:30", "", "", ""}, {"22:00", "",
        "", ""}, {"22:30", "", "", ""},
    {"23:00", "", "", ""}, {"23:30", "", "", ""}};
    private JTable table_3;

    public Test() {

        JFrame f = new JFrame("WSDP"); // creating instance of JFrame#
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JScrollPane scrollPane = new JScrollPane();

        table_3 = new JTable(myTimes, colTimes);
        table_3.setFillsViewportHeight(true);
        // This is dangerous and is likely to come back and haunt you
        table_3.setRowHeight(20);
        table_3.setFont(new Font("Courier", Font.BOLD, 14));

        // THIS is what's missing
        scrollPane.setViewportView(table_3);

        f.getContentPane().add(scrollPane);

        f.pack();
        f.setVisible(true);

    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }
                new Test();
            }
        });
    }

}

Я также рекомендую прочитать Расположение компонентов в контейнере , поскольку это решит многие издругие проблемы, с которыми вы столкнетесь

...