在一行中调整图像和文本

时间:2014-02-28 10:13:18

标签: java image swing jlabel swingworker

我有以下代码:

  import java.awt.*;
   import java.awt.event.*;
  import javax.swing.*;

          import java.beans.*;
 import java.util.Random;
@SuppressWarnings("serial")
 public class ProgressBarDemo extends JPanel
                         implements ActionListener, 
                                    PropertyChangeListener {
private JProgressBar progressBar;
private JButton generateButton;
private JButton exceptionButton;
private JTextArea taskOutput;
private Task task;

class Task extends SwingWorker<Void, Void> {
    /*
     * Main task. Executed in background thread.
     */
    @Override
    public Void doInBackground() {
        Random random = new Random();
        int progress = 0;
        //Initialize progress property.
        setProgress(0);
        while (progress < 100) {
            //Sleep for up to one second.
            try {
                Thread.sleep(random.nextInt(1000));
            } catch (InterruptedException ignore) {}
            //Make random progress.
            progress += random.nextInt(10);
            setProgress(Math.min(progress, 100));
        }
        return null;
    }
    /*
     * Executed in event dispatching thread
     */
    @Override
    public void done() {
        Toolkit.getDefaultToolkit().beep();
        generateButton.setEnabled(true);
        setCursor(null); //turn off the wait cursor
        taskOutput.append("Done!\n");
        JFrame newFrame = new JFrame();
        newFrame.setVisible(true);
        JLabel label = new JLabel("Task Complete");
        newFrame.add(label);
        newFrame.setSize(250, 250);
    }
}
public ProgressBarDemo() {
    super(new BorderLayout());

    JPanel labelpanel = new JPanel();

    JLabel headerLabel = new JLabel("", JLabel.LEADING); 
    headerLabel.setText("TEST APPLICATION");  
    headerLabel.setFont(new Font("Calibri",Font.BOLD,25));
    headerLabel.setForeground(Color.blue);

    ImageIcon icon = new ImageIcon("logo.jpg","hiii");
    JLabel imgl=new JLabel(icon);
    labelpanel.add(imgl);
    labelpanel.add(headerLabel);

    imgl.setBounds(10,10, 150, 70);
    //Create the demo's UI.
    generateButton = new JButton("button1");
    generateButton.setActionCommand("button1");
    generateButton.addActionListener(this);
    generateButton.setBounds(50, 200, 150, 30);

    exceptionButton = new JButton("button2");
    exceptionButton.setActionCommand("button2");
    exceptionButton.addActionListener(this);
    exceptionButton.setBounds(50, 300, 150, 30);

    progressBar = new JProgressBar(0, 100);
    progressBar.setValue(0);
    progressBar.setStringPainted(true);
    //progressBar.setBounds(x, y, width, height)

    taskOutput = new JTextArea(5, 20);
    taskOutput.setMargin(new Insets(5,5,5,5));
    taskOutput.setEditable(false);

    JPanel panel = new JPanel();
    labelpanel.add(headerLabel);
    labelpanel.setVisible(true);
    add(labelpanel, BorderLayout.PAGE_START);
   // panel.add(headerLabel);
    panel.add(generateButton);
   // panel.add(progressBar);
    panel.add(exceptionButton);
    labelpanel.setLayout(new BoxLayout(labelpanel,BoxLayout.Y_AXIS));
    add(panel, BorderLayout.LINE_START);
    add(new JScrollPane(taskOutput), BorderLayout.CENTER);
    panel.add(progressBar);
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
/**
 * Invoked when the user presses the start button.
 */
public void actionPerformed(ActionEvent evt) {

    generateButton.setEnabled(false);
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    //Instances of javax.swing.SwingWorker are not reusuable, so
    //we create new instances as needed.
    task = new Task();
    task.addPropertyChangeListener(this);

    task.execute();

}
/**
 * Invoked when task's progress property changes.
 */
public void propertyChange(PropertyChangeEvent evt) {
    if ("progress" == evt.getPropertyName()) {
        int progress = (Integer) evt.getNewValue();
        progressBar.setValue(progress);
        taskOutput.append(String.format(
                "Completed %d%% of task.\n", task.getProgress()));
    } 
}
/**
 * Create the GUI and show it. As with all GUI code, this must run
 * on the event-dispatching thread.
 */
private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("ProgressBarDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new ProgressBarDemo();
    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();
        }
    });
}
}

我有一个图像logo.jpg和文本“测试应用程序”。我希望这两个都在一行。使用上面的代码,图像位于顶部,文本位于下一行。我应该如何修改此代码以将两者都放在一行而不影响框架中存在的其他元素?

1 个答案:

答案 0 :(得分:3)

JLabels可以包含图标和文本,因此您只需将它们添加到同一标签:

JLabel headerLabel = new JLabel("TEST APPLICATION", JLabel.LEADING); 
ImageIcon icon = new ImageIcon("logo.jpg","hiii");
headerLabel.setIcon(icon);

然后你将不再需要imgl

作为旁注,请勿使用绝对布局。你 会遇到问题。请改用布局管理器。