ImageIcon img_1 = new ImageIcon("src/menu/btn_1.jpg");
ImageIcon img_2 = new ImageIcon("src/menu/btn_2.jpg");
ImageIcon img_3 = new ImageIcon("src/menu/btn_3.jpg");
ImageIcon img_4 = new ImageIcon("src/menu/btn_4.jpg");
ImageIcon img_5 = new ImageIcon("src/menu/btn_5.jpg");
ImageIcon img_6 = new ImageIcon("src/menu/btn_6.jpg");
ImageIcon img_7 = new ImageIcon("src/menu/btn_7.jpg");
ImageIcon img_8 = new ImageIcon("src/menu/btn_8.jpg");
ImageIcon img_9 = new ImageIcon("src/menu/btn_9.jpg");
bgNumbers = new ButtonGroup();
btnNumbers = new JToggleButton[9];
for (int i = 0; i < 9; i++) {
btnNumbers[i] = new JToggleButton(???);
.....
.....
}
How do I insert the individuals ImageIcon img_1, img_2 ....... img_9 into the loop?
Add them to an array instead of individual variables. – Gábor Bakos Apr 4 at 7:35
Related
I am working on java swing application.I have to browse multiple CSV data files and display them into JFrame using JTable.I am trying to add multiple(non static) JTable into JFrame.All (N) JTable i want to include inside a JSrollPane.At this moment i can display only 1 table to JScrollPane.
Thanks in advance!
if (e.getSource() == jbtreadbrowsefile) {
try {
for(int k=0;k<file_locations.length;k++) {
String currentLocation=file_locations[k];
inputList = new ArrayList();
File inputF = new File(currentLocation);
InputStream inputFS = new FileInputStream(inputF);
BufferedReader br = new BufferedReader(new InputStreamReader(inputFS));
inputList = br.lines().collect(Collectors.toList());
br.close();
int count = inputList.size();
if(count>0)
{
data = new String[count - 1][8];
for (int i = 0; i < count - 1; i++) {
String[] arrOfStr = inputList.get(i + 1).toString().split(",");
String test1= arrOfStr[0];
String test2= arrOfStr[1];
String test3= arrOfStr[2];
String test4 = arrOfStr[3];
String test5= arrOfStr[4];
String test6= arrOfStr[5];
String test7= arrOfStr[6];
data[i][0] = "" + (i + 1);
data[i][1] = test1;
data[i][2] = test2;
data[i][3] = test3;
data[i][4] = test4;
data[i][5] = test5;
data[i][6] = test6;
data[i][7] = test7;
}
j = new JTable(data, columnNames);
TableColumnModel tcm = j.getColumnModel();
tcm.getColumn(0).setPreferredWidth(40);
tcm.getColumn(1).setPreferredWidth(220);
tcm.getColumn(2).setPreferredWidth(120);
tcm.getColumn(3).setPreferredWidth(80);
tcm.getColumn(4).setPreferredWidth(80);
tcm.getColumn(5).setPreferredWidth(80);
tcm.getColumn(6).setPreferredWidth(80);
tcm.getColumn(7).setPreferredWidth(80);
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
j.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
for (int i = 0; i < j.getRowCount(); i++) {
j.setRowHeight(i, 20);
}
j.getTableHeader().setFont(new Font("SansSerif", Font.BOLD, 15));
j.getTableHeader().setReorderingAllowed(false);
j.repaint();
JScrollPane sp = new JScrollPane(j);
sp.setBounds(10, 200, 780, 440);
add(sp);
}
else
{
JOptionPane.showMessageDialog(this,"No Data Found in the File");
}
}
JScrollPane sp = new JScrollPane(j);
sp.setBounds(10, 200, 780, 440);
add(sp);
Don't use setBounds(). It is the job of the layout manager to determine the size/location of a component.
At this moment i can display only 1 table to JScrollPane.
Correct. A JScrollPane is designed to display a single JTable. The header of the JTable will be displayed at the header view of the scroll pane and the table will be displayed in the center of the scroll pane. You may then also see scrollbars in the scroll pane depending on the data in the table.
If you want to "merge" data from multiple files into the same table, then you need to update the TableModel with the data from each file instead of creating a new table each time.
You can dynamically add data to the model by using the addRow(…) method of the DefaultTableModel.
For displaying each JTable into JFrame,i added all JTable into a JPanel and added this JPanel into JScrollPane.After displaying each JTable the problem was that we can not display each JTable header.I added to another JPanel each JTable header and it's shows up.
if (e.getSource() == jbtreadbrowsefile) {
GridLayout grid = new GridLayout(0, 1, 30, 20);
jpaneltable=new JPanel(grid);
try {
for(int k=0;k<file_locations.length;k++) {
String currentLocation=file_locations[k];
inputList = new ArrayList();
File inputF = new File(currentLocation);
InputStream inputFS = new FileInputStream(inputF);
BufferedReader br = new BufferedReader(new InputStreamReader(inputFS));
inputList = br.lines().collect(Collectors.toList());
br.close();
int count = inputList.size();
if(count>0)
{
data = new String[count - 1][8];
for (int i = 0; i < count - 1; i++) {
String[] arrOfStr = inputList.get(i + 1).toString().split(",");
String test1= arrOfStr[0];
String test2= arrOfStr[1];
String test3= arrOfStr[2];
String test4= arrOfStr[3];
String test5= arrOfStr[4];
String test6= arrOfStr[5];
String test7= arrOfStr[6];
data[i][0] = "" + (i + 1);
data[i][1] = test1;
data[i][2] = test2;
data[i][3] = test3;
data[i][4] = test4;
data[i][5] = test5;
data[i][6] = test6;
data[i][7] = test7;
}
j = new JTable(data, columnNames);
TableColumnModel tcm = j.getColumnModel();
tcm.getColumn(0).setPreferredWidth(40);
tcm.getColumn(1).setPreferredWidth(220);
tcm.getColumn(2).setPreferredWidth(120);
tcm.getColumn(3).setPreferredWidth(80);
tcm.getColumn(4).setPreferredWidth(80);
tcm.getColumn(5).setPreferredWidth(80);
tcm.getColumn(6).setPreferredWidth(80);
tcm.getColumn(7).setPreferredWidth(80);
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
j.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
for (int i = 0; i < j.getRowCount(); i++) {
j.setRowHeight(i, 20);
}
j.getTableHeader().setFont(new Font("SansSerif", Font.BOLD, 15));
j.getTableHeader().setReorderingAllowed(false);
j.getTableHeader().setPreferredSize(new Dimension(0,HEADER_HEIGHT));
j.repaint();
jpaneltable.add(j.getTableHeader(),BorderLayout.NORTH);
jpaneltable.add(j, BorderLayout.CENTER);
}
else
{
JOptionPane.showMessageDialog(this,"No Data Found in the File");
}
}
JScrollPane sp = new JScrollPane(jpaneltable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
sp.setBounds(10, 200, 780, 440);
add(sp);
}
Before adding image to JLabel, I used below code to resize them.
BufferedImage myPicture1 = ImageIO.read(new
File("C:\\Users\\yumi\\Desktop\\Salad.png"));
Image scaled1 = myPicture1.getScaledInstance(80,95,Image.SCALE_SMOOTH);
JLabel picLabel1 = new JLabel("Japanese Noodles",new
ImageIcon(scaled1),JLabel.CENTER);
panel.add(picLabel1);
Now I have array, want to store image to array
static private JLabel[] foodLabel;
static private JTextField[] qtyField;
static private ImageIcon[] imageIcon;
static private Image[] imageScaled;
static private BufferedImage[] image;
static private File[] file;
private static final int ELEMENTS = 9;
Trying to read file and scale it
file[0] = new File("C:\\Users\\yumi\\Desktop\\Salad.png");
.....
for (int i = 0; i < ELEMENTS; i++) {
image[i] = ImageIO.read(file[i]);
imageScaled[i] = image[i].getScaledInstance(80,95,Image.SCALE_SMOOTH);
foodLabel[i] = new JLabel(imageIcon([imageScaled[i]])); // error
}
Error
Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem:
Syntax error on token "(", Expression expected after this token
The following should work. You have to create an ImageIcon for your scaled image first.
for (int i = 0; i < ELEMENTS; i++) {
image[i] = ImageIO.read(file[i]);
imageScaled[i] = image[i].getScaledInstance(80,95,Image.SCALE_SMOOTH);
imageIcon[i] = new ImageIcon(imageScaled[i]);
foodLabel[i] = new JLabel(imageIcon[i]);
}
Note that there seems to be no reason to keep all those values in an array. Unless you have more code that references those arrays the following is a bit cleaner:
for (int i = 0; i < ELEMENTS; i++) {
Image image = ImageIO.read(file[i]);
Image imageScaled = image.getScaledInstance(80,95,Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(imageScaled);
foodLabel[i] = new JLabel(imageIcon);
}
I'm trying to learn Java bit by bit, recreating an application I completed in Python - a library control software, very basic. I am having problems, though, with Event Handling, primarily because (I think) I went full-blown in to Swing without knowing much about it, but figuring it out as I went.
Here's my code, so far:
public class SEHBV extends JFrame{
public SEHBV(){
super("SEHBV Biblio 2.0");
ImageIcon img = new ImageIcon("books.ico");
setIconImage(img.getImage());
JPanel p_ini, locar, devolver, buscar, administrar;
JLabel l_dia, l_mes, l_ano, loca_cs, loca_cl, loca_prazo, loca_cb, locado_state;
JTextField dia, mes, ano, loca_cs_tf, loca_cl_tf, loca_prazo_tf, loca_cb_tf, devolve_cod;
JTextArea loca_prazo_data, loca_oper_res, mostra_multa;
JButton data, loca_cb_bt, loca_commit, ver_multa;
JList<String> loca_s_res, loca_cb_res, atrasos, locados;
p_ini = new JPanel(new GridBagLayout());
GridBagConstraints i = new GridBagConstraints();
l_dia = new JLabel("Dia: ");
l_mes = new JLabel("Mês: ");
l_ano = new JLabel("Ano: ");
dia = new JTextField(6);
mes = new JTextField(6);
ano = new JTextField(6);
data = new JButton("Afirmar Data");
atrasos = new JList<String>();
atrasos.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
atrasos.setLayoutOrientation(JList.VERTICAL);
atrasos.setVisibleRowCount(10);
JScrollPane scroll_atrasos = new JScrollPane(atrasos);
atrasos.setBackground(Color.WHITE);
atrasos.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
i.fill = GridBagConstraints.HORIZONTAL;
i.gridx = 0;
i.gridy = 0;
p_ini.add(l_dia, i);
i.gridx = 1;
p_ini.add(dia, i);
i.gridx = 2;
p_ini.add(l_mes, i);
i.gridx = 3;
p_ini.add(mes, i);
i.gridx = 4;
p_ini.add(l_ano, i);
i.gridx = 5;
p_ini.add(ano, i);
i.gridx = 6;
p_ini.add(data, i);
i.gridy = 1;
i.gridx = 0;
i.gridwidth = 7;
p_ini.add(scroll_atrasos, i);
//GUI Locação
locar = new JPanel(new GridBagLayout());
GridBagConstraints l = new GridBagConstraints();
l.gridx = 0;
l.gridy = 0;
JPanel loca_socios = new JPanel(new FlowLayout());
JPanel loca_oper = new JPanel(new GridBagLayout());
GridBagConstraints o = new GridBagConstraints();
JPanel loca_busca = new JPanel(new GridBagLayout());
GridBagConstraints b = new GridBagConstraints();
locar.add(loca_socios, l); //Busca de Sócios na janela de Locação
loca_s_res = new JList<String>();
loca_s_res.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
loca_s_res.setLayoutOrientation(JList.VERTICAL);
loca_s_res.setModel(Runner.nome_socios);
loca_s_res.setVisibleRowCount(25);
JScrollPane scroll_loca_s = new JScrollPane(loca_s_res);
loca_s_res.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
loca_socios.add(scroll_loca_s);
l.gridx = 1;
locar.add(loca_oper, l); //Locação propriamente dita
o.weighty = 1;
o.weightx = 1;
o.anchor = GridBagConstraints.NORTHWEST;
o.insets = new Insets(1,1,1,1);
loca_cs = new JLabel("Código do Sócio: ");
o.fill = GridBagConstraints.HORIZONTAL;
o.gridx = 0;
o.gridy = 0;
loca_oper.add(loca_cs, o);
loca_cs_tf = new JTextField(5);
loca_cs_tf.setEditable(false);
loca_cs_tf.setBackground(Color.WHITE);
o.fill = GridBagConstraints.BOTH;
o.gridx = 1;
o.gridy = 0;
loca_oper.add(loca_cs_tf, o);
loca_cl = new JLabel("Código do Livro: ");
o.fill = GridBagConstraints.BOTH;
o.gridx = 0;
o.gridy = 1;
loca_oper.add(loca_cl, o);
loca_cl_tf = new JTextField(5);
o.fill = GridBagConstraints.BOTH;
o.gridx = 1;
o.gridy = 1;
loca_oper.add(loca_cl_tf, o);
loca_prazo = new JLabel("Prazo para devolução (em dias): ");
o.fill = GridBagConstraints.BOTH;
o.gridx = 0;
o.gridy = 2;
loca_oper.add(loca_prazo, o);
loca_prazo_tf = new JTextField(5);
o.fill = GridBagConstraints.BOTH;
o.gridx = 1;
o.gridy = 2;
loca_oper.add(loca_prazo_tf, o);
loca_prazo_data = new JTextArea();
loca_prazo_data.setBackground(getForeground());
o.gridx = 0;
o.gridy = 3;
o.gridwidth = 3;
loca_oper.add(loca_prazo_data, o);
loca_commit = new JButton("Realizar Locação");
o.fill = GridBagConstraints.BOTH;
o.gridx = 0;
o.gridy = 4;
o.gridwidth = 3;
loca_oper.add(loca_commit, o);
loca_oper_res = new JTextArea();
loca_oper_res.setBackground(getForeground());
o.gridy = 5;
loca_oper.add(loca_oper_res, o);
l.gridx = 2;
locar.add(loca_busca, l);
loca_cb = new JLabel("Chave de Busca: ");
b.fill = GridBagConstraints.HORIZONTAL;
b.gridx = 0;
b.gridy = 0;
loca_busca.add(loca_cb, b);
loca_cb_tf = new JTextField(20);
b.fill = GridBagConstraints.HORIZONTAL;
b.gridx = 1;
b.gridy = 0;
loca_busca.add(loca_cb_tf, b);
loca_cb_bt = new JButton("Busca Rápida");
b.fill = GridBagConstraints.HORIZONTAL;
b.gridx = 2;
b.gridy = 0;
loca_busca.add(loca_cb_bt, b);
loca_cb_res = new JList<String>();
loca_cb_res.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
loca_cb_res.setLayoutOrientation(JList.VERTICAL);
b.fill = GridBagConstraints.HORIZONTAL;
loca_cb_res.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
b.gridx = 0;
b.gridy = 1;
b.gridwidth = 3;
b.gridheight = 2;
loca_cb_res.setVisibleRowCount(25);
JScrollPane scroll_loca_cb = new JScrollPane(loca_cb_res);
loca_cb_res.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
loca_busca.add(scroll_loca_cb, b);
// Other Tabs of the GUI
//GUI Geral
JTabbedPane tp = new JTabbedPane();
tp.addTab("Página inicial (Alt+I)", null, p_ini, "pág. inicial");
tp.addTab("Locação (Alt+L)", locar);
tp.addTab("Devolução (Alt+D)", devolver);
tp.addTab("Busca Avançada (Alt+B)", buscar);
tp.addTab("Administração (Alt+A)", administrar);
tp.setMnemonicAt(0, KeyEvent.VK_I);
tp.setMnemonicAt(1, KeyEvent.VK_L);
tp.setMnemonicAt(2, KeyEvent.VK_D);
tp.setMnemonicAt(3, KeyEvent.VK_B);
tp.setMnemonicAt(4, KeyEvent.VK_A);
add(tp);
}
So, lets say I'm trying to handle the clicking of the loca_commit JButton. I'm trying to create an Event Handler - according to Java tutorials and other StackOverflow questions/answers - but the handler does not identify loca_commit. Right now I'm just trying to get it to work, then I'll use it for calling a method, but if I can't make it create a pop up, well, you get my point.
So, my code for the handler so far is this:
private class LocaHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
String string = "";
if(event.getSource()==loca_commit)
string=String.format("Botão Apertado");
JOptionPane.showMessageDialog(null, string);
}
Can you guys shed a light here?
The core issue is probably one of context, the LocaHandler probably doesn't have any context to SEHBV or the loca_commit button, so you can't reference it (it's out of context).
There are couple of ways you might fix this...
You could...
Pass a reference of loca_commit to the instance of LocaHandler, but unless you intended to make use of LocaHandler to handle multiple actions, it really doesn't make sense, which means...
You could...
Make LocaHandler responsible for only doing one thing, what ever loca_commit needs it to. This leads you into the realm of the Actions API
How ever...
You could...
Make use of the actionCommand property support of JButton and ActionEvent
loca_commit = new JButton("Realizar Locação");
loca_commit.setActionCommand("locaCommit");
//...
private class LocaHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
String string = "";
if("locaCommit".equals(event.getActionCommand()))
string=String.format("Botão Apertado");
JOptionPane.showMessageDialog(null, string);
}
This means that you could use the same instance of LocaHandler to handle multiple commands (by expanding the if statement)
My personal preference is to use the Actions API or anonymous classes, focusing on the handlers to a single responsibility, if done well, it will increase the reusability of the classes
One way of making it work is to attach action listener on button after initializing it. In your case, try the following:
loca_commit = new JButton("Realizar Locação");
//other code
loca_commit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Hello");
}
});
loca_oper.add(loca_commit, o);
Remember, this is just one way of doing it. There are multiple other ways to achieve the same result.
I have used below code but did not work properly. I have list of JButton objects on the panel but could not click on each button individually.
for(int i=0; i<udataArr.length(); i++) {
userBtn = new JButton();
userLb = new JLabel();
cur1 = userBtn.getCursor();
userBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
Image imgUO = ImageIO.read(getClass().getResource("/resources/img-std.png"));
userBtn.setIcon(new ImageIcon(imgUO));
userBtn.setBorder(BorderFactory.createCompoundBorder(border,paddingBorder));
userLb.setText((String) udataArr.getJSONObject(i).get("user_name"));
//button[i].setText((String) udataArr.getJSONObject(i).get("user_name"));
panelLeft.add(userBtn);
panelLeft.add(userLb);
panelLeft.add(Box.createVerticalStrut(15));
}
This is the code to create JButton Array
JButton buttons[];
buttons = new JButton[10];
for(int i = 0; i < 10; i++) {
buttons[i] = new JButton(String.valueOf(i));
}
I'm trying to create a java program that generates 10 playing cards. The playing cards are in gif format. I have tried to put these in an array, but do not know how I get on. The playing cards should ideally be displayed without the strict placement. The cards are left anyway. Would need tips to get ahead. As it stands now, I get no error message. But the box that comes up, is empty. What should I do?
Thanks in advance
cards.java
public abstract class cards extends JPanel {
Random gen = new Random();
int noOfCards = 10;
int line;
int col;
boolean faceUp;
String back = "img/b2fv.gif";
JLabel[] stackLabel = new JLabel[noOfCards];
ImageIcon[] stack = new ImageIcon[noOfCards];
ImageIcon [][] cards = {
{new ImageIcon("img/c1.gif"), new ImageIcon("img/d1.gif"), new ImageIcon("img/h1.gif") , new ImageIcon("img/s1.gif")},
{new ImageIcon("img/c2.gif"), new ImageIcon("img/d2.gif"), new ImageIcon("img/h2.gif") , new ImageIcon("img/s2.gif")},
{new ImageIcon("img/c3.gif"), new ImageIcon("img/d3.gif"), new ImageIcon("img/h3.gif") , new ImageIcon("img/s3.gif")},
{new ImageIcon("img/c4.gif"), new ImageIcon("img/d4.gif"), new ImageIcon("img/h4.gif") , new ImageIcon("img/s4.gif")},
{new ImageIcon("img/c5.gif"), new ImageIcon("img/d5.gif"), new ImageIcon("img/h5.gif") , new ImageIcon("img/s5.gif")},
{new ImageIcon("img/c6.gif"), new ImageIcon("img/d6.gif"), new ImageIcon("img/h6.gif") , new ImageIcon("img/s6.gif")},
{new ImageIcon("img/c7.gif"), new ImageIcon("img/d7.gif"), new ImageIcon("img/h7.gif") , new ImageIcon("img/s7.gif")},
{new ImageIcon("img/c8.gif"), new ImageIcon("img/d8.gif"), new ImageIcon("img/h8.gif") , new ImageIcon("img/s8.gif")},
{new ImageIcon("img/c9.gif"), new ImageIcon("img/d9.gif"), new ImageIcon("img/h9.gif") , new ImageIcon("img/s9.gif")},
{new ImageIcon("img/c10.gif"), new ImageIcon("img/d10.gif"), new ImageIcon("img/h10.gif") , new ImageIcon("img/s10.gif")},
{new ImageIcon("img/cj.gif"), new ImageIcon("img/dj.gif"), new ImageIcon("img/hj.gif") , new ImageIcon("img/sj.gif")},
{new ImageIcon("img/cq.gif"), new ImageIcon("img/dq.gif"), new ImageIcon("img/hq.gif") , new ImageIcon("img/sq.gif")},
{new ImageIcon("img/ck.gif"), new ImageIcon("img/dk.gif"), new ImageIcon("img/hk.gif") , new ImageIcon("img/sk.gif")},
{new ImageIcon("img/jr.gif"), new ImageIcon("img/jb.gif")}
};
public JLabel[] genCards(){
try{
for(int i = 0; i < noOfCards; i++){
line = gen.nextInt(14);
col = gen.nextInt(4);
faceUp = gen.nextBoolean();
stack[i] = cards[line][col];
stackLabel[i] = new JLabel();
ImageIcon img;
stackLabel[i].setIcon(img = stack[i]);
this.add(stackLabel[i]);
}
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);
System.out.println("Problem med array");
}
return stackLabel;
}
}
table.java
public class table extends cards {
public void paintComponent(Graphics g){
super.paintComponent(g);
for(int i = 0; i < this.stackLabel.length; i++){
//System.out.println(stack[i]);
}
}
ImageIcon is a Swing component, so just add those ImageIcons to a container like a JPanel (perhaps that Cards extends JPanel you have). The container itself draws the Swing components it contains, so you don't have to manually draw them.
At least you have to call to genCards() somewhere. Probably in constructor or a init method:
public Cards(){
genCards();
}