【问题标题】:JButton with image background and text alignment具有图像背景和文本对齐的 JButton
【发布时间】:2014-01-21 21:32:01
【问题描述】:

我又遇到了一个问题:我有一个背景上有图像的 jbutton,但是当我想在上面放一些文字时,它会出现在背景的右侧,而不是在按钮中,而是在旁边... 这是工作代码,您只能链接一些图像:)

package program;

import java.awt.Image;
import java.awt.Insets;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class Program {
    private static JFrame frame;
    private static JPanel panel;
    private static JButton button;
    private static Image buttonImage;
    private static ImageIcon buttonIcon;

    public static void main(String[] args) {
        frame = new JFrame("Program");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        panel = new JPanel();
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
        frame.setSize(200,100);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        String imgUrl = "images/";
        try {
            buttonImage = ImageIO.read(new File(imgUrl+"img.png"));    
        } catch (IOException e) {
            Logger.getLogger(Program.class.getName()).log(Level.SEVERE, null, e);
        }
        buttonIcon = new ImageIcon(buttonImage);
        button = new JButton("TEST", buttonIcon);
        panel.add(button);
        button.setMargin(new Insets(0, 0, 0, 0));
        button.setBounds(0, 0, 146, 67);
        button.setOpaque(false);
        button.setContentAreaFilled(false);
        button.setBorderPainted(false);
    }
}

【问题讨论】:

    标签: java swing jbutton


    【解决方案1】:

    以下是在图像上显示文字的 4 种方法:

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    
    public class LabelImageText extends JPanel
    {
        public LabelImageText()
        {
            JLabel label1 = new JLabel( new ColorIcon(Color.ORANGE, 100, 100) );
            label1.setText( "Easy Way" );
            label1.setHorizontalTextPosition(JLabel.CENTER);
            label1.setVerticalTextPosition(JLabel.CENTER);
            add( label1 );
    
            //
    
            JLabel label2 = new JLabel( new ColorIcon(Color.YELLOW, 200, 150) );
            label2.setLayout( new BoxLayout(label2, BoxLayout.Y_AXIS) );
            add( label2 );
    
            JLabel text = new JLabel( "More Control" );
            text.setAlignmentX(JLabel.CENTER_ALIGNMENT);
            label2.add( Box.createVerticalGlue() );
            label2.add( text );
            label2.add( Box.createVerticalStrut(10) );
    
            //
    
            JLabel label3 = new JLabel( new ColorIcon(Color.GREEN, 200, 150) );
            label3.setLayout( new GridBagLayout() );
            add( label3 );
    
            JLabel text3 = new JLabel();
            text3.setText("<html><center>Text<br>over<br>Image<center></html>");
            text3.setLocation(20, 20);
            text3.setSize(text3.getPreferredSize());
            label3.add( text3 );
    
            //
    
            JLabel label4 = new JLabel( new ColorIcon(Color.CYAN, 200, 150) );
            add( label4 );
    
            JTextPane textPane = new JTextPane();
            textPane.setText("Add some text that will wrap at your preferred width");
            textPane.setEditable( false );
            textPane.setOpaque(false);
            SimpleAttributeSet center = new SimpleAttributeSet();
            StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
            StyledDocument doc = textPane.getStyledDocument();
            doc.setParagraphAttributes(0, doc.getLength(), center, false);
            textPane.setBounds(20, 20, 75, 100);
            label4.add( textPane );
        }
    
        public static class ColorIcon implements Icon
        {
            private Color color;
            private int width;
            private int height;
    
            public ColorIcon(Color color, int width, int height)
            {
                this.color = color;
                this.width = width;
                this.height = height;
            }
    
            public int getIconWidth()
            {
                return width;
            }
    
            public int getIconHeight()
            {
                return height;
            }
    
            public void paintIcon(Component c, Graphics g, int x, int y)
            {
                g.setColor(color);
                g.fillRect(x, y, width, height);
            }
        }
    
        private static void createAndShowUI()
        {
            JFrame frame = new JFrame("LabelImageText");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add( new LabelImageText() );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible( true );
        }
    
        public static void main(String[] args)
        {
            EventQueue.invokeLater(new Runnable()
            {
                public void run()
                {
                    createAndShowUI();
                }
            });
        }
    }
    

    【讨论】:

      【解决方案2】:

      你从来没有设置背景,你设置了按钮的图标

      【讨论】:

      • hm,那么,如何将图像设置为背景? :(
      【解决方案3】:
      import java.awt.*;
      import java.awt.event.*;
      import javax.swing.*;
      
      public class StringTest extends JFrame
              implements ActionListener
      {
        private JTextField input, result;
        private int i;
      
        public StringTest()
        {
          super("String test");
          i=0;
      
          Box box1 = Box.createVerticalBox();
          box1.add(new JLabel(" Input:"));
          box1.add(Box.createVerticalStrut(10));
          box1.add(new JLabel("Result:"));
      
          input = new JTextField(40);
          input.setBackground(Color.WHITE);
          input.addActionListener(this);
          input.selectAll();
      
          result = new JTextField(40);
          result.setBackground(Color.YELLOW);
          result.setEditable(false);
      
          Box box2 = Box.createVerticalBox();
          box2.add(input);
          box2.add(Box.createVerticalStrut(10));
          box2.add(result);
      
          Box box3 = Box.createHorizontalBox(); 
          box3.add(box1);
          box3.add(box2);
      
          Box box4 = Box.createVerticalBox();
          JButton new_game = new JButton("NEW GAME");
          JLabel game_title =new JLabel("***Welcome to Hangman Game***");
          box4.add(game_title);
      
          box4.add(box3);
          box4.add(Box.createVerticalStrut(10));
          box4.add(box3);
          box4.add(Box.createVerticalStrut(10));
          box4.add(new_game);
          new_game.setAlignmentX(Component.CENTER_ALIGNMENT);
      
          Container c = getContentPane();
          c.setLayout(new FlowLayout());
          c.add(box4);
          //c.add(box2);
         // c.add(ok_button);c.add(ok1_button);
          input.requestFocus();
        }
      
      
      
        public void actionPerformed(ActionEvent e)
        {
      
          String str = input.getText();
      
          result.setText(str);
          if (i%2==0)
             result.setBackground(Color.WHITE);
          else
             result.setBackground(Color.YELLOW);
          input.selectAll();
        }
      
        public static void main(String[] args)
        {
          StringTest window = new StringTest();
          window.setBounds(100, 100, 600, 100);
          window.setDefaultCloseOperation(EXIT_ON_CLOSE);
          window.setVisible(true);
        }
      }
      

      【讨论】:

      • 我发现 JButton Alignment Failed 和 JLabel 一起出现。上面的代码 new_game 按钮不在中心。但是,如果您删除 JLabel 游戏标题,它就可以工作。所以这是一个摇摆不定的错误。
      • 当然你可以添加另一个级别box5来分隔JButton和JLabel,然后它就可以了。
      猜你喜欢
      • 2018-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      • 2014-05-11
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      相关资源
      最近更新 更多