I'm quite new to Java Programming and I found this code on the internet. It works fine there is no problem. I downloaded the png's of every fruit and I want to see them when I click on them instead of seeing their names. For example, if I click only apple, I want to see the png of apple. But if I use shift and multiple select grape and banana, I want to see their pngs at the right. (If it is possible of course)
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Ğ extends JFrame
{
//Sample 02: Create a Label
JLabel label = new JLabel();
public Ğ(String title) throws HeadlessException
{
super(title);
//Sample 01: Set Size and Position
setBounds(100, 100, 200, 200);
Container ControlHost = getContentPane();
ControlHost.setLayout(new GridLayout(1,1));
//Sample 03: Create List of Fruit Items
String[] Fruits = new String[10];
Fruits[0] = "Apple";
Fruits[1] = "Mango";
Fruits[2] = "Banana";
Fruits[3] = "Grapes";
Fruits[4] = "Cherry";
Fruits[5] = "Lemon";
Fruits[6] = "Orange";
Fruits[7] = "Strawberry";
Fruits[8] = "Watermelon";
Fruits[9] = "Ananas";
//Sample 04: Create JList to Show Fruit Name
JList ListFruits = new JList(Fruits);
ListFruits.setVisibleRowCount(10);
//Sample 05: Hand-Over the JList to ScrollPane & Display
JScrollPane jcp = new JScrollPane(ListFruits);
ControlHost.add(jcp);
ControlHost.add(label);
ListFruits.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
//Sample 06: Handle the JList Event
ListFruits.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
String strFruits = "";
List<String> SelectedFruits = ListFruits.getSelectedValuesList();
for(String Fruit: SelectedFruits)
strFruits = strFruits + Fruit + ",";
strFruits = strFruits.substring(0, strFruits.length()-1);
label.setText(strFruits);
}
});
}
}
And this is the main class of course
import javax.swing.JFrame;
public class Fruits {
public static void main(String[] args) {
// TODO Auto-generated method stub
Ğ frame = new Ğ ("Fruits");
frame.setVisible(true);
}
}
Related
I want to change my second combobox elements by changing the first one's value, but its doesn't work. ActionListener for Combobox works only for the first column after the declaration. If I run debug and press "Run Into" - it works well.
Here is my code:
import java.awt.Container;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class face extends JFrame {
public face() {
super("Test frame");
setDefaultCloseOperation(EXIT_ON_CLOSE);
// READ FILE //
File f=new File("");
String tname = f.getAbsolutePath()+File.separator+"1.txt";
Scanner in = null;
int i=0;
List<String> list = new ArrayList<String>();
try {
in = new Scanner(new File(tname));
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
while (in.hasNextLine())
list.add(in.nextLine());
in.close();
String[] teacherlist = list.toArray(new String[0]);
JComboBox tcombo = new JComboBox(teacherlist);
tcombo.setSelectedIndex(1);
String item = (String)tcombo.getSelectedItem();
JPanel panel = new JPanel();
panel.add(tcombo);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
File r = new File("");
//String item = (String)tcombo.getSelectedItem();
String sname = r.getAbsolutePath()+File.separator+"aaaa.txt";
List<String> slist = new ArrayList<String>();
Scanner k;
k=null;
try {
k = new Scanner(new File(sname));
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
while (k.hasNextLine())
slist.add(k.nextLine());
k.close();
String[] subjectlist = slist.toArray(new String[0]);
JComboBox scombo = new JComboBox(subjectlist);
scombo.setVisible(true);
panel.add(scombo);
}
};
tcombo.addActionListener(actionListener);
panel.add(but);
label.setVisible(false);
setContentPane(panel);
}
public static void main(String[] args)
{JFrame myWindow = new face();
myWindow.setVisible(true);
myWindow.setSize(500,500);
}}
I would guess the problem is with this code:
JComboBox scombo = new JComboBox(subjectlist);
//scombo.setVisible(true); // not needed components are visible by default
panel.add(scombo);
The default size of the combo box is (0, 0) so there is nothing to paint.
Whenever you add components to a visible GUI the basic logic is:
panel.add(...);
panel.revalidate();
panel.repaint();
However probably a better solution is to add both combo boxes to the GUI when you create the frame. Then when you select an item in the first combo box you just change the "data" in the second combo box. You do this by invoked the setModel(...) method on the second combo box.
Check out Binding comboboxes in swing for an example of this approach.
I'm recently working on a project- Bus Ticket Machine. This is a program which helps the user to print their tickets.
I have one screen (destPanel) where I display a list of cities to be chosen (JList departures).
Once the user choses a city the addListSelectionListener of the first JList will save and return a timetable (JList timetable) for the user to choose again and this time save the chosen departure for printing on the ticket later on.
I cannot get the addListSelectionListener to stop when the timetable is displayed. This in order to be able to select a departure to be saved for printing the ticket.
I've added my three classes showing what I've been working on.
Class one:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.Arrays;
import java.util.Vector;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class TicketGUI extends JFrame
{
public static void main(String[] args)
{
new TicketGUI();
}
private JPanel destPanel = new JPanel();
private JPanel departPanel = new JPanel();
private JPanel payPanel = new JPanel();
private JButton[] buttons;
// Display size
private final int WIDTH = 310;
private final int HEIGHT = 150;
JList departJList;
JList defltList;
Vector<Enum> listContent = new Vector<Enum>();
//Following line used for adding info to display JList.
//Vector<Object> listContent = new Vector<Object>();
JList timeTable; //Not being used.
private DefaultListModel listModel; //Not being used.
Vector<String> newListContent = new Vector<String>(); //Not being used.
JTextArea textArea = new JTextArea();
JTextField payField = new JTextField(15);
public TicketGUI()
{
this.setTitle("Bus Ticket Machine");
setLayout(new BorderLayout());
JPanel agePanel = new JPanel();
JRadioButton adultButton = new JRadioButton("Adult");
adultButton.setSelected(true);
JRadioButton studentButton = new JRadioButton("Student");
JRadioButton childButton = new JRadioButton("Children");
//Group the radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(adultButton);
group.add(studentButton);
group.add(childButton);
JPanel bPanel = new JPanel();
bPanel.setMaximumSize(new Dimension(100, 100));
bPanel.setLayout(new GridLayout(4, 3));
buttons= new JButton[12];
for (int i=0; i<12; i++)
{
buttons[i]=new JButton();
//buttons[i].addActionListener(this);
}
for (int i=1; i<10; i++)
{
buttons[i-1].setText(""+i);
bPanel.add(buttons[i-1]);
}
buttons[9].setText("X");
bPanel.add(buttons[9]);
buttons[10].setText("0");
bPanel.add(buttons[10]);
buttons[11].setText("OK");
bPanel.add(buttons[11]);
payField.setText("Card Number");
payField.setEditable(false);
payPanel.setLayout(new BorderLayout());
payPanel.add(payField, BorderLayout.NORTH);
// Display
// listContent.add("London");
// listContent.add("Bristol");
// listContent.add("Sheffield");
// listContent.add("Birmingham");
// listContent.add("...");
// listContent.add("Here under list to be displayed after choosing a city");
// listContent.add("1. London -> Bristol Depart: 11:45 Arrives: 13:15");
// listContent.add("2. London -> Bristol Depart: 12:30 Arrives: 15:00");
// listContent.add("3. London -> Bristol Depart: 13:45 Arrives: 16:15");
// listContent.add("4. London -> Bristol Depart: 14:30 Arrives: 17:00");
// listContent.add("...");
// listContent.add("Your Journey");
// listContent.add("Ticket: Adult");
// listContent.add("From: London ");
// listContent.add("Going to: Bristol");
// listContent.add("Leaving: 11:45");
// listContent.add("Fare: £ 18.00");
listContent = new Vector<Enum>(Arrays.asList(EnumCity.values()));
System.out.print(listContent + "one");
// defltList = new JList(listContent);
//
// System.out.print(defltList);
departJList = new JList(listContent);
// departJList.add(listContent);
System.out.print("\n\n");
System.out.print(departJList + "two");
timeTable = new JList();
departJList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e)
{
if (!e.getValueIsAdjusting())
{
TimeTable selected = new TimeTable();
selected.setTimeTable();
newListContent.addAll(selected.getTimeTable());
// timeTable.setListData(newListContent.toArray());
// departJList.setListData(newListContent);
}
System.out.println(newListContent);
// timeTable.setListData(newListContent.toArray());
departJList.setListData(newListContent);
// departJList.setListData(newListContent);
}
});
JScrollPane m_clScrollpane = new JScrollPane(departJList);
m_clScrollpane.setPreferredSize(new Dimension(WIDTH, HEIGHT));
JPanel farePanel = new JPanel(new GridLayout(4, 1));
farePanel.add(adultButton);
farePanel.add(studentButton);
farePanel.add(childButton);
JTextField tf = new JTextField("£ 0.00");
tf.setEditable(false);
farePanel.add(tf);
destPanel.add(farePanel);
destPanel.add(m_clScrollpane);
payPanel.add(bPanel);
add(destPanel);
add(payPanel, BorderLayout.EAST);
setVisible(true);
pack();
addWindowListener(new java.awt.event.WindowAdapter()
{
public void windowClosing(java.awt.event.WindowEvent evt) {
dispose();
System.exit(0);
}
});
}
}
Class two:
public enum EnumCity {
London,
Bristol,
Sheffield,
Birmingham
}
Class three:
import java.util.Vector;
public class TimeTable {
private String timeTable;
public TimeTable()
{
}
public String setTimeTable()
{
return this.timeTable;
}
public Vector<String> getTimeTable()
{
Vector<String> timeList = new Vector<String>();
timeList.addElement("1. London -> Bristol Depart: 11:45 Arrives: 13:15");
timeList.addElement("2. London -> Bristol Depart: 12:30 Arrives: 15:00");
timeList.addElement("3. London -> Bristol Depart: 13:45 Arrives: 16:15");
timeList.addElement("4. London -> Bristol Depart: 14:30 Arrives: 17:00");
return timeList;
}
}
Instead of replacing the data in the list (which is a good idea generally), you could establish two different lists, one that manages list of cities and one that managers the list of time tables.
Then using a CardLayout, you could switch between them.
This means that you don't need to worry about switching selection listeners each time you switch the data.
One way to stop a listener from working is to remove it. If you are set on swapping the data in your list, you could do:
departJList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
// ******* added **********
((JList)e.getSource()).removeListSelectionListener(this);
TimeTable selected = new TimeTable();
selected.setTimeTable();
newListContent.addAll(selected.getTimeTable());
}
System.out.println(newListContent);
departJList.setListData(newListContent);
}
});
trying to solve a problem and i cant get why it wont work. I'm sorry if I confuse you with my norwegian comments and variables.
First, here is my form.java file.
import java.awt.FlowLayout;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
public class Form implements ActionListener {
String[] ansatt_type = {"Sjef","Mellomleder","Assistent"};
String totlønn;
// KOMPONENTER FOR GUI START
JList ansatte;
DefaultListModel model;
JLabel label1 = new JLabel ();
JComboBox ansatt_id = new JComboBox (ansatt_type);
JButton add_me = new JButton ();
JLabel lønn = new JLabel ();
// KOMPONENTER FOR GUI SLUTT
public Form () {
// LAGER RAMME START
JFrame ramme = new JFrame ();
ramme.setBounds(0,0,275,400);
ramme.setTitle("Ansatt kontroll");
ramme.setLayout(new FlowLayout ());
ramme.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// LEGGER TIL TEXT LABEL1
label1.setText("Liste over ansatte: ");
ramme.add(label1);
// LEGGER TIL DEFAULTLISTMODEL
model = new DefaultListModel();
ansatte = new JList(model);
ansatte.setBounds(0, 0, 200, 200);
model.addElement("KU");
ramme.add(ansatte);
// LEGGER TIL DROPDWON LIST;
ramme.add(ansatt_id);
// LEGGER TIL ANSATT KNAPP
add_me.setText("Legg til ny ansatt");
ramme.add(add_me);
add_me.addActionListener(this);
// LEGGER TIL SAMLEDE LØNNSKOSTNADER
totlønn = "Totale lønnskostnader er : eksempeltall";
lønn.setText(totlønn);
ramme.add(lønn);
ramme.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Du har valgt:
"+ansatt_id.getSelectedItem()+"!" +
" Du blir nå videreført og kan legge til en ny ansatt");
if(ansatt_id.getSelectedItem() == "Sjef"){
System.out.println("Valgt Sjef");
Sjef sj = new Sjef ();
model.addElement(sj);
}
if(ansatt_id.getSelectedItem() == "Mellomleder"){
System.out.println("Valgt Mellomleder");
}
if(ansatt_id.getSelectedItem() == "Assistent"){
System.out.println("Valgt Assistent");
}
}
}
I also have a class file called Ansatt.java who several class fiels extends from. I'l show you one.
First my Ansatt.java file ;
import javax.swing.JOptionPane;
public class Ansatt extends Form {
public String Navn;
public int Lønn;
public String Type;
public Ansatt () {
Navn = JOptionPane.showInputDialog(null, "Skriv inn navn på ny ansatt: ");
System.out.println("Ansatt lag til i liste");
}
public String toString(){
return Navn + " " + Type;
}
}
And the extended class Sjef.java
public class Sjef extends Ansatt {
public Sjef () {
super();
this.Lønn = 40000;
this.Type = "Sjef";
}
}
Everything works, except the ModelList wont update, I have a working example, who is almost identical but it just doesent work in this one!
Your problem is the String comparison in your ActionListener:
ansatt_id.getSelectedItem() == "Sjef"
will most likely not return true. You should use
"Sjef".equals( ansatt_id.getSelectedItem() )
Same for the other comparisons.
I have to convert styled text to wrapped simple text (for SVG word wrapping). I cannot beleive that the word wrapping information (how many lines are there, where are the line breaks) cannot be extracted from the JTextArea. So I created a small frame program:
package bla;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTextArea;
public class Example1 extends WindowAdapter {
private static String content = "01234567890123456789\n" + "0123456 0123456 01234567 01234567";
JTextArea text;
public Example1() {
Frame f = new Frame("TextArea Example");
f.setLayout(new BorderLayout());
Font font = new Font("Serif", Font.ITALIC, 20);
text = new JTextArea();
text.setFont(font);
text.setForeground(Color.blue);
text.setLineWrap(true);
text.setWrapStyleWord(true);
f.add(text, BorderLayout.CENTER);
text.setText(content);
// Listen for the user to click the frame's close box
f.addWindowListener(this);
f.setSize(100, 511);
f.show();
}
public static List<String> getLines( JTextArea text ) {
//WHAT SHOULD I WRITE HERE
return new ArrayList<String>();
}
public void windowClosing(WindowEvent evt) {
List<String> lines = getLines(text);
System.out.println( "Number of lines:" + lines.size());
for (String line : lines) {
System.out.println( line );
}
System.exit(0);
}
public static void main(String[] args) {
Example1 instance = new Example1();
}
}
If you run it you will see this:
And what I expect as output:
Number of lines:6
0123456789
0123456789
0123456
0123456
01234567
01234567
What should I write in place of the comment?
Complete answer:
So, then the complete solution based on the accepted answer without displaying the frame actually (note, that you should remove the actual newline characters from the result):
package bla;
import java.awt.Color;
import java.awt.Font;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;
import javax.swing.text.Utilities;
public class Example1 {
private static String content = "01234567890123456789\n" + "0123456 0123456 01234567 01234567";
public static List<String> getLines( String textContent, int width, Font font ) throws BadLocationException {
JTextArea text;
text = new JTextArea();
text.setFont(font);
text.setForeground(Color.blue);
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setText(content);
text.setSize(width, 1);
int lastIndex = 0;
int index = Utilities.getRowEnd(text, 0);
List<String> result = new ArrayList<String>();
do {
result.add( textContent.substring( lastIndex, Math.min( index+1, textContent.length() ) ) );
lastIndex = index + 1;
}
while ( lastIndex < textContent.length() && ( index = Utilities.getRowEnd(text, lastIndex) ) > 0 );
return result;
}
public static void main(String[] args) throws BadLocationException {
Font font = new Font("Serif", Font.ITALIC, 20);
Example1 instance = new Example1();
for (String line : getLines(content,110,font)) {
System.out.println( line.replaceAll( "\n", "") );
}
}
}
Open question in me (not that important), why is that a frame with 100px width containing a jtextarea wraps the text later than a jtextarea without frame with the same width. Ideas for this?
JTextArea does not support styled text, but it does support line-oriented access to its model, PlainDocument, as shown below. For reference,
Don't mix AWT (Frame) and Swing (JTextArea) components unnecessarily.
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
As noted here, the getLineCount() method counts line.separator delimited lines, not wrapped lines.
BasicTextUI handles Look & Feel dependent rendering; the methods viewToModel() and viewToModel() translate between the two coordinate systems.
Console:
01234567890123456789
0123456 0123456
01234567 01234567
Code:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class Example2 {
private static final Character SEP = Character.LINE_SEPARATOR;
private static String content = ""
+ "01234567890123456789" + SEP
+ "0123456 0123456" + SEP
+ "01234567 01234567";
private JTextArea text;
public Example2() {
JFrame f = new JFrame("TextArea Example");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Font font = new Font("Serif", Font.ITALIC, 20);
text = new JTextArea(4, 8);
text.setFont(font);
text.setForeground(Color.blue);
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setText(content);
f.add(new JScrollPane(text));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
for (String s : getLines(text)) {
System.out.println(s);
}
}
private List<String> getLines(JTextArea text) {
PlainDocument doc = (PlainDocument) text.getDocument();
List<String> list = new ArrayList<String>();
for (int i = 0; i < text.getLineCount(); i++) {
try {
int start = text.getLineStartOffset(i);
int length = text.getLineEndOffset(i) - start;
list.add(doc.getText(start, length));
} catch (BadLocationException ex) {
ex.printStackTrace(System.err);
}
}
return list;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Example2 instance = new Example2();
}
});
}
}
Use Utilities.getRowEnd()
Pass 0 as start offset and then previousline's end offset +1
JTextArea does have a : getLines() method, is that not working for you?
I've got some very old code which uses a Box to list some information. I create it like so:
Box patterns = Box.createVerticalBox();
Very (very) often, new items are added and old items are removed eg:
label = new JLabel("xyz");
patterns.add(label);
and later
patterns.remove(label);
whenever something is added ore removed I have to have it repaint, so I call:
patterns.revalidate();
patterns.repaint();
Problem is, since this happens very often it chokes up the UI. I think I need a better implementation in order to make it more efficient.
I know I could maintain a list of the active items in the background and then intermittently update the actual UI (batch update) but...
Can someone suggest a more efficient alternative approach?
Why don't you just use a JList and implement a cell renderer?
Or more flexibility with a JTable and implement a table cell renderer (returns a Component instead)?
Based on this example, the following code loafs doing 16 labels at 10 Hz.
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
/** #see https://stackoverflow.com/questions/6605554 */
public class ImageLabelPanel extends Box implements ActionListener {
private static final int N = 16;
private final List<JLabel> list = new ArrayList<JLabel>();
private final Timer timer = new Timer(100, this);
ImageLabelPanel() {
super(BoxLayout.Y_AXIS);
BufferedImage bi = null;
try {
bi = ImageIO.read(new File("image.jpg"));
} catch (IOException e) {
e.printStackTrace(System.err);
}
for (int r = 0; r < N; r++) {
int w = bi.getWidth();
int h = bi.getHeight() / N;
BufferedImage b = bi.getSubimage(0, r * h, w, h);
list.add(new JLabel(new ImageIcon(b)));
}
createPane();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setVisible(true);
timer.start();
}
private void createPane() {
this.removeAll();
for (JLabel label : list) {
add(label);
}
this.revalidate();
}
#Override
public void actionPerformed(ActionEvent e) {
Collections.shuffle(list);
createPane();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ImageLabelPanel();
}
});
}
}