Я хотел создать несколько выпадающих списков в том же графическом интерфейсе. Я хотел расположить их в соответствии с (x, y), и поэтому мне пришлось делать: .setLayout (null); Не уверен, что это вызвало проблемы. Однако, когда я пытаюсь щелкнуть любое раскрывающееся меню, ни один из них не открывается (просто ничего не происходит), а другой выпадающий список (на этой странице несколько) получает фокус. что-то действительно странное .. и я уверен, что я не сделал это правильно. Я добавляю код здесь. он построен из 3-х различных классов (каждый класс в собственном файле). если кто-то может запустить код как есть и просто увидеть поведение, возможно, вы узнаете, что его вызывает. Еще одна вещь. программы читаются из файла с именем: Menu.txt. файл должен быть в основной директории из Netbeans проектов и должны иметь следующие строки (точные линии):JcomboBox не открывается при щелчке и теряет фокус на соседнем объекте
Файл: Menu.txt => Содержание:
Суши Chips
20,0
Главная Potetos
5,0
Суп моркови
10,0
горячий кофе
5,0
Первый файл: ItemInMenu.java:
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JTextField;
public class ItemInMenu {
int itemAmount, itemType, maxOrderAmountPerItem=50;
double itemPrice;
String itemDisc;
JComboBox itemComboBox;
JCheckBox itemCheckBox;
JTextField itemTextField;
public ItemInMenu(double itemPrice, String itemDisc, int itemType){
this.itemCheckBox = new JCheckBox("Select Item");
this.itemTextField = new JTextField();
this.itemComboBox = new JComboBox();
this.itemAmount = 0;
this.itemType = itemType;
this.itemPrice = itemPrice;
this.itemDisc = itemDisc;
//Add options to the dropdown (max 50 items to be ordered fro meach item)
for (int i=0; i<maxOrderAmountPerItem; i++)
{
this.itemComboBox.addItem("Amount: " + i);
}
}
}
Теперь второй класс. MainFunction.java:
import javax.swing.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static java.lang.Integer.*;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class MainFunction {
public static void main(String[] args) {
int defaultWidth = 900, defaultHeight = 600;
JFrame frame = new JFrame("Maman 13 - Question 1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(defaultWidth,defaultHeight);
//Adding the option not to resize the window.
frame.setResizable(false);
// Creation of a MyPanel object (which belongs to a class which inherits from JPanel class) //
MyPanel newPanel = new MyPanel();
//The .setLayot(null) is a line that disables the Layout manager and lets us position
//items by ourselves (manual positioning of elements like Jcombo and such). We do
//this line on the JPanel element (and not on the frame....).
newPanel.setLayout(null);
frame.add(newPanel);
newPanel.readFromFile("Menu.txt");
newPanel.printMenu();
frame.setVisible(true);
}
}
И третий файл: MyPanel.java:
import java.awt.Color;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class MyPanel extends JPanel {
private ArrayList<ItemInMenu> itemsList = new ArrayList();
private String fileName;
public void readFromFile(String whichFile)
{
ItemInMenu newItem;
int lineNumber, itemType = -1;
Double itemPrice = -1.0;
String currentLine, itemDisc = "";
this.fileName = whichFile;
//Now lets start reading this file...
System.out.println("Reading from File: " + this.fileName);
File myFile = new File(this.fileName);
try {
lineNumber = 0;
Scanner myScanner = new Scanner(myFile);
while (myScanner.hasNext())
{
lineNumber++;
currentLine = myScanner.nextLine();
System.out.println(currentLine);
if (lineNumber == 1)
{
itemDisc = currentLine;
}
else if (lineNumber == 2)
{
itemType = Integer.parseInt(currentLine);
}
else
{
itemPrice = Double.parseDouble(currentLine);
newItem = new ItemInMenu(itemPrice, itemDisc, itemType);
this.itemsList.add(newItem);
lineNumber = 0;
}
//System.out.println(currentLine);
}
myScanner.close();
}
catch (FileNotFoundException ex)
{
System.out.println("File Not Found!");
}
}
public void printMenu(){
for (ItemInMenu tmpVar : this.itemsList)
{
System.out.println("Printing Item Details:");
System.out.print("Item Disc: " + tmpVar.itemDisc + "\nItem Price: " + tmpVar.itemPrice + "\nItem Quantity: " + tmpVar.itemAmount + "\nItem Type: " + tmpVar.itemType + "\n\n");
}
}
// The function who update the graphics of JPanel on every operation of the user (resize etc') //
public void paintComponent(Graphics g) {
int xLeftBox = 5, xCenterBox = 305, xRightBox = 605;
int yLeftBox = 5, yCenterBox = 5, yRightBox = 5;
int comboBoxWidth = 100, comboBoxHeight=25, spaceBetweenItems=100;
super.paintComponent(g);
//Now start drawing your own painting.
for (ItemInMenu tmpVar : this.itemsList)
{
if (tmpVar.itemType == 1)
{
tmpVar.itemComboBox.setBounds(xLeftBox, yLeftBox, comboBoxWidth, comboBoxHeight);
yLeftBox += spaceBetweenItems;
}
else if (tmpVar.itemType == 2)
{
tmpVar.itemComboBox.setBounds(xCenterBox, yCenterBox, comboBoxWidth, comboBoxHeight);
yCenterBox += spaceBetweenItems;
}
else
{
tmpVar.itemComboBox.setBounds(xRightBox, yRightBox, comboBoxWidth, comboBoxHeight);
yRightBox += spaceBetweenItems;
}
tmpVar.itemComboBox.setSelectedIndex(-1);
tmpVar.itemComboBox.addActionListener(
new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
JComboBox combo = (JComboBox)e.getSource();
String currentQuantity = (String)combo.getSelectedItem();
System.out.println(currentQuantity);
}
}
);
this.add(tmpVar.itemComboBox);
}
}
}
Надеется, что вы будете хорошо работает это .. спасибо за помощь.