I am trying to create a JList with some elements and when the user selects an element another JList will appear in the window. Then, if the user selects an element of the other list a text area will appear in the window. Here is what I have made so far :
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class ProductsList extends JFrame implements ItemListener {
private JLabel availableDev;
private JComboBox avDevBox
private JTextArea itemDetails;
private JList Items;
private JList devicesForSale;
private JList imandSJList;
private JList applJList;
private JList gamJList;
public ProductsList() {
String[] avDevicesListItems = {"Image and Sound", "Appliance", "Gaming"};
ArrayList<imageAndSound> iasList = new ArrayList<imageAndSound>;
ArrayList<Appliance> applianceList = new ArrayList<Appliance>;
ArrayList<Gaming> gamingList = new ArrayList<Gaming>;
//construct components
availableDev = new JLabel ("Available Devices");
avDevicesList = new JList (avDevicesListItems);
itemDetails = new JTextArea (5, 5);
avDevBox = new JComboBox (avDevicesListItems);
devicesForSale = new JList(devList);
imandSJList = new JList(iasList);
applJList = new JList(applianceList);
gamJList = new JList(gamingList);
avDevBox.addItemListener(this);
//adjust size and set layout
setPreferredSize (new Dimension (944, 574));
setLayout (null);
//add components
add (availableDev);
add (avDevicesList);
add (itemDetails);
add (avDevBox);
add(devicesForSale);
//set component bounds
availableDev.setBounds (35, 0, 100, 25);
avDevBOx.setBounds (25, 30, 120, 25);
itemDetails.setBounds (245, 225, 265, 215);
public void itemStateChanged(ItemEvent event) {
int choice = avDevBox.getSelectedIndex();
if (choice = 0) {
add(imandSJList);
imandSJList.addItemListener(this);
}
else if (choice = 1){
add(applJList);
applJList.addItemListener(this);
}
else {
add(gamJList);
gamJList.addItemListener(this);
}
}
public static void main (String[] args) {
JFrame frame = new JFrame ("Products List");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new MyPanel());
frame.pack();
frame.setVisible (true);
TV tv1 = new TV("LCD","28","720p","HDMI/DVI","11235","AT142","2015","SONY",500,5); //Creates object of class TV
TV tv2 = new TV("LED","32","1080p","HDMI/DVI","15394","AT168","2016","SAMSUNG",1000,0); //Creates object of class TV
bluerayDVD dvd = new bluerayDVD("DVD","720p","DVD-RW","15642","TT172","2015","SONY",400,100); //Creates object of class bluerayDVD
bluerayDVD blueray = new bluerayDVD("blueray","1080p","BD-R","18412","TT100","2015","SONY",500,1000); //Creates object of class bluerayDVD
Camera cam1 = new Camera("DSLR","50","stable","x5","2","19785","TC137","2016","SONY",600,50); //Creates object of class Camera
Camera cam2 = new Camera("compact,","40","stable","x7","1","16783","TC108","2016","SONY",700,70); //Creates object of class Camera
Console c1 = new Console("PS4","RGEN","1080p","Dolby","1 TB","15641","TG142","2016","SONY",400,80); //Creates object of class Console
Console c2 = new Console("XBOX","RGEN2","1080p","Dolby Digital","2 TB","13424","TG123","2016","MICROSOFT",400,10); //Creates object of class Console
Refrigerator f1 = new Refrigerator("Single door","C++","5kg","2kg","28756","TF357","2016","BOSS",1500,10); //Creates object of class Refrigerator
Refrigerator f2 = new Refrigerator("Double door","C++","8kg","4kg","26756","TF382","2016","SIEMENS",500,5); //Creates object of class Refrigerator
WashMachines wM1 = new WashMachines("C++","2kg","200rs","49356","TW364","2016","SIEMENS",3000,10); //Creates object of class WashMachines
WashMachines wM2 = new WashMachines("C++","4kg","250rs","49579","TW376","2016","BOSS",5000,10); //Creates object of class WashMachines
imandSJList.add(tv1);
imandSJList.add(tv2);
imandSJList.add(dvd);
imandSJList.add(blueray);
imandSJList.add(cam1);
imandSJList.add(cam2);
gamJList.add(c1);
gamJList.add(c2);
applJList.add(f1);
applJList.add(f2);
applJList.add(wM1);
applJList.add(wM2);
}
}
So if any body could suggest a better way, I would be very glad
Thank You
Similarly you can keep on adding listener directly to each list
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class JListDemo extends JFrame {
public JListDemo() {
setSize(new Dimension(300, 300));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
final JLabel label = new JLabel("Update");
String[] data = { "one", "two", "three", "four" };
final JList dataList = new JList(data);
dataList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent arg0) {
if (!arg0.getValueIsAdjusting()) {
label.setText(dataList.getSelectedValue().toString());
}
}
});
add(dataList);
add(label);
setVisible(true);
}
public static void main(String args[]) {
new JListDemo();
}
}
Related
I am trying to make my program so that an integer value entered in a JTextfield can be stored into a variable. Then, when a JButton is clicked, this variable can tell a JSlider to move it's head to that of the integer value stored in the variable. My class name is Camera.Java
Code is showing no errors, however if I click my JButton, nothing happens, instead I see this error in the console:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at Camera.main(Camera.java:67)
My code:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;
import java.util.Scanner;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.*;
public class Camera {
static JButton addtolist;
static Scanner input = new Scanner(System.in);
static JSlider cam = new JSlider();
static JTextField enterval = new JTextField();
static int x ;
public static void main (String args[]){
JFrame myFrame = new JFrame ("Matthew Damon on Mars");
myFrame.setSize(300, 600);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel userinp = new JLabel("Enter input: ");
cam = new JSlider(0, 15, 0);
cam.setPaintLabels(true);
enterval.setPreferredSize(new Dimension(100,80));
addtolist = new JButton("Enter");
addtolist.setPreferredSize(new Dimension(50,20));
JTextField enterval1 = new JTextField();
panel.add(addtolist);
Hashtable<Integer, JLabel> table = new Hashtable<Integer, JLabel>();
table.put(0, new JLabel("0"));
table.put(1, new JLabel("1"));
table.put(2, new JLabel("2"));
table.put(3, new JLabel("3"));
table.put(4, new JLabel("4"));
table.put(5, new JLabel("5"));
table.put(6, new JLabel("6"));
table.put(7, new JLabel("7"));
table.put(8, new JLabel("8"));
table.put(9, new JLabel("9"));
table.put(10, new JLabel("A"));
table.put(11, new JLabel("B"));
table.put(12, new JLabel("C"));
table.put(13, new JLabel("D"));
table.put(14, new JLabel("E"));
table.put(15, new JLabel("F"));
cam.setLabelTable(table);
myFrame.add(cam, BorderLayout.SOUTH);
myFrame.add(userinp, BorderLayout.NORTH);
myFrame.add(enterval1, BorderLayout.NORTH);
myFrame.add(panel, BorderLayout.CENTER);
myFrame.setVisible(true);
buttonAction();
}
public static void buttonAction() {
addtolist.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int x = Integer.parseInt(enterval.getText());
cam.setValue(x);
} catch (NumberFormatException npe) {
// show a warning message
}
}
});
}
}
Your setting x on program creation before the user has had any chance to change its value. Get the text value from within the actionPerformed method which should be after the user has already selected a value, parse it into a number and set the slider with that value.
public void actionPerformed(ActionEvent e) {
try {
int x = Integer.parseInt(enterval.getText());
cam.setValue(x);
} catch (NumberFormatException npe) {
// show a warning message
}
}
Then get rid of all that static nonsense. The only method that should be static here is main, and it should do nothing but create an instance and set it visible.
Note that better than using a JTextField, use a JSpinner or a JFormattedTextField or if you're really stuck, a DocumentFilter to limit what the user can enter
Again, you should put most everything into the instance realm and out of the static realm. This means getting most of that code outside of the main method and into other methods and constructors, that means not trying to access fields or methods from the class, but rather from the instance. For instance, your main method should only create the main instances, hook them up and set them running and that's it. It should not be used to build the specific GUI components. For example:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class CameraFoo extends JPanel {
// only static field here is a constant.
private static String TEXTS = "0123456789ABCDEF";
private JSpinner spinner = new JSpinner();
private JSlider slider = new JSlider(0, 15, 0);
public CameraFoo() {
List<Character> charList = new ArrayList<>();
Hashtable<Integer, JLabel> table = new Hashtable<>();
for (int i = 0; i < TEXTS.toCharArray().length; i++) {
char c = TEXTS.charAt(i);
String myText = String.valueOf(c);
JLabel label = new JLabel(myText);
table.put(i, label);
charList.add(c);
}
SpinnerListModel spinnerModel = new SpinnerListModel(charList);
spinner.setModel(spinnerModel);
slider.setLabelTable(table);
slider.setPaintLabels(true);
JPanel topPanel = new JPanel();
topPanel.add(spinner);
topPanel.add(new JButton(new ButtonAction("Press Me")));
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(slider);
}
private class ButtonAction extends AbstractAction {
public ButtonAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
char ch = (char) spinner.getValue();
int value = TEXTS.indexOf(ch);
slider.setValue(value);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
private static void createAndShowGui() {
CameraFoo mainPanel = new CameraFoo();
JFrame frame = new JFrame("CameraFoo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
In this code I am trying to insert a JScrollPane into my panel which is using the MigLayout.
import java.awt.*;
import javax.swing.*;
import net.miginfocom.swing.MigLayout;
public class Simple2
{
JFrame simpleWindow = new JFrame("Simple MCVE");
JPanel simplePanel = new JPanel();
JLabel lblTitle;
JLabel lblSimple;
JTextArea txtSimple;
JScrollPane spSimple;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String []fontFamilies = ge.getAvailableFontFamilyNames();
public void numberConvertGUI()
{
simpleWindow.setBounds(10, 10, 285, 170);
simpleWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
simpleWindow.setLayout(new GridLayout(1,1));
createSimplePanel();
simpleWindow.getContentPane().add(simplePanel);
simpleWindow.setVisible(true);
simpleWindow.setResizable(false);
}
public void createSimplePanel()
{
MigLayout layout = new MigLayout("" , "[][grow]");
simplePanel.setLayout(layout);
lblTitle = new JLabel();
lblTitle.setText("This is a Title");
simplePanel.add(lblTitle, "wrap, align center,span 2");
lblSimple = new JLabel();
lblSimple.setText("Next to me is a JTextArea: ");
simplePanel.add(lblSimple);
txtSimple = new JTextArea();
txtSimple.setLineWrap(false);
txtSimple.setWrapStyleWord(true);
spSimple = new JScrollPane(txtSimple);
simplePanel.add(txtSimple,"width 100:100:100 , height 100:100:100");
}
public static void main(String[] args)
{
Simple2 s = new Simple2();
s.numberConvertGUI();
}
}
However when the text gets to the end of the JTextArea and continues off the screen there are no scroll bars horizontally or vertically. I am unsure of what I am doing wrong.
With txtSimple.setLineWrap(false);
With txtSimple.setLineWrap(true);
Edit
My desired outcome is to have scroll bars on the scroll pane
The code which provided these samples is
import java.awt.*;
import javax.swing.*;
import java.lang.Object.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.event.*;
import java.awt.Checkbox;
public class TextAreaSample extends JFrame implements ActionListener
{
JFrame myMainWindow = new JFrame("This is my title");
JTabbedPane myTabs = new JTabbedPane();
JPanel firstPanel = new JPanel(); //a panel for first tab
//first panel components
JTextArea txtSimple;
JLabel lblSimple;
JScrollPane myScrollTable;
JCheckBox TextWrap;
//end first panel
public void runGUI()
{
myMainWindow.setBounds(10, 10, 800, 800); //set position, then dimensions
myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myMainWindow.setLayout(new GridLayout(1,1));
createFirstPanel(); //call method to create each panel
myMainWindow.getContentPane().add(firstPanel); //adds the tabbedpane to mainWindow
myMainWindow.setVisible(true); //make the GUI appear
}
public void createFirstPanel()
{
firstPanel.setLayout(null);
txtSimple = new JTextArea();
txtSimple.setLineWrap(false);
txtSimple.setWrapStyleWord(true);
myScrollTable = new JScrollPane(txtSimple);
myScrollTable.setSize(700,700);
myScrollTable.setLocation(20,20);
firstPanel.add(myScrollTable);
System.out.println("Creating compare table");
lblSimple = new JLabel();
lblSimple.setText("Text Wrap");
lblSimple.setSize(100,25);
lblSimple.setLocation(20,730);
lblSimple.setHorizontalAlignment(JLabel.RIGHT);
firstPanel.add(lblSimple);
TextWrap = new JCheckBox();
TextWrap.setLocation(125,730);
TextWrap.setSize(25,25);
TextWrap.addActionListener(this);
firstPanel.add(TextWrap);
}
public void actionPerformed(ActionEvent e)
{
if(TextWrap.isSelected())
{
txtSimple.setLineWrap(true);
}
else
{
txtSimple.setLineWrap(false);
}
}
public static void main(String[] args)
{
TextAreaSample TSA = new TextAreaSample();
TSA.runGUI();
}
}
Here's the issue:
spSimple = new JScrollPane(txtSimple);
simplePanel.add(txtSimple,"width 100:100:100 , height 100:100:100");
You're not adding the JScrollPane to the layout. You need this:
spSimple = new JScrollPane(txtSimple);
simplePanel.add(spSimple,"width 100:100:100 , height 100:100:100");
Notice the use of spSimple in the second line.
My program is supposed to have the basic code examples in java and to do that I need help to have the dialogues where I can write have the code preloaded but I can't add spaces in the dialogues and resize them. Please help!
Main Class:
public class JavaHelperTester{
public static void main(String[] args){
JavaWindow display = new JavaWindow();
JavaHelper j = new JavaHelper();
display.addPanel(j);
display.showFrame();
}
}
Method Class:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class JavaHelper extends JPanel implements ActionListener{
JButton print = new JButton("Print Statements");
JButton classes = new JButton("Classes");
JButton varibles = new JButton("Assiging variables");
JButton signs = new JButton("Sign meanings");
JButton typesv = new JButton("Different Types of variables");
JButton scanners = new JButton("Scanner");
JButton loops = new JButton("Loops");
JButton ifstatements = new JButton("If statements");
JButton graphics = new JButton("Graphics");
JButton objects = new JButton("Making an oject");
JButton importstatments = new JButton("Import Statements");
JButton integers = new JButton("Different types of integers");
JButton methods = new JButton("Scanner methods");
JButton math = new JButton("Math in java");
JButton creation = new JButton("Method creation");
JButton arrays = new JButton("Arrays");
JButton jframe = new JButton("JFrame");
JButton stringtokenizer = new JButton("String Tokenizer");
JButton extending = new JButton("Class extending");
JButton fileio = new JButton("File I.O.");
JButton quit = new JButton("Quit");
public JavaHelper(){
setPreferredSize(new Dimension(500,350));
setBackground(Color.gray);
this.add(print);
print.addActionListener(this);
this.add(classes);
classes.addActionListener(this);
this.add(varibles);
varibles.addActionListener(this);
this.add(signs);
signs.addActionListener(this);
this.add(typesv);
typesv.addActionListener(this);
this.add(scanners);
scanners.addActionListener(this);
this.add(loops);
loops.addActionListener(this);
this.add(ifstatements);
ifstatements.addActionListener(this);
this.add(graphics);
graphics.addActionListener(this);
this.add(objects);
objects.addActionListener(this);
this.add(importstatments);
importstatments.addActionListener(this);
this.add(integers);
integers.addActionListener(this);
this.add(methods);
methods.addActionListener(this);
this.add(math);
math.addActionListener(this);
this.add(creation);
creation.addActionListener(this);
this.add(arrays);
arrays.addActionListener(this);
this.add(jframe);
jframe.addActionListener(this);
this.add(stringtokenizer);
stringtokenizer.addActionListener(this);
this.add(fileio);
fileio.addActionListener(this);
this.add(quit);
quit.addActionListener(this);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == print){
JOptionPane.showMessageDialog (null, "System.out.println(); and System.out.print();", "Print Statements", JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource() == classes){
JOptionPane.showMessageDialog (null, "Main class : public class ClassNameTester{ // public static void main(String[] args){, Other Classes : public class ClassName", "Classes", JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource() == quit){
System.exit(0);
}
}
private void dialogSize(){
}
}
JavaWindow:
import java.awt.*;
import javax.swing.*;
public class JavaWindow extends JFrame{
private Container c;
public JavaWindow(){
super("Java Helper");
c = this.getContentPane();
}
public void addPanel(JPanel p){
c.add(p);
}
public void showFrame(){
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I made changes to clean up the Java Helper GUI and to allow you to format the information on the JOptionPane dialogs.
Here's the Java Helper GUI.
And here's the Classes JOptionPane.
I modified your JavaHelperTester class to include a call to the SwingUtilities invokeLater method. This method puts the creation and use of your Swing components on the Event Dispatch thread (EDT). A Swing GUI must start with a call to the SwingUtilities invokeLater method.
I also formatted all of your code and resolved the imports.
package com.ggl.java.helper;
import javax.swing.SwingUtilities;
public class JavaHelperTester {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JavaWindow display = new JavaWindow();
JavaHelper j = new JavaHelper();
display.addPanel(j);
display.showFrame();
}
};
SwingUtilities.invokeLater(runnable);
}
}
Here's your JavaWindow class.
package com.ggl.java.helper;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JavaWindow extends JFrame {
private static final long serialVersionUID = 6535974227396542181L;
private Container c;
public JavaWindow() {
super("Java Helper");
c = this.getContentPane();
}
public void addPanel(JPanel p) {
c.add(p);
}
public void showFrame() {
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
And here's your JavaHelper class. I made the changes to your action listener to allow you to define the text as an HTML string. You may only use HTML 3.2 commands.
I also changed your button panel to use the GridLayout. The grid layout makes your buttons look neater and makes it easier for the user to select a JButton.
package com.ggl.java.helper;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class JavaHelper extends JPanel implements ActionListener {
private static final long serialVersionUID = -3150356430465932424L;
JButton print = new JButton("Print Statements");
JButton classes = new JButton("Classes");
JButton varibles = new JButton("Assiging variables");
JButton signs = new JButton("Sign meanings");
JButton typesv = new JButton("Different Types of variables");
JButton scanners = new JButton("Scanner");
JButton loops = new JButton("Loops");
JButton ifstatements = new JButton("If statements");
JButton graphics = new JButton("Graphics");
JButton objects = new JButton("Making an oject");
JButton importstatments = new JButton("Import Statements");
JButton integers = new JButton("Different types of integers");
JButton methods = new JButton("Scanner methods");
JButton math = new JButton("Math in java");
JButton creation = new JButton("Method creation");
JButton arrays = new JButton("Arrays");
JButton jframe = new JButton("JFrame");
JButton stringtokenizer = new JButton("String Tokenizer");
JButton extending = new JButton("Class extending");
JButton fileio = new JButton("File I.O.");
JButton quit = new JButton("Quit");
public JavaHelper() {
this.setLayout(new GridLayout(0, 2));
setBackground(Color.gray);
this.add(print);
print.addActionListener(this);
this.add(classes);
classes.addActionListener(this);
this.add(varibles);
varibles.addActionListener(this);
this.add(signs);
signs.addActionListener(this);
this.add(typesv);
typesv.addActionListener(this);
this.add(scanners);
scanners.addActionListener(this);
this.add(loops);
loops.addActionListener(this);
this.add(ifstatements);
ifstatements.addActionListener(this);
this.add(graphics);
graphics.addActionListener(this);
this.add(objects);
objects.addActionListener(this);
this.add(importstatments);
importstatments.addActionListener(this);
this.add(integers);
integers.addActionListener(this);
this.add(methods);
methods.addActionListener(this);
this.add(math);
math.addActionListener(this);
this.add(creation);
creation.addActionListener(this);
this.add(arrays);
arrays.addActionListener(this);
this.add(jframe);
jframe.addActionListener(this);
this.add(stringtokenizer);
stringtokenizer.addActionListener(this);
this.add(fileio);
fileio.addActionListener(this);
this.add(quit);
quit.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == print) {
String title = ((JButton) e.getSource()).getText();
JLabel label = new JLabel(createPrintText());
JOptionPane.showMessageDialog(this, label, title,
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getSource() == classes) {
String title = ((JButton) e.getSource()).getText();
JLabel label = new JLabel(createClassesText());
JOptionPane.showMessageDialog(this, label, title,
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getSource() == quit) {
System.exit(0);
}
}
private String createPrintText() {
StringBuilder builder = new StringBuilder();
builder.append("<html><pre><code>");
builder.append("System.out.print()");
builder.append("<br>");
builder.append("System.out.println()");
builder.append("</code></pre>");
return builder.toString();
}
private String createClassesText() {
StringBuilder builder = new StringBuilder();
builder.append("<html><pre><code>");
builder.append("Main class : public class ClassNameTester { <br>");
builder.append(" public static void main(String[] args) { <br>");
builder.append(" } <br>");
builder.append("} <br><br>");
builder.append("Other Classes : public class ClassName { <br>");
builder.append("}");
builder.append("</code></pre>");
return builder.toString();
}
}
I have created 2 classes that are working together to show pictures by clicking different buttons. In my EventEvent class I tried to make it so that when you press the "Picture 1" button, the variable ImageIcon xpic gets the value of ImageIcon vpic (which holds an image), after xpic has the same value as vpic my frame is supposed to somehow refresh so that xpic's new value applies and gets then shows the picture.
Why doesn't my image show up even though the button press repaints the JPanel the image is in?
Main class:
import java.awt.*;
import javax.swing.*;
public class EventMain extends JFrame{
EventEvent obje = new EventEvent(this);
// Build Buttons
JButton picB1;
JButton picB2;
JButton picB3;
JButton picB4;
JButton picB5;
//Build Panels
JPanel row0;
//Build Pictures
ImageIcon xpic;
ImageIcon vpic;
public EventMain(){
super("Buttons");
setLookAndFeel();
setSize(470, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout layout1 = new GridLayout(3,4);
setLayout(layout1);
picB1 = new JButton("Picture 1");
picB2 = new JButton("Picture 2");
picB3 = new JButton("Picture 3");
picB4 = new JButton("Picture 4");
picB5 = new JButton("Picture 5");
vpic = new ImageIcon(getClass().getResource("Images/vanessa.png"));
// Set up Row 0
row0 = new JPanel();
JLabel statement = new JLabel("Choose a picture: ", JLabel.LEFT);
JLabel picture = new JLabel(xpic);
// Set up Row 1
JPanel row1 = new JPanel();
// Set up Row 2
JPanel row2 = new JPanel();
//Listeners
picB1.addActionListener(obje);
FlowLayout grid0 = new FlowLayout (FlowLayout.CENTER);
row0.setLayout(grid0);
row0.add(statement);
row0.add(picture);
add(row0);
FlowLayout grid1 = new FlowLayout(FlowLayout.CENTER);
row1.setLayout(grid1);
row1.add(picB1);
row1.add(picB2);
add(row1);
FlowLayout grid2 = new FlowLayout(FlowLayout.CENTER);
row2.setLayout(grid2);
row2.add(picB3);
row2.add(picB4);
row2.add(picB5);
add(row2);
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.NimbusLookAndFeel");
} catch (Exception exc) {
}
}
public static void main(String[] args) {
EventMain con = new EventMain();
}
}
Class containing events:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventEvent implements ActionListener {
EventMain gui;
public EventEvent(EventMain in){
gui = in;
}
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("Picture 1")){
gui.xpic = gui.vpic;
gui.row0.repaint();
}
}
}
You're confusing variables with objects. Just because you change the object associated with the xpic variable, don't assume that this will change the object (the Icon) held by the JLabel. There is no magic in Java, and changing the object that a variable refers to will have no effect on the prior object.
In other words, this:
gui.xpic = gui.vpic;
gui.row0.repaint();
will have no effect on the icon that the picture JLabel is displaying
To swap icons, you must call setIcon(...) on the JLabel. Period. You will need to make the picture JLabel a field, not a local variable, and give your GUI class a public method that allows outside classes to change the state of the JLabel's icon.
Also, you should not manipulate object fields directly. Instead give your gui public methods that your event object can call.
Edit
For example:
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class MyGui extends JPanel {
public static final String IMAGE_PATH = "https://duke.kenai.com/cards/.Midsize/CardFaces.png.png";
private static final int ROWS = 4;
private static final int COLS = 13;
private BufferedImage largeImg;
private List<ImageIcon> iconList = new ArrayList<>();
private JLabel pictureLabel = new JLabel();
private JButton swapPictureBtn = new JButton(new SwapPictureAction(this, "Swap Picture"));
private int iconIndex = 0;
public MyGui() throws IOException {
add(pictureLabel);
add(swapPictureBtn);
URL imgUrl = new URL(IMAGE_PATH);
largeImg = ImageIO.read(imgUrl);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
int x = (j * largeImg.getWidth()) / COLS;
int y = (i * largeImg.getHeight()) / ROWS;
int w = largeImg.getWidth() / COLS;
int h = largeImg.getHeight() / ROWS;
iconList.add(new ImageIcon(largeImg.getSubimage(x, y, w, h)));
}
}
pictureLabel.setIcon(iconList.get(iconIndex));
}
public void swapPicture() {
iconIndex++;
iconIndex %= iconList.size();
pictureLabel.setIcon(iconList.get(iconIndex));
}
private static void createAndShowGui() {
MyGui mainPanel;
try {
mainPanel = new MyGui();
JFrame frame = new JFrame("MyGui");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class SwapPictureAction extends AbstractAction {
private MyGui myGui;
public SwapPictureAction(MyGui myGui, String name) {
super(name);
this.myGui = myGui;
}
#Override
public void actionPerformed(ActionEvent e) {
myGui.swapPicture();
}
}
See the createAction() method below and how it creates an AbstractAction. See also the tutorial related to using actions with buttons. http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html
import javax.swing.*;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import java.awt.*;
import java.awt.event.ActionEvent;
public class EventMain {
private static final ImageIcon PICTURE_1 = new ImageIcon(EventMain.class.getResource("images/v1.png"));
private static final ImageIcon PICTURE_2 = new ImageIcon(EventMain.class.getResource("images/v2.png"));
private JFrame frame;
EventMain create() {
setLookAndFeel();
frame = createFrame();
frame.getContentPane().add(createContent());
return this;
}
void show() {
frame.setSize(470, 300);
frame.setVisible(true);
}
private JFrame createFrame() {
JFrame frame = new JFrame("Buttons");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
return frame;
}
private Component createContent() {
final JLabel picture = new JLabel();
JButton picB1 = new JButton(createAction("Picture 1", picture, PICTURE_1));
JButton picB2 = new JButton(createAction("Picture 2", picture, PICTURE_2));
JButton picB3 = new JButton(createAction("Picture 3", picture, PICTURE_1));
JButton picB4 = new JButton(createAction("Picture 4", picture, PICTURE_2));
JButton picB5 = new JButton(createAction("Picture 5", picture, PICTURE_1));
JLabel statement = new JLabel("Choose a picture: ", JLabel.LEFT);
// Create rows 1, 2, 3
JPanel panel = new JPanel(new GridLayout(3, 4));
panel.add(createRow(statement, picture));
panel.add(createRow(picB1, picB2));
panel.add(createRow(picB3, picB4, picB5));
return panel;
}
/**
* Create an action for the button. http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html
*/
private Action createAction(String label, final JLabel picture, final Icon icon) {
AbstractAction action = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
picture.setIcon(icon);
}
};
action.putValue(Action.NAME, label);
return action;
}
private Component createRow(Component... componentsToAdd) {
JPanel row = new JPanel(new FlowLayout(FlowLayout.CENTER));
for (Component component : componentsToAdd) {
row.add(component);
}
return row;
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(new NimbusLookAndFeel());
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new EventMain().create().show();
}
});
}
}
Guys I have a problem with my JTable, my JTable(tblLivro) which contents should be the result(ArrayList) of my query (working) , but when I try to put the rsult in my jtable it just doesn't work, it doesn't show any errors, yet not show it. Why?
Here is my code
package view;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import model.Livro;
import control.LivroControl;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
public class LivroView extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel lblIdLivro, lblLombada, lblTitulo, lblTituloInternacional, lblEdicao, lblEditora, lblAutor ;
private JTextField txtIdLivro, txtTombo, txtTitulo, txtTituloInternacional, txtEdicao, txtEditora, txtAutor;
private JButton btnAdicionar, btnPesquisar, btnExcluir;
private JPanel painelPrincipal, painelGeral, painelBotoes, painelJPanel;
private JTable tblLivros;
private List<Livro> encontrados;
DefaultTableModel modelo;
public LivroView() {
super("Manutenção de Livros");
encontrados = new ArrayList<Livro>();
lblIdLivro = new JLabel("Código do livro:");
lblLombada = new JLabel("Tombo:");
lblTitulo = new JLabel("Título:");
lblTituloInternacional = new JLabel("Título Internacional:");
lblEdicao = new JLabel("Edição:");
lblEditora = new JLabel("Editora:");
lblAutor = new JLabel("Autor:");
txtIdLivro = new JTextField(20);
txtTombo= new JTextField("Tombo");
txtTitulo = new JTextField(20);
txtTituloInternacional= new JTextField(20);
txtEdicao = new JTextField(20);
txtEditora= new JTextField(20);
txtAutor= new JTextField("Autor");
txtIdLivro.setText("");
txtTombo.setText("");
txtTitulo.setText("");
txtTituloInternacional.setText("");
txtEdicao.setText("");
txtEditora.setText("");
txtAutor.setText("");
btnAdicionar = new JButton("Adicionar");
btnExcluir = new JButton("Excluir");
btnPesquisar = new JButton("Pesquisar");
btnAdicionar.addActionListener(this);
btnPesquisar.addActionListener(this);
btnExcluir.addActionListener(this);
painelPrincipal = new JPanel();
painelGeral = new JPanel();
painelBotoes = new JPanel();
painelJPanel = new JPanel();
painelPrincipal.setLayout(new BorderLayout());
painelGeral.setLayout(new GridLayout(7,2));
painelBotoes.setLayout(new GridLayout(2,1));
painelGeral.add(lblIdLivro);
painelGeral.add(txtIdLivro);
painelGeral.add(lblLombada);
painelGeral.add(txtTombo);
painelGeral.add(lblTitulo);
painelGeral.add(txtTitulo);
painelGeral.add(lblTituloInternacional);
painelGeral.add(txtTituloInternacional);
painelGeral.add(lblEdicao);
painelGeral.add(txtEdicao);
painelGeral.add(lblEditora);
painelGeral.add(txtEditora);
painelGeral.add(lblAutor);
painelGeral.add(txtAutor);
painelBotoes.add(btnAdicionar);
painelBotoes.add(btnPesquisar);
painelBotoes.add(btnExcluir);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(55, 80, 359, 235);
painelJPanel.add(scrollPane);
tblLivros = new JTable();
tblLivros.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Tombo", "T\u00EDtulo", "T\u00EDtulo Internacional", "Edi\u00E7\u00E3o", "Autor", "Editora"
}
));
modelo = new DefaultTableModel();
tblLivros.getColumnModel().getColumn(0).setPreferredWidth(54);
tblLivros.getColumnModel().getColumn(1).setPreferredWidth(104);
tblLivros.getColumnModel().getColumn(2).setPreferredWidth(136);
tblLivros.getColumnModel().getColumn(4).setPreferredWidth(102);
// modelo = (DefaultTableModel) tblLivros.getModel();
scrollPane.setViewportView(tblLivros);
painelJPanel.setLayout(null);
painelPrincipal.add(painelGeral, BorderLayout.NORTH);
painelPrincipal.add(painelBotoes, BorderLayout.CENTER);
this.setSize(500,300);
this.setVisible(true);
this.setContentPane(painelPrincipal);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
LivroControl control = new LivroControl();
if ("Adicionar".equalsIgnoreCase(cmd)){
boolean adicionado = false;
adicionado = control.adicionarLivro(txtIdLivro.getText(), txtTitulo.getText(), txtTituloInternacional.getText(), txtTombo.getText(), txtAutor.getText(), txtEdicao.getText(), txtEditora.getText());
if (adicionado == true){
txtIdLivro.setText("");
txtTombo.setText("");
txtTitulo.setText("");
txtTituloInternacional.setText("");
txtEdicao.setText("");
txtEditora.setText("");
txtAutor.setText("");
txtIdLivro.requestFocus();
}
}
else if("Excluir".equalsIgnoreCase(cmd)){
control.excluirLivro(txtTombo.getText());
txtTombo.setText("");
}
else if("Pesquisar".equalsIgnoreCase(cmd)){
if (!txtTombo.getText().equals("")){
Livro l = control.pesquisarLivroPorTombo(txtTombo.getText());
if (l!=null){
txtIdLivro.setText(String.valueOf(l.getIdLivro()));
txtTombo.setText(l.getTombo());
txtTitulo.setText(l.getTitulo());
txtTituloInternacional.setText(l.getTituloInternacional());
txtEdicao.setText(l.getEdicao());
txtEditora.setText(l.getEditora());
txtAutor.setText(l.getAutor());
}
}
else if (!txtAutor.getText().equals("")){
encontrados = control.pesquisarLivroPorAutor(txtAutor.getText());
if (encontrados!= null){
for (Livro dados : encontrados){
Object[] objetoTombo = new Object[1];
Object[] objetoTitulo = new Object[2];
Object[] objetoTituloInternacional = new Object[3];
Object[] objetoEdicao = new Object[4];
Object[] objetoAutor = new Object[5];
Object[] objetoEditora = new Object[6];
objetoTombo[0] = dados.getTombo();
objetoTitulo[0] = dados.getTitulo();
objetoTituloInternacional[0] = dados.getTituloInternacional();
objetoEdicao[0] = dados.getEdicao();
objetoAutor[0]= dados.getAutor();
objetoEditora[0]= dados.getEditora();
//modelo.setNumRows(0);
modelo.addRow(objetoTombo);
modelo.addRow(objetoTitulo);
modelo.addRow(objetoTituloInternacional);
modelo.addRow(objetoEdicao);
modelo.addRow(objetoAutor);
modelo.addRow(objetoEditora);
}
this.setSize(700,500);
tblLivros.setModel(modelo);
painelJPanel.add(tblLivros);
painelJPanel.setVisible(true);
painelJPanel.repaint();
painelPrincipal.add(painelJPanel, BorderLayout.SOUTH);
painelPrincipal.repaint();
}
}
else {
encontrados = control.pesquisarLivroPorNome(txtTitulo.getText());
if (encontrados!= null){
}
}
}
}
public static void main(String[] args) {
new LivroView();
}
}
Thank you!
Because you didn't even added JScrollPane on your painelPrincipal. You can do it like this:
painelPrincipal.add(scrollPane, BorderLayout.SOUTH);
Also:
Do not call setVisible for JFrame before all components are added.
Call pack instead of setSize for JFrame
Avoid using null layout and absolute positioning.
Regards and good luck!
EDIT:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LivroView extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel lblIdLivro, lblLombada, lblTitulo, lblTituloInternacional, lblEdicao, lblEditora, lblAutor ;
private JTextField txtIdLivro, txtTombo, txtTitulo, txtTituloInternacional, txtEdicao, txtEditora, txtAutor;
private JButton btnAdicionar, btnPesquisar, btnExcluir;
private JPanel painelPrincipal, painelGeral, painelBotoes, painelJPanel;
private JTable tblLivros;
DefaultTableModel modelo;
public LivroView() {
super("Manutenção de Livros");
lblIdLivro = new JLabel("Código do livro:");
lblLombada = new JLabel("Tombo:");
lblTitulo = new JLabel("Título:");
lblTituloInternacional = new JLabel("Título Internacional:");
lblEdicao = new JLabel("Edição:");
lblEditora = new JLabel("Editora:");
lblAutor = new JLabel("Autor:");
txtIdLivro = new JTextField(20);
txtTombo= new JTextField("Tombo");
txtTitulo = new JTextField(20);
txtTituloInternacional= new JTextField(20);
txtEdicao = new JTextField(20);
txtEditora= new JTextField(20);
txtAutor= new JTextField("Autor");
txtIdLivro.setText("");
txtTombo.setText("");
txtTitulo.setText("");
txtTituloInternacional.setText("");
txtEdicao.setText("");
txtEditora.setText("");
txtAutor.setText("");
btnAdicionar = new JButton("Adicionar");
btnExcluir = new JButton("Excluir");
btnPesquisar = new JButton("Pesquisar");
btnAdicionar.addActionListener(this);
btnPesquisar.addActionListener(this);
btnExcluir.addActionListener(this);
painelPrincipal = new JPanel();
painelGeral = new JPanel();
painelBotoes = new JPanel();
painelJPanel = new JPanel();
painelPrincipal.setLayout(new BorderLayout());
painelGeral.setLayout(new GridLayout(7,2));
painelBotoes.setLayout(new GridLayout(2,1));
painelGeral.add(lblIdLivro);
painelGeral.add(txtIdLivro);
painelGeral.add(lblLombada);
painelGeral.add(txtTombo);
painelGeral.add(lblTitulo);
painelGeral.add(txtTitulo);
painelGeral.add(lblTituloInternacional);
painelGeral.add(txtTituloInternacional);
painelGeral.add(lblEdicao);
painelGeral.add(txtEdicao);
painelGeral.add(lblEditora);
painelGeral.add(txtEditora);
painelGeral.add(lblAutor);
painelGeral.add(txtAutor);
painelBotoes.add(btnAdicionar);
painelBotoes.add(btnPesquisar);
painelBotoes.add(btnExcluir);
tblLivros = new JTable();
tblLivros.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Tombo", "T\u00EDtulo", "T\u00EDtulo Internacional", "Edi\u00E7\u00E3o", "Autor", "Editora"
}
));
JScrollPane scrollPane = new JScrollPane(tblLivros);
painelPrincipal.add(painelGeral, BorderLayout.NORTH);
painelPrincipal.add(painelBotoes, BorderLayout.CENTER);
painelPrincipal.add(scrollPane, BorderLayout.SOUTH);
this.setContentPane(painelPrincipal);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if ("Adicionar".equalsIgnoreCase(cmd)){
boolean adicionado = false;
if (adicionado == true){
txtIdLivro.setText("");
txtTombo.setText("");
txtTitulo.setText("");
txtTituloInternacional.setText("");
txtEdicao.setText("");
txtEditora.setText("");
txtAutor.setText("");
txtIdLivro.requestFocus();
}
}
else if("Excluir".equalsIgnoreCase(cmd)){
txtTombo.setText("");
}
else if("Pesquisar".equalsIgnoreCase(cmd)){
if (!txtTombo.getText().equals("")){
}
else if (!txtAutor.getText().equals("")){
} }
}
public static void main(String[] args) {
new LivroView();
}
}
Ok, here is your code. Altough I had to remove some pieces of code to make it functional.
First of all, stop using null layouts. Swing was designed to be used with layout managers.
You add the table to the scroll pane which is a good thing.
scrollPane.setViewportView(tblLivros);
Later on it looks like you update the model (which is a good thing), but then you add the table to another panel (which is a bad thing). This removes the table from the scrollpane. The table will no longer have a header unless the table is displayed in a scrollpane. All you need to do is invoke the setModel() method and the table will automatically repaint itself.
tblLivros.setModel(modelo);
//painelJPanel.add(tblLivros);
//painelJPanel.setVisible(true);
//painelJPanel.repaint();
//painelPrincipal.add(painelJPanel, BorderLayout.SOUTH);
If you ever do need to add a component to a visible GUI then the code should be:
panel.add(..)
panel.revalidate();
panel.repaint();
just got help from a friend, here is the final code:
public class LivroView extends JFrame implements ActionListener {
private JTable tblLivros;
DefaultTableModel modeloTabela;
private List<Livro> encontrados;
public LivroView() {
super("Manutenção de Livros");
encontrados = new ArrayList<Livro>();
modeloTabela = new DefaultTableModel(
new String[] {
"Tombo", "Título", "Título Internacional", "Edição", "Autor", "Editora"
}, 0);
tblLivros = new JTable(modeloTabela);
tblLivros.getColumnModel().getColumn(0).setPreferredWidth(54);
tblLivros.getColumnModel().getColumn(1).setPreferredWidth(104);
tblLivros.getColumnModel().getColumn(2).setPreferredWidth(136);
tblLivros.getColumnModel().getColumn(4).setPreferredWidth(102);
painelTabela = new JScrollPane(tblLivros);
painelTabela.setVisible(false);
painelPrincipal.add(painelGeral, BorderLayout.NORTH);
painelPrincipal.add(painelBotoes, BorderLayout.CENTER);
painelPrincipal.add(painelTabela, BorderLayout.SOUTH);
//this.setSize(500,300);
this.setContentPane(painelPrincipal);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
LivroControl control = new LivroControl();
if ("Adicionar".equalsIgnoreCase(cmd)){
}
else if("Excluir".equalsIgnoreCase(cmd)){
}
else if("Pesquisar".equalsIgnoreCase(cmd)){
if (!txtTombo.getText().equals("")){
Livro l = control.pesquisarLivroPorTombo(txtTombo.getText());
if (l!=null){
txtIdLivro.setText(String.valueOf(l.getIdLivro()));
txtTombo.setText(l.getTombo());
txtTitulo.setText(l.getTitulo());
txtTituloInternacional.setText(l.getTituloInternacional());
txtEdicao.setText(l.getEdicao());
txtEditora.setText(l.getEditora());
txtAutor.setText(l.getAutor());
}
}
else if (!txtAutor.getText().equals("")){
encontrados = control.pesquisarLivroPorAutor(txtAutor.getText());
if (encontrados!= null){
for (Livro dados : encontrados){
Object[] row = new Object[6];
row[0] = dados.getTombo();
row[1] = dados.getTitulo();
row[2] = dados.getTituloInternacional();
row[3] = dados.getEdicao();
row[4]= dados.getAutor();
row[5]= dados.getEditora();
modeloTabela.addRow(row);
}
painelTabela.setVisible(true);
painelPrincipal.repaint();
this.pack();
}
}
else {
//the same
}
}
}
public static void main(String[] args) {
new LivroView();
}
}
Thank you so much for the help!