除了列表未显示在JFrame上之外,一切正常。我不明白为什么我不能在没有声明新布局的情况下添加东西。
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.*;
public class Gui3 extends JFrame {
private JPanel mousepanel;
private JLabel statusbar;
private JList list;
private static String[] colornames = {"black","blue","red","white"};
private static Color[] colors = {Color.BLACK, Color.BLUE,Color.RED,Color.WHITE};
public Gui3(){
super("The title");
list = new JList(colornames);
list.setVisibleRowCount(4);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setFixedCellHeight(15);
list.setFixedCellWidth(100);
add(new JScrollPane(list));
list.addListSelectionListener(
new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event){
用户应该能够从列表中选择背景颜色,然后程序应该将背景更改为该颜色。但是不是......
mousepanel.setBackground(colors[list.getSelectedIndex()]);
}
}
);
mousepanel = new JPanel();
mousepanel.setBackground(Color.WHITE);
add(mousepanel, BorderLayout.CENTER);
statusbar = new JLabel("Default");
add(statusbar, BorderLayout.SOUTH);
HandlerClass handler = new HandlerClass();
mousepanel.addMouseListener(handler);
mousepanel.addMouseMotionListener(handler);
}
private class HandlerClass implements MouseListener, MouseMotionListener
{
@Override
public void mouseClicked(MouseEvent event) {
statusbar.setText(String.format("Clicked at %d, %d", event.getX(),event.getY()));
DrawShapes shapes = new DrawShapes();
shapes.setPosition(event.getX(), event.getY());
add(shapes);
}
@Override
public void mousePressed(MouseEvent event){
statusbar.setText("You pressed down the mouse");
}
@Override
public void mouseReleased(MouseEvent event){
statusbar.setText("You released the button");
}
@Override
public void mouseEntered(MouseEvent event){
statusbar.setText("You entered the area");
mousepanel.setBackground(Color.RED);
}
@Override
public void mouseExited(MouseEvent event){
statusbar.setText("The mouse has left the window");
mousepanel.setBackground(Color.WHITE);
}
//These are mouse motion events
@Override
public void mouseDragged(MouseEvent event){
statusbar.setText("You are dragging the mouse");
}
@Override
public void mouseMoved(MouseEvent event){
statusbar.setText("You are moving the mouse");
}
}
}
答案 0 :(得分:5)
因为您使用BorderLayout
但未设置ScrollPane
的排名。因此,mousePanel
将位于ScrollPane
。
试试这个
add(new JScrollPane(list), BorderLayout.WEST);