2015-04-12 8 views
-2

Я знаю, мне все еще нужно преобразовать строку в int и удвоить для providerID и providerPrice, чтобы я мог их установить, а затем сохранить позже; Я ожидаю, что смогу это понять. Кажется, что я не могу найти, как правильно настроить JLabels. Метка cloudBack должна быть основным фоном, и каждый набор JLabel и JTextField должен быть на отдельной строке, перекрывающей основной фон, с 3 JButtons внизу. Как заставить их идти в нужные места? btw источник .png - 400x224 пикселей package newprovider;Как заставить перекрытие JLabels

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

/*@Michael Christopher, author/owner */ 
public class NewProvider { 
/** @param args the command line arguments*/ 
public static void createGUI() { 
    // Create the window 
    JFrame mainFrame = new JFrame ("NewProvider"); 
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    //Create the MenuBar 
    JMenuBar maintenanceMenuBar = new JMenuBar(); 
    maintenanceMenuBar.setOpaque(true); 
    maintenanceMenuBar.setBackground(new Color(176,224,230)); 
    maintenanceMenuBar.setPreferredSize(new Dimension(400, 20)); 

    //create variables 
    int providerID; 
    String providerName; 
    Double providerPrice; 
    int addProviderCheck; 
    String[] options = {"Yes","No"}; 

    //create image icon, labels, and JTextFields 
    JLabel cloudBack; 
    cloudBack = new JLabel (new ImageIcon("images/CloudBack.png")); 
    JLabel labelID = new JLabel ("New ProviderID"); 
    JTextField textID = new JTextField("providerID \n", 10); 
    JLabel labelName = new JLabel ("New Provider Name"); 
    JTextField textName = new JTextField("Provider Name \n", 20); 
    JLabel labelPrice = new JLabel ("New Provider Price"); 
    JTextField textPrice = new JTextField ("Price \n", 5); 
    //make Submit, Clear, & Exit buttons 
    JButton submit = new JButton("Submit"); 
    JButton clear = new JButton("Clear"); 
    JButton exit = new JButton("Exit"); 

    /*Set the FlowLayout to arrange the window, setting labels, text fields, 
    menubar, background, and orientation*/ 
    FlowLayout newProviderLayout = new FlowLayout(); 
    mainFrame.setLayout(newProviderLayout); 
    mainFrame.setJMenuBar(maintenanceMenuBar); 
    mainFrame.add(cloudBack, BorderLayout.CENTER); 
    mainFrame.add(labelID); 
    mainFrame.add(textID); 
    mainFrame.add(labelName); 
    mainFrame.add(textName); 
    mainFrame.add(labelPrice); 
    mainFrame.add(textPrice); 
    mainFrame.add(submit); 
    mainFrame.add(clear); 
    mainFrame.add(exit); 

    //ActionListener for Submit button 
    submit.addActionListener(new ActionListener() 
    {   public void actionPerformed(ActionEvent e) { 
        String ID = textID.getText(); 
        String Name = textName.getText(); 
        String Price = textPrice.getText(); 
      int submitPress = JOptionPane.showOptionDialog(null, 
    "ProviderID: " + ID + "\n" + "Provider Name: " + Name +"\n" + "Provider Price: " + Price, 
    "Please Verify Content",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE,null, options,options[0]); 
if (submitPress <= 0) {     
    //Store Displayed data 
    System.out.println(ID); 
    System.out.println(Name); 
    System.out.println(Price); 
    /*providerID = ID; 
    providerName = Name; 
    providerPrice = Price; */ 
    textID.setText("Confirmed"); 
} 
else if (submitPress > 0) {  
      textID.setText("providerID"); 
      textName.setText("Provider Name"); 
      textPrice.setText("Price"); } 
     } 
    }); 
    //ActionListener for clear button 
    clear.addActionListener(new ActionListener() 
    { @Override 
     public void actionPerformed(ActionEvent e) { 
      textID.setText("providerID"); 
      textName.setText("Provider Name"); 
      textPrice.setText("Price"); } 
    }); 
    //ActionListener for Exit Button 
    exit.addActionListener(new ActionListener() 
    { @Override 
     public void actionPerformed(ActionEvent e) { 
      mainFrame.setVisible(false); 
      mainFrame.dispose(); } 
    }); 
//verify intent to add new provider to system before continuing 
addProviderCheck = JOptionPane.showOptionDialog(null, 
    "This will add a new service provider to the database.\n" 
    + "Are you sure you wish to continue?", 
    "Please Verify Intent",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null, options,options[0]); 
if (addProviderCheck <= 0) { 
       //Display Window 
    mainFrame.pack(); 
    mainFrame.setSize(400, 400); 
    mainFrame.setVisible(true);} 
else { //else close app 
    mainFrame.setVisible(false); 
    mainFrame.dispose(); 
} 
} 
public static void main(String[] args){ 
    //draw and show the GUI 
    javax.swing.SwingUtilities.invokeLater(() -> { 
     createGUI(); 
    });   
    //store new provider data 
    } 
} 
+0

Обратите внимание, что вы разместили не компилируемый код. Пожалуйста, исправьте это. –

+1

Для примера [http://stackoverflow.com/questions/24176008/background-image-for-a-jpanel-not-working/24176183#24176183), [пример] (http://stackoverflow.com/questions/22162398/how-to-set-a-background-picture-in-jpanel/22162430 # 22162430), [пример] (http://stackoverflow.com/questions/18393971/having-images-as-background-of- jpanel/18394047 # 18394047) – MadProgrammer

+0

@ Hovercraft Full Of Eels - пакет newprovider; должен был находиться в блоке кода как верхняя строка; кроме этого, это копия> вставки моего рабочего кода - это все, что вы имели в виду, или есть большая проблема, которую мне не хватает? MadProgrammer - просматривая ваши примеры, ty. Второй ответ на воздушной подушке - спасибо. Я собираюсь провести сегодня, глядя на JPanel и paintComponent, а также на другие 2 макета, на которые вы ссылались. –

ответ

2

Вместо displayiing вашего CloudBack.jpg в JLabel, рассмотреть вопрос о разработке его в методе paintComponent JPanel, используя g.drawImage(...), а затем устанавливать ваши другие компоненты на этом рисунке JPanel. Обратите внимание, что если вы добавите какие-либо другие JPanels на чертеж JPanel, убедитесь, что нерисовые JPanels установлены как непрозрачные с помощью setOpaque(false).

Я также предлагаю, чтобы вы не использовали FlowLayout в качестве основного графического интерфейса GUI, так как он не будет добавлять ваши компоненты в приятный, простой в использовании и вид. Рассмотрите возможность использования GridBagLayout или MigLayout в дополнение к BorderLayout.

+0

Я исправил все функционально, хотя я еще не получил изменений в макете - мне нужно посмотреть JPanels завтра. Помимо этого, любые проблемы в новом коде, которые будут созданы при реализации JPanel с drawImage и GridBagLayout? (Я действительно смотрел эту часть вверх lol) - изменить - я не могу опубликовать новый код, потому что он слишком длинный для комментариев ... предложений? –

Смежные вопросы