JAVA GUI 中下拉列表框中怎么添加图片

JAVA GUI 中下拉列表框中怎么添加图片,第1张

// 可把代码编译运行

/**

 * 注意标有“重点”两字的注释

 */

import java.awt.BorderLayout

import java.awt.Color

import java.awt.Component

import java.awt.Font

import java.awt.Graphics2D

import java.awt.Rectangle

import java.awt.Transparency

import java.awt.event.WindowAdapter

import java.awt.event.WindowEvent

import java.awt.image.BufferedImage

import javax.swing.ImageIcon

import javax.swing.JDialog

import javax.swing.JLabel

import javax.swing.JList

import javax.swing.JPanel

import javax.swing.ListCellRenderer

/**

 *

 * @author beans

 */

public class TestComboBox {

    public static void main(String[] args) {

        new TestComboBox().showDialog()

    }

    /**

     * 显示窗口

     */

    private void showDialog() {

        JDialog dialog = new JDialog()

        dialog.setBounds(new Rectangle(50, 50, 380, 350))

        dialog.setTitle("组合框")

        dialog.addWindowListener(new WindowAdapter() {

            @Override

            public void windowClosing(WindowEvent e) {

                dialog.setVisible(false)

                dialog.dispose()

            }

        })

        dialog.add(this.getPanel(), BorderLayout.CENTER)

        dialog.setVisible(true)

    }

    private javax.swing.JComboBox<String> comboBox

    private JPanel getPanel() {

        JPanel panel = new JPanel()

        comboBox = new javax.swing.JComboBox<>()

        comboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[]{"Item 1", "Item 2", "Item 3", "Item 4"}))

        

        /**

         * 重点:设置节点渲染器

         */

        comboBox.setRenderer(new NodeRenderer())

        

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(panel)

        panel.setLayout(layout)

        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                .addGroup(layout.createSequentialGroup()

                        .addGap(72, 72, 72)

                        .addComponent(comboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)

                        .addContainerGap(209, Short.MAX_VALUE))

        )

        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                .addGroup(layout.createSequentialGroup()

                        .addGap(52, 52, 52)

                        .addComponent(comboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

                        .addContainerGap(227, Short.MAX_VALUE))

        )

        return panel

    }

    /**

     * 重点:节点渲染器

     */

    protected class NodeRenderer extends JLabel implements ListCellRenderer {

        @Override

        public Component getListCellRendererComponent(JList list, Object value, int index, boolean selected, boolean cellHasFocus) {

            this.setIcon(this.getIcon(selected))

            this.setText("  " + value + " ")

            return this

        }

        /**

         * 图标

         *

         * @param isSelect 选中节点时返回不同的图标。

         * @return

         */

        ImageIcon getIcon(boolean isSelect) {

            int wh = 20

            BufferedImage image = new BufferedImage(wh, wh, BufferedImage.TYPE_INT_ARGB)

            Graphics2D g2 = image.createGraphics()

            image = g2.getDeviceConfiguration().createCompatibleImage(wh, wh, Transparency.TRANSLUCENT)

            Graphics2D g2d = image.createGraphics()

            Font font = new Font("Dialog", Font.PLAIN, wh - 4)

            g2d.setFont(font)

            g2d.setBackground(Color.WHITE)

            g2d.setColor(Color.BLACK)

            g2d.drawString(isSelect ? " S " : " N ", 0, wh - 1)

            g2d.setColor(isSelect ? Color.RED : Color.YELLOW)

            g2d.drawLine(0, 5, wh, 5)

            g2d.drawLine(0, 10, wh, 10)

            g2d.drawLine(0, 15, wh, 15)

            g2d.dispose()

            g2.dispose()

            return new ImageIcon(image)

        }

    }

}

import java.awt.*

import java.awt.event.*

import javax.swing.*

/*

* CustomComboBoxDemo.java 你要有下列文件

* images/Bird.gif

* images/Cat.gif

* images/Dog.gif

* images/Rabbit.gif

* images/Pig.gif

*/

public class CustomComboBoxDemo extends JPanel {

ImageIcon[] images

String[] petStrings = {"Bird", "Cat", "Dog", "Rabbit", "Pig"}

/*

* Despite its use of EmptyBorder, this panel makes a fine content

* pane because the empty border just increases the panel's size

* and is "painted" on top of the panel's normal background. In

* other words, the JPanel fills its entire background if it's

* opaque (which it is by default)adding a border doesn't change

* that.

*/

public CustomComboBoxDemo() {

super(new BorderLayout())

//Load the pet images and create an array of indexes.

images = new ImageIcon[petStrings.length]

Integer[] intArray = new Integer[petStrings.length]

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

intArray[i] = new Integer(i)

images[i] = createImageIcon("images/" + petStrings[i] + ".gif")

if (images[i] != null) {

images[i].setDescription(petStrings[i])

}

}

//Create the combo box.

JComboBox petList = new JComboBox(intArray)

ComboBoxRenderer renderer= new ComboBoxRenderer()

renderer.setPreferredSize(new Dimension(200, 130))

petList.setRenderer(renderer)

petList.setMaximumRowCount(3)

//Lay out the demo.

add(petList, BorderLayout.PAGE_START)

setBorder(BorderFactory.createEmptyBorder(20,20,20,20))

}

/** Returns an ImageIcon, or null if the path was invalid. */

protected static ImageIcon createImageIcon(String path) {

java.net.URL imgURL = CustomComboBoxDemo.class.getResource(path)

if (imgURL != null) {

return new ImageIcon(imgURL)

} else {

System.err.println("Couldn't find file: " + path)

return null

}

}

/**

* Create the GUI and show it. For thread safety,

* this method should be invoked from the

* event-dispatching thread.

*/

private static void createAndShowGUI() {

//Create and set up the window.

JFrame frame = new JFrame("CustomComboBoxDemo")

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

//Create and set up the content pane.

JComponent newContentPane = new CustomComboBoxDemo()

newContentPane.setOpaque(true)//content panes must be opaque

frame.setContentPane(newContentPane)

//Display the window.

frame.pack()

frame.setVisible(true)

}

public static void main(String[] args) {

//Schedule a job for the event-dispatching thread:

//creating and showing this application's GUI.

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {

createAndShowGUI()

}

})

}

class ComboBoxRenderer extends JLabel

implements ListCellRenderer {

private Font uhOhFont

public ComboBoxRenderer() {

setOpaque(true)

setHorizontalAlignment(CENTER)

setVerticalAlignment(CENTER)

}

/*

* This method finds the image and text corresponding

* to the selected value and returns the label, set up

* to display the text and image.

*/

public Component getListCellRendererComponent(

JList list,

Object value,

int index,

boolean isSelected,

boolean cellHasFocus) {

//Get the selected index. (The index param isn't

//always valid, so just use the value.)

int selectedIndex = ((Integer)value).intValue()

if (isSelected) {

setBackground(list.getSelectionBackground())

setForeground(list.getSelectionForeground())

} else {

setBackground(list.getBackground())

setForeground(list.getForeground())

}

//Set the icon and text. If icon was null, say so.

ImageIcon icon = images[selectedIndex]

String pet = petStrings[selectedIndex]

setIcon(icon)

if (icon != null) {

setText(pet)

setFont(list.getFont())

} else {

setUhOhText(pet + " (no image available)",

list.getFont())

}

return this

}

//Set the font and text when no image was found.

protected void setUhOhText(String uhOhText, Font normalFont) {

if (uhOhFont == null) { //lazily create this font

uhOhFont = normalFont.deriveFont(Font.ITALIC)

}

setFont(uhOhFont)

setText(uhOhText)

}

}

}

http://java.sun.com/docs/books/tutorial/uiswing/examples/components/CustomComboBoxDemoProject/src/components/CustomComboBoxDemo.java

Java程序:

import java.awt.*

import java.awt.event.ItemEvent

import java.awt.event.ItemListener

import javax.swing.*

public class Main extends JFrame implements ItemListener {

JComboBox cmbProvince, cmbCity

JTextField txtProvince, txtCity

String[] provinces = {"请选择省份", "北京市", "上海市", "河南省"}

String[][] cities = {{"东城区", "西城区", "海淀区", "丰台区"}, {"浦东区", "徐汇区", "崇明县"}, {"郑州市", "洛阳市", "开封市"}}

public Main() {

super("请选择省份/城市")

this.setSize(350, 200)

this.setVisible(true)

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

this.setLayout(new FlowLayout())

init()

}

public void init() {

cmbProvince = new JComboBox(provinces)

cmbCity = new JComboBox(new String[]{"请选择城市"})

txtProvince = new JTextField(15)

txtCity = new JTextField(15)

this.add(cmbProvince)

this.add(txtProvince)

this.add(cmbCity)

this.add(txtCity)

cmbProvince.addItemListener(this)

cmbCity.addItemListener(this)

}

public static void main(String[] args) {

new Main()

}

@Override

public void itemStateChanged(ItemEvent arg0) {

if(arg0.getStateChange() != ItemEvent.SELECTED){

return

}

JComboBox cmb = (JComboBox) arg0.getSource()

int i

int index

if(cmb == cmbProvince) {

index = cmbProvince.getSelectedIndex()

if(index == 0) {

return

}

cmbCity.removeAllItems()

cmbCity.addItem("请选择城市")

for(i=0 i<cities[index-1].length i++) {

cmbCity.addItem(cities[index-1][i])

}

txtProvince.setText("您选择的省份是:" + cmbProvince.getSelectedItem().toString())

}

else if(cmb == cmbCity) {

index = cmbCity.getSelectedIndex()

if(index == 0) {

return

}

txtCity.setText("您选择的城市是:" + cmb.getSelectedItem().toString())

}

}

}

运行测试:


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11683872.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-17
下一篇 2023-05-17

发表评论

登录后才能评论

评论列表(0条)

保存