Java 教程是为 JDK 8 编写的。本页中描述的示例和实践未利用在后续版本中引入的改进。
This section discusses problems that you might encounter while using components. If you do not find your problem in this section, consult the following sections:
Problem:I am having trouble implementing a model (or some other code that is similar to something already in Java SE Platform, Standard Edition).
Problem:Whenever the text in my text field updates, the text field's size changes.
int
argument to the JTextField
constructor or the setColumns
method.Problem:Certain areas of the content pane look weird when they are repainted.
setOpaque(true)
on your content pane. Note that although JPanel
s are opaque in most look and feels, that is not true in the GTK+ look and feel. See Adding Components to the Content Pane for details.Problem:My program is exhibiting weird symptoms that sometimes seem to be related to timing.
Problem:My modal dialog gets lost behind other windows.
Problem:The scroll bar policies do not seem to be working as advertised.
VERTICAL_SCROLLBAR_AS_NEEDED
and the HORIZONTAL_SCROLLBAR_AS_NEEDED
policies. If feasible for your project, use the most recent release of Swing.revalidate
on the client.Problem:My scroll pane has no scroll bars.
VERTICAL_SCROLLBAR_ALWAYS
or HORIZONTAL_SCROLLBAR_ALWAYS
for the scroll bar policy as appropriate.getPreferredScrollableViewportSize
method. Refer to Sizing a Scroll Pane for information.Problem:The divider in my split pane does not move!
Problem:The setDividerLocation
method of JSplitPane
does not work.
setDividerLocation(double)
method has no effect if the split pane has no size (typically true if it is not onscreen yet). You can either use setDividerLocation(int)
or specify the preferred sizes of the split pane's contained components and the split pane's resize weight instead. Refer to Positioning the Divider and Restricting Its Range for information.Problem:The borders on nested split panes look too wide.
Problem:The buttons in my tool bar are too big.
button.setMargin(new Insets(0,0,0,0));
Problem: The components in my layered pane are not layered correctly. In fact, the layers seem to be inversed the lower the depth the higher the component.
int
instead of an Integer
when adding components to a layered pane. To see what happens, in the LayeredPaneDemo
class, changelayeredPane.add(label, new Integer(i));
layeredPane.add(label, i);
.Problem:The method call colorChooser.setPreviewPanel(null)
does not remove the color chooser's preview panel as expected.
null
argument specifies the default preview panel. To remove the preview panel, specify a standard panel with no size, like this: colorChooser.setPreviewPanel(new JPanel());