JavaSwing高级组件:功能与应用详解
立即解锁
发布时间: 2025-08-18 00:08:26 阅读量: 1 订阅数: 9 

### Java Swing高级组件:功能与应用详解
#### 1. 数据操作与文本组件
在数据处理方面,有一些基本的操作方法,例如在指定索引行添加一行数据。同时,还提供了移除指定行以及移动行的功能,具体方法如下:
- `adds a row of data at index row`:在指定索引行添加一行数据。
- `void removeRow(int row)`:从模型中移除指定行。
- `void moveRow(int start, int end, int to)`:将索引在`start`和`end`之间的所有行移动到从`to`开始的新位置。
在文本组件方面,除了常见的`JTextField`和`JTextArea`用于获取用户文本输入外,`JEditorPane`是一个非常有用的类,它可以显示和编辑HTML和RTF格式的文本。不过,RTF格式文档记录不完善,不同微软应用之间兼容性也不佳,这里不做过多介绍。目前,`JEditorPane`存在一定局限性,其HTML渲染器只能显示简单文件,对复杂网页处理能力有限,HTML编辑器也不稳定。但它非常适合用于以HTML格式显示程序帮助文档,因为开发者可以控制帮助文件内容,避开`JEditorPane`显示效果不佳的特性。
以下是一个简单的`JEditorPane`示例程序:
```java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
/**
* This program demonstrates how to display HTML document
* in an editor pane.
*/
public class EditorPaneTest {
public static void main(String[] args) {
JFrame frame = new EditorPaneFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
/**
* This frame contains an editor pane, a text field and b
* to enter a URL and load a document, and a Back button
* return to a previously loaded document.
*/
class EditorPaneFrame extends JFrame {
public EditorPaneFrame() {
setTitle("EditorPaneTest");
setSize(WIDTH, HEIGHT);
final Stack urlStack = new Stack();
final JEditorPane editorPane = new JEditorPane();
final JTextField url = new JTextField(30);
// set up hyperlink listener
editorPane.setEditable(false);
editorPane.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent event) {
if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try {
// remember URL for back button
urlStack.push(event.getURL().toString());
// show URL in text field
url.setText(event.getURL().toString());
editorPane.setPage(event.getURL());
} catch(IOException e) {
editorPane.setText("Exception: " + e);
}
}
}
});
// set up checkbox for toggling edit mode
final JCheckBox editable = new JCheckBox();
editable.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
editorPane.setEditable(editable.isSelected());
}
});
// set up load button for loading URL
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
// remember URL for back button
urlStack.push(url.getText());
editorPane.setPage(url.getText());
} catch(IOException e) {
editorPane.setText("Exception: " + e);
}
}
};
JButton loadButton = new JButton("Load");
loadButton.addActionListener(listener);
url.addActionListener(listener);
// set up back button and button action
JButton backButton = new JButton("Back");
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (urlStack.size() <= 1) return;
try {
// get URL from back button
urlStack.pop();
// show URL in text field
String urlString = (String)urlStack.peek();
url.setText(urlString);
editorPane.setPage(urlString);
} catch(IOException e) {
editorPane.setText("Exception: " + e);
}
}
});
Container contentPane = getContentPane();
contentPane.add(new JScrollPane(editorPane), BorderLayout.CENTER);
// put all control components in a panel
JPanel panel = new JPanel();
panel.add(new JLabel("URL"));
panel.add(url);
panel.add(loadButton);
panel.add(backButton);
panel.add(new JLabel("Editable"));
panel.add(editable);
contentPane.add(panel, BorderLayout.SOUTH);
}
private static final int WIDTH = 600;
private static final int HEIGHT = 400;
}
```
这个示例程序展示了如何使用`JEditorPane`显示HTML页面。用户可以在文本框中输入以`http:`或`file:`开头的URL,点击“Load”按钮加载页面,点击超链接可加载新页面,“Back”按钮可返回上一页。若勾选“Editable”复选框,编辑器面板可编辑,支持基本的文本输入和删除操作,以及复制、粘贴快捷键。但要添加字体和格式支持,还需要进行额外编程。
在使用`JEditorPane`时,有一些重要的方法和注意事项:
- `setPage(URL url)`:从指定URL加载页面到编辑器面板。
- `addHyperlinkListener(HyperLinkListener listener)`:为编辑器面板添加超链接监听器。
- 默认情况下,`JEditorPane`处于编辑模式,可调用`editorPane.setEditable(false)`关闭编辑模式。
#### 2. 组件组织者
为了更好地组织其他组件,有几种非常实用的组件,包括分割面板、选项卡面板和桌面面板。
##### 2.1 分割面板(Split Panes)
分割面板用于将一个组件分割成两部分,中间有可调整的边界。可以通过指定分割方向(`JSplitPane.HORIZONTAL_SPLIT`或`JSplitPane.VERTICAL_SPLIT`)和两个组件来创建分割面板。例如:
```java
JSplitPane innerPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, planetList, planetImage);
```
分割面板还支持一些实用的特性:
- `setOneTouchExpandable(true)`:添加“一键展开”图标,点击图标可将分割条移动到尽头,完全展开其中一个面板。
- `setContinuousLayout(true)`:开启“连续布局”特性,用户调整分割条时,两个组件内容会持续重绘,但可能会影响性能。
以下是一个分割面板的示例程序:
```java
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
/**
* This program demonstrates the split pane component organizer.
*/
public class SplitPaneTest {
public static void main(String[] args) {
JFrame frame = new SplitPaneFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
/**
* This frame consists of two nested split panes to demon
* planet images and data.
*/
class SplitPaneFrame extends JFrame {
public SplitPaneFrame() {
setTitle("SplitPaneTest");
setSize(WIDTH, HEIGHT);
// set up components for planet names, images, desc
final JList planetList = new JList(planets);
final JLabel planetImage = new JLabel();
final JTextArea description = new JTextArea();
planetList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
Planet value = (Planet)planetList.getSelectedValue();
// update image and description
planetImage.setIcon(value.getImage());
description.setText(value.getDescription());
}
});
// set up split panes
JSplitPane innerPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, planetList, planetImage);
innerPane.setContinuousLayout(true);
innerPane.setOneTouchExpandable(true);
JSplitPane outerPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, innerPane, description);
getContentPane().add(outerPane, "Center");
}
private Planet[] planets = {
new Planet("Mercury", 2440, 0),
new Planet("Venus", 6052, 0),
new Planet("Earth", 6378, 1),
new Planet("Mars", 3397, 2),
new Planet("Jupiter", 71492, 16),
new Planet("Saturn", 60268, 18),
new Planet("Uranus", 25559, 17),
new Planet("Neptune", 24766, 8),
new Planet("Pluto", 1137, 1)
};
private static final int WIDTH = 300;
private static final int HEIGHT = 200;
}
/**
* Describes a planet.
*/
class Planet {
/**
* Constructs a planet.
* @param n the planet name
* @param r the planet radius
* @param m the number of moons
*/
public Planet(String n, double r, int m) {
name = n;
radius = r;
moons = m;
image = new ImageIcon(name + ".gif");
}
public String toString() {
return name;
}
/**
* Gets a description of the planet.
* @return the description
*/
public String getDescription() {
return "Radius: " + radius + "\nMoons: " + moons;
}
/**
* Gets an image of the planet.
* @return the image
*/
public ImageIcon getImage() {
return image;
}
private String name;
private double radius;
private int moons;
private ImageIcon image;
}
```
这个示例程序创建了一个包含两个嵌套分割面板的窗口,用户可选择行星列表中的行星,右侧显示行星图片,底部显示行星描述。用户可以调整分割条,体验“一键展开”和“连续布局”特性。
分割面板的创建方法有多种重载形式:
- `JSplitPane()`
- `JSplitPane(int direction)`
- `JSplitPane(int direction, boolean continuousLayout)`
- `JSplitPane(int direction, Component first, Component second)`
- `JSplitPane(int direction, boolean continuousLayout, Component first, Component second)`
同时,还有一些用于获取和设置属性的方法:
- `isOneTouchExpandable()`和`setOneTouchExpandable(boolean b)`:获取和设置“一键展开”属性。
- `isContinuousLayout()`和`setContinuousLayout(boolean b)`:获取和设置“连续布局”属性。
- `setLeftComponent(Component c)`和`setTopComponent(Component c)`:设置分割面板的第一个组件。
- `setRightComponent(Component c)`和`setBottomComponent(Component c)`:设置分割面板的第二个组件。
##### 2.2 选项卡面板(Tabbed Panes)
选项卡面板是一种常见的用户界面组件,用于将复杂对话框拆分为相关选项子集,也可让用户切换一组文档或图像。创建选项卡面板的步骤如下:
1. 创建`JTabbedPane`对象。
2. 使用`addTab`方法添加选项卡,可指定标题、图标和组件。例如:
```java
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab(title, icon, component);
```
3. 若要在选项卡集合中间插入选项卡,可使用`insertTab`方法;移除选项卡使用`removeTabAt`方法。
4. 添加新选项卡后,需调用`setSelectedIndex`方法选择要显示的选项卡。
如果选项卡较多,可通过`setTabLayoutPolicy`方法设置选项卡布局为包裹或滚动模式:
- `tabbedPane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT)`
- `tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT)`
以下是一个选项卡面板的示例程序:
```java
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
/**
* This program demonstrates the tabbed pane component organizer.
*/
public class TabbedPaneTest {
public static void main(String[] args) {
JFrame frame = new TabbedPaneFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
/**
* This frame shows a tabbed pane and radio buttons to
* switch between wrapped and scrolling tab layout.
*/
class TabbedPaneFrame extends JFrame {
public TabbedPaneFrame() {
setTitle("TabbedPaneTest");
setSize(WIDTH, HEIGHT);
final JTabbedPane tabbedPane = new JTabbedPane();
// we set the components to null and delay their
// loading until the tab is shown for the first time
ImageIcon icon = new ImageIcon("yellow-ball.gif");
tabbedPane.addTab("Mercury", icon, null);
tabbedPane.addTab("Venus", icon, null);
tabbedPane.addTab("Earth", icon, null);
tabbedPane.addTab("Mars", icon, null);
tabbedPane.addTab("Jupiter", icon, null);
tabbedPane.addTab("Saturn", icon, null);
tabbedPane.addTab("Uranus", icon, null);
tabbedPane.addTab("Neptune", icon, null);
tabbedPane.addTab("Pluto", icon, null);
getContentPane().add(tabbedPane, "Center");
tabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
// check if this tab still has a null component
if (tabbedPane.getSelectedComponent() == null) {
// set the component to the image icon
int n = tabbedPane.getSelectedIndex();
String title = tabbedPane.getTitleAt(n);
ImageIcon planetIcon = new ImageIcon(title + ".gif");
tabbe
```
0
0
复制全文
相关推荐









