Javaswing选项卡

Python017

Javaswing选项卡,第1张

参考代码

import javax.swing.*

import java.awt.*

public class DemoFrame extends JFrame {

private JTabbedPane tpp

public DemoFrame() {

tpp = new JTabbedPane(JTabbedPane.LEFT) //指定JTabbedPane靠左

JPanel jp1 = new JPanel()

jp1.setBackground(Color.YELLOW)

tpp.add("TabLevel # 1", jp1)

JPanel jp2 = new JPanel()

jp2.setBackground(Color.RED)

tpp.add("TabLevel # 2", jp2)

add(tpp)

setTitle("JTabbedPane Nested Demonstration")

setSize(new Dimension(600, 500))

setLocationRelativeTo(null)

setDefaultCloseOperation(EXIT_ON_CLOSE)

}

public static void main(String[] args) {

DemoFrame main = new DemoFrame()

main.setVisible(true)

}

}

拓展和思考: 

关于修改选项卡之间的距离,增加特效等, 在java swing里 其实自定义组件的外观,一般是继承BasicXxxUI 来实现 .

如果想要实现一些特殊的效果, 也可以自己使用按钮, 标签,面板 等 自己模拟一个 选项卡 .

例如 下面的组件, 就是自己做的一个选项卡的效果, 使用按钮来实现, 当鼠标移动到按钮上时, 按钮变黄. 移开时恢复按钮的初始外观. 当按钮被点击时, 按钮变成白色.  始终只能有一个按钮处于被选中状态. 根据选中按钮的不同, 来展示不同的面板.

又比如下面的选项卡, 是 JPanel 里放入图片和文字 来进行模仿的

swing里

JTabbedPane

下面一个例子:

其中private JTabbedPane tabs = new JTabbedPane()这句是实例化一个选项卡tabs,

tabs.addTab(colorNames[i],panel)这句是向tabs里加一个页面。

import javax.swing.*

import java.awt.*

import java.awt.event.*

import javax.swing.event.*

public class TabbedPaneDemo extends JFrame {

private String[] colorNames = {

"red", "blue", "green", "black",

"yellow", "pink", "white"}

private Color[] colors = {

Color.RED, Color.BLUE, Color.GREEN, Color.BLACK,

Color.YELLOW, Color.PINK, Color.WHITE}

private JTabbedPane tabs = new JTabbedPane()

//private JTabbedPane tabs = new JTabbedPane(JTabbedPane.BOTTOM,

// JTabbedPane.SCROLL_TAB_LAYOUT )

private JTextField txt = new JTextField(20)

public TabbedPaneDemo(String title) {

super(title)

for(int i = 0i <colors.lengthi++){

JPanel panel=new JPanel()

panel.setBackground(colors[i])

tabs.addTab(colorNames[i],panel) //加入一个页面

}

tabs.addChangeListener(new ChangeListener() {

public void stateChanged(ChangeEvent e) {

txt.setText("Tab selected: " +

tabs.getSelectedIndex())

}

})

Container contentPane = getContentPane()

contentPane.add(BorderLayout.SOUTH, txt)

contentPane.add(tabs)

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

pack()

setVisible(true)

}

public static void main(String[] args) {

new TabbedPaneDemo("Hello")

}

}

查看java eclipse 中 search 搜索中每一个选项卡,选项,字段的详解:

①运行Eclipse。

②在菜单栏找到【Help】==》【Help Contents】。

③在弹出窗口做如下图操作。