Я создал программу для генерации случайных чисел, вещей, животных, имен и прочего, но иногда дублированные значения отображаются в JTable;Any Есть ли способ их удалить?
Я имею в виду, что, когда я прошу свою программу отобразить значения стран, иногда Арджелия ставится дважды;Итак, как я могу удалить эти значения из моего массива и как правильно отображать их в моем JTable?
- Самое короткое, если это возможно.
- Тот, который занимает меньше строк кода.
Наконец, спасибо, что уделили мне время на помощь: D
Essential:
String [][] values = new String[15][4];
String [] raw = {
"Marta","Pedro","Rodrigo","Juan","José","Francisco",
"Guadalupe","María","Juana","Antonio","Jesús","Manuel"
};
for (String[] value : values) {
for (int j = 0; j < 4; j++) {
value[j] = raw[((int)(Math.random()*raw.length-1))];
System.out.println(value[j]);
}
}
Полный код (на всякий случай):
/**
* Makes easier the filling of random data in Excel
* by providing several value options and functions
*
* @author Steven Merino
*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
class RandomValues extends JFrame implements ActionListener, ChangeListener {
//Class fields
JButton generate;
JLabel title, columnNum, rowNum;
JScrollPane scroll;
JTextField columnData, rowData;
JRadioButton numberBox, countryBox, cityBox, nameBox, objectBox, animalBox;
ButtonGroup cluster;
JTable display;
static int defRowNum = 15, defColumnNum = 4;
String countries [] = {
"Afganistán","Albania","Alemania","Andorra","Angola","Antigua y Barbuda",
"Arabia Saudita","Argelia","Argentina","Armenia","Australia","Austria",
"Azerbaiyán","Bahamas","Bangladés","Barbados","Baréin","Bélgica","Belice",
"Benín","Bielorrusia","Birmania","Bolivia","Bosnia y Herzegovina","Botsuana",
"Brasil","Brunéi","Bulgaria","Burkina Faso","Burundi","Bután","Cabo Verde",
"Camboya","Camerún","Canadá","Catar","Chad","Chile","China","Chipre",
"Ciudad del Vaticano","Colombia","Comoras","Corea del Norte","Corea del Sur",
"Costa de Marfil","Costa Rica","Croacia","Cuba","Dinamarca"
};
String cities []= {
"Reikiavik","Lisboa","Londres","Madrid","París","Argel","Bruselas","Ámsterdam",
"Zúrich","Fráncfort","Oslo","Roma","Copenhague","Berlín","Estocolmo","Budapest",
"Varsovia","Ciudad del Cabo","Sofía","Atenas","Helsinki","Estambul","Kiev",
"El Cairo","Jerusalén","Adís Abeba","Yeda","Teherán","Moscú","Dubái","Kabul",
"Karachi","Delhi","Katmandú","Daca","Rangún","Novosibirsk","Bangkok"
};
String names [] = {
"Juan","José","Francisco","Guadalupe","María","Juana","Antonio","Jesús","Pedro",
"Alejandro","Manuel","Margarita","Roberto","Fernando","Daniel","Carlos","Jorge",
"Ricardo","Miguel","Eduardo","Javier","Rafael","Martín","Raúl","David","Josefina",
"Arturo","Enrique","Verónica","Gerardo","Leticia","Rosa","Mario","Francisca",
"Alfredo","Teresa","Alicia","Sergio","Alberto"
};
String objects [] = {
"Chaleco","Pantalones","Camisetas","Botas","Zapatillas deporte","Chanclas goma",
"Gorras","Pañuelos cuello","Gafas de sol cerradas","Toalla oscura","Calcetines",
"Pilas","Cargador móvil","Cámara foto","Cámara vídeo","Cargadores","Roaming",
"Pinzas ropa","Bolígrafos","Palillos de dientes","Mochila de diario","Pasaporte",
"Mapas","Medicación diaria","Linterna de frente","Conversor 12v a 220v",
"Enchufe múltiple mechero","Linterna","Extintor","Nevera","Cámaras de neumático",
"Permiso de circulación","Seguro y carta verde","Juego de llaves","Botiquín",
"Emisora de 27 mhz","Compresor"
};
String animals [] = {
"Águila","Alacrán","Albatros","Boa","Bongo","Cangrejo","Caracol","Ciempiés",
"Ciervo","Cisne","Gato","Gavilán","Golondrina","Gorila","Gorgojo","Perezoso",
"Pingüino","Pinzón","Piojo","Piquituerto","Polilla","Termita","Tiburón","Tigre",
"Topo","Toro","Tortuga","Zarigüeya","Zorro","Zebra","Mariposa","Marmota",
"Medusa","Mejillón","Milpiés","Mofeta","Mono","Mosca"
};
public RandomValues () {
setLayout(null);
//Title
title = new JLabel("Generador de valores aleatorios");
title.setBounds(160,10,300,30);
add(title);
//Copy random values to Excel
display = new JTable();
display.setTableHeader(null);
display.setRowHeight(20);
scroll = new JScrollPane(display);
scroll.setBounds(20,45,445,365);
add(scroll);
//Generate random values
generate = new JButton("Generar valores");
generate.setBounds(150,420,200,30);
generate.addActionListener(this);
add(generate);
//Column number guide
columnNum = new JLabel("Nº Filas");
columnNum.setBounds(30,490,100,30);
add(columnNum);
//Row number guide
rowNum = new JLabel("Nº Columnas");
rowNum.setBounds(30,460,100,30);
add(rowNum);
//Number of columns
columnData = new JTextField();
columnData.setBounds(110,465,100,20);
add(columnData);
//Number of rows
rowData = new JTextField();
rowData.setBounds(110,495,100,20);
add(rowData);
//Category options
cluster = new ButtonGroup();
numberBox = new JRadioButton("Números");
numberBox.setBounds(220,465,80,20);
numberBox.addChangeListener(this);
add(numberBox);
cluster.add(numberBox);
countryBox = new JRadioButton("Paises");
countryBox.setBounds(220,495,80,20);
countryBox.addChangeListener(this);
add(countryBox);
cluster.add(countryBox);
cityBox = new JRadioButton("Ciudades");
cityBox.setBounds(300,465,80,20);
cityBox.addChangeListener(this);
add(cityBox);
cluster.add(cityBox);
nameBox = new JRadioButton("Nombres");
nameBox.setBounds(300,495,80,20);
nameBox.addChangeListener(this);
add(nameBox);
cluster.add(nameBox);
objectBox = new JRadioButton("Cosas");
objectBox.setBounds(380,465,250,20);
objectBox.addChangeListener(this);
add(objectBox);
cluster.add(objectBox);
animalBox = new JRadioButton("Animales");
animalBox.setBounds(380,495,250,20);
animalBox.addChangeListener(this);
add(animalBox);
cluster.add(animalBox);
}
public static void main (String [] args) {
//Creates JFrame
RandomValues random = new RandomValues();
random.setSize(500,570);
random.setLocationRelativeTo(null);
random.setResizable(false);
random.setVisible(true);
random.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
void random(String [] raw) {
//Checks whether it has to use defValue or userValue for columns
if(!"".equals(columnData.getText())){
String p = columnData.getText();
defColumnNum = Integer.parseInt(columnData.getText());
}
//Checks whether it has to use defValue or userValue for rows
if(!"".equals(rowData.getText())){
String p = rowData.getText();
defRowNum = Integer.parseInt(rowData.getText());
}
//Fulfills the table's header array
String [] hidden = new String[defColumnNum];
for (int i = 0; i < hidden.length; i++) {
hidden[i]=String.valueOf(i+1);
}
//Fulfills the table's value array
String [][] values = new String[defRowNum][defColumnNum];
//-----------------------------------------------------------------------
for (String[] value : values) {
for (int j = 0; j < defColumnNum; j++) {
double randomNums = (Math.random()*1)+9;
value[j] = raw == null? String.format("%.2f",randomNums):raw[((int)(Math.random()*raw.length-1))];
}
}
//-----------------------------------------------------------------------
//Assigns the number of columns and rows with their values
DefaultTableModel model = new DefaultTableModel(values,hidden);
display.setModel(model);
for (int i = 0; i < defColumnNum; i++) {
TableColumn column = display.getColumnModel().getColumn(i++);
column.setMinWidth(40);
}
}
@Override
public void actionPerformed(ActionEvent e) {
//Uses the checked category
if (numberBox.isSelected()) {
random(null);
}
if (countryBox.isSelected()) {
random(countries);
}
if (cityBox.isSelected()) {
random(cities);
}
if (nameBox.isSelected()) {
random(names);
}
if (objectBox.isSelected()) {
random(objects);
}
if (animalBox.isSelected()) {
random(animals);
}
}
@Override public void stateChanged(ChangeEvent e) {}
}