I'm trying to insert an image into resource folder and use it to display in frame. But I'm getting this error :
Type Mismatch: can't convert from java.awt.Image to project.image
Here is a example using an image icon from the default java resources.
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setIcon(new ImageIcon(test.class.getResource("/com/sun/java/swing/plaf/windows/icons/Question.gif")));
lblNewLabel.setBounds(112, 60, 151, 126);
frmTitle.getContentPane().add(lblNewLabel);
the code above will add a question mark image on your application, like this image. You can of course change it to whatever you would like.
Hope this simple sample helps you...
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
import java.util.Arrays;
import java.awt.EventQueue;
import javax.swing.JFrame;
public class FloorPlaner extends JFrame {
protected BufferedImage wall;
public FloorPlaner(){
super("FloorPlaner");
try {
wall = ImageIO.read(new File ("wall.png")); //Load a wall
} catch(IOException bug) { //Create a wall image
wall=new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB);
Graphics2D wg=wall.createGraphics();
wg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
wg.setColor(Color.BLACK);
wg.fillRect(0,0,20,20);
System.out.println(bug);
}
requestFocus();
setContentPane(new DrawingPane());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setResizable(true);
setVisible(true);
while (true) {
repaint();
try {
Thread.sleep(40); //25 FPS
} catch(InterruptedException bug) {
Thread.currentThread().interrupt();
System.out.println(bug);
}
}
}
class DrawingPane extends JPanel { //Where you actually draw on
public void paintComponent(Graphics g) { //Drawing method
g.drawImage(wall,0,0,null);
}
}
public static void main(String args[]) {
new FloorPlaner(); //Start it
}
}
Related
When I started my project about a Dictionary from Chinese to English, I got some problems.First,
I used the addCaretListener method to realize that when I changed the cursor in wordLine,changed the context in JList and show the result.But here a problem comes,If I changed the cursor, the JList were clear,and not show anything.
Another problem is I want to invoke the http video API to realize the video play. As I add the video button and add the audio method to realize ,I failed.
I'll appreciate if you can solve them.
This is part of my code:
import java.applet.*;
import java.awt.*;
import java.net.*;
import java.lang.Thread;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import org.omg.CORBA.portable.InputStream;
import org.omg.CORBA.portable.OutputStream;
import javax.swing.JScrollPane;
import javax.swing.JList;
public class DictionaryWindow extends JFrame{
public ArrayList<String> wordList = new ArrayList<>();
public ArrayList<String> meaningList = new ArrayList<>();
private JButton searchBn=new JButton("搜索");
private JTextField wordLine=new JTextField();
private JButton addToNote=new JButton("添加入生词本");
private JButton videoBn=new JButton();
private JScrollPane scroll=new JScrollPane();
private String waitForSearch;
private String local="151310421";
private JList list;
private int index=0;
private int wordLocation;//查找想要找单词的序号
private JTextField showMean=new JTextField();
private String []str;
private String []str1;
//private String []str2;
private TrieTree trie=new TrieTree();
private Vector <String>v=new Vector <String>();
private DefaultListModel dlm = new DefaultListModel();
private boolean wait=false;
public DictionaryWindow()
{
toTrieTree();
}
public void dictionaryInit()
{
this.setResizable(false);
this.setLayout(null);
this.setSize(600,500);
str=wordList.toArray(new String[wordList.size()]);
str1=meaningList.toArray(new String[meaningList.size()]);
for(int i=0;i<str.length;i++)
{
dlm.addElement(str[i]);
}
list=new JList(dlm);//v To str
scroll.setViewportView(list);
scroll.setPreferredSize(new Dimension(200,200));
searchBn.setBounds(200, 100, 60, 25);
wordLine.setBounds(60, 100, 100, 25);
addToNote.setBounds(60, 150, 200, 25);
scroll.setBounds(300, 200, 100, 200);
showMean.setBounds(300, 100, 200, 25);
videoBn.setBounds(450,100,100,25);
wordLine.addCaretListener(new CaretListener(){
public void caretUpdate(CaretEvent e){
trie.searchNextWords(wordLine.getText());
String []str2=new String[]{};
str2=null;
str2=trie.wordL.toArray(new String[trie.wordL.size()]);
//str=str2;
//v.clear();
//for(int i=0;i<str2.length;i++)
//v.add(str2[i]);`
((DefaultListModel)list.getModel()).removeAllElements();
for(int i=0;i<str2.length;i++)
{
dlm.addElement(str2[i]);
}
list.setModel(dlm);
scroll.setViewportView(list);
//JScrollPane scroll=new JScrollPane(list);
//scroll.setPreferredSize(new Dimension(200,200));
//scroll.setBounds(300, 200, 100, 200);
//add(scroll);
}
});
addToNote.addActionListener(e->{
String writeFilePath = local + ".txt";
try {
String note = wordLine.getText() + " " + showMean.getText();
Files.write(Paths.get(writeFilePath), Arrays.asList(note), StandardOpenOption.APPEND);
} catch (Exception e1) {
System.err.println("File Writing error\n" + e);
}
});
videoBn.addActionListener(e->{
class sound extends Applet{
AudioClip loopClip;
public void init()
{
String word=wordLine.getText();
String httpVideo="http://dict.youdao.com/dictvoice?type=1&audio="+word;
try {
loopClip=getAudioClip(new URL(httpVideo));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public sound(){
init();
loopClip.play();
}
}
sound s=new sound();
});
searchBn.addActionListener(e->{
wordLocation=0;
waitForSearch=wordLine.getText();
while(!waitForSearch.equals(str[wordLocation]))
{
wordLocation++;
}
showMean.setText(str1[wordLocation]);
});
list.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(e.getClickCount()==2)
twoClick(list.getSelectedValue());
}
private void twoClick(Object selectedValue) {
// TODO Auto-generated method stub
wordLine.setText((String) selectedValue);
}
});
Border border = BorderFactory.createMatteBorder(1, 1, 2, 2, Color.RED);
showMean.setBorder(border);
showMean.setEditable(false);
this.add(searchBn);
this.add(wordLine);
this.add(addToNote);
this.add(scroll);
this.add(showMean);
this.add(videoBn);
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
/* class doubleClick extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if(e.getClickCount() ==2) {
wordLine.setText((JList)e.getSource());
}
}
}*/
public void toTrieTree()
{
int i=0;
while(i<wordList.size())
{
trie.insert(str[i],str1[i]);
dlm.addElement(str[i]);
i++;
}
}
}
I am developing one java swing application for task remainder.Please find the below code for the same.But the problem is i am not able to maintain session here since i am using ScheduledExecutorService class which will help to trigger this Swing app one hour once.When triggering new one all changes has been made in previous session of app is gone.
Kindly help me on this and let me know how can i use session on my Swing application.
Example : If you run the below app yon can see two buttons when we click on button it will change color to "green" and status change to "Done" but when the application trigger after one minute all changes were erased launching as new one.
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.awt.Toolkit;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.Timer;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class Taskschdeuler {
private final static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public static void main(String[] args) {
final Runnable beeper = new Runnable()
{
public void run()
{
// do anything here that you want to execute in a scheduler.
Task r=new Task();
}
};
final ScheduledFuture<?> beeper1 = scheduler.scheduleAtFixedRate(beeper, 0, 1, TimeUnit.MINUTES);
}
}
class Task extends JFrame implements ActionListener
{
JButton b1,b2,b3;
JLabel l1,l2;
public Task()
{
l1=new JLabel("Pending");
l2=new JLabel("Pending");
b1=new JButton("AVM DART");
b2=new JButton("HANDSHAKE");
b3=new JButton("Remind me later!!");
add(b1);
add(l1);
add(b2);
add(l2);
add(b3);
b1.setBackground(Color.PINK);
b2.setBackground(Color.PINK);
b3.setBackground(Color.CYAN);
b1.setPreferredSize(new Dimension(200, 50));
b2.setPreferredSize(new Dimension(200, 50));
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice defaultScreen = ge.getDefaultScreenDevice();
Rectangle rect = defaultScreen.getDefaultConfiguration().getBounds();
int x = (int) rect.getMaxX() -300;
int y = 500;
setLocation(x, y);
setLayout(new FlowLayout());
setVisible(true);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(e.getSource()==b1)
{
if (((Component)source).getBackground().equals(Color.GREEN))
{
((Component)source).setBackground(Color.PINK);
l1.setText("Pending");
}
else
{
((Component)source).setBackground(Color.GREEN);
l1.setText(" Done");
}
}
if(e.getSource()==b2)
{
if (((Component)source).getBackground().equals(Color.GREEN))
{
((Component)source).setBackground(Color.PINK);
l2.setText("Pending");
} else
{
((Component)source).setBackground(Color.GREEN);
l2.setText(" Done");
}
}
if(e.getSource()==b3)
{
setVisible(false);
}
}
}
I have a problem when i add a jpanel to existing jpanel!
i want jlist at center loction and jbuttom in south location!
i can see the jlist, but the jbuttom won't show on!
I'm using Eclipse 3.0 version.
this is my code:
package classes;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.LinkedList;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class JPanelDecorator extends JPanel implements ActionListener
{
private static final long serialVersionUID = 1L;
private JList<String> list = null;
private JButton Change=null;
public JPanelDecorator()
{
super();
setLayout(new BorderLayout());
setSize(450 ,400);
String animals_list[] = new String[AquaPanel.swims.size()];
LinkedList<Swimmable> ir = new LinkedList<Swimmable>(AquaPanel.swims);
for(int i=0;i<ir.size();i++)
{
animals_list[i]=(i+1+". "+ir.get(i).toString());
}
list = new JList<String>(animals_list );
list.setFont(new Font("Tahoma",Font.BOLD,15));
list.setSize(450, 300);
add(list,BorderLayout.CENTER);
Change = new JButton("Change Color");
Change.addActionListener(this);
add(Change,BorderLayout.CENTER);
repaint();
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
please help!
You have a subtle bug. In the constructor of JPanelDecorator you have :
public JPanelDecorator()
{
//....
add(list,BorderLayout.CENTER);
//...
add(Change,BorderLayout.CENTER); // center again...
//...
}
But what you need is this:
public JPanelDecorator()
{
//....
add(list,BorderLayout.CENTER);
//...
add(Change,BorderLayout.SOUTH); // south
//...
}
I have this code below. How do I make this JComboBOx run in an Applet? I'm trying to create an applet that allows the user to select a font and type in that font in a JTextArea. I have been searching for answers and made little progress. The error java.lang.reflect.InvocationTargetException keeps popping up. If you need more specifics please just comment.
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Font_Chooser extends JApplet {
JLabel jlbPicture;
public Font_Chooser(){
// Create the combo box, and set first item as Default
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] names = ge.getAvailableFontFamilyNames();
final JComboBox comboTypesList = new JComboBox(names);
comboTypesList.setSelectedIndex(0);
comboTypesList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox jcmbType = (JComboBox) e.getSource();
String cmbType = (String) jcmbType.getSelectedItem();
jlbPicture.setIcon(new ImageIcon(""
+ cmbType.trim().toLowerCase() + ".jpg"));
System.out.println(comboTypesList.getSelectedItem());
//Font myFont = new Font((String)comboTypesList.getSelectedItem(), Font.BOLD, 12);
}
});
// Set up the picture
jlbPicture = new JLabel(new ImageIcon(""
+ names[comboTypesList.getSelectedIndex()] + ".jpg"));
jlbPicture.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
jlbPicture.setPreferredSize(new Dimension(177, 122 + 10));
// Layout the demo
setLayout(new BorderLayout());
add(comboTypesList, BorderLayout.NORTH);
add(jlbPicture, BorderLayout.SOUTH);
}
public static void main(String s[]) {
JFrame frame = new JFrame("JComboBox Usage Demo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setContentPane(new Font_Chooser());
frame.pack();
frame.setVisible(true);
}
}
I have developed a task manager for linux in java. The output as of now is diplayed in the console whereas a tabbed window appears separatelt (this was done using java swing).
Now I want the output from the console to be displayed in the tabbed window. How do I do it?
There are classes that i ve used. One for the task manager functionalities and the other for GUI. I ve pasted below the codings for somebod to help me out pls..
**TabbedPaneDemo1.java**
package components;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Writer;
import java.util.Iterator;
import java.util.List;
/*
* TabbedPaneDemo.java requires one additional file:
* images/middle.gif.
*/
import javax.swing.JTabbedPane;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
public class TabbedPaneDemo1
{
public static void main(String args[]) throws Exception
{
try
{
TextArea textarea = new TextArea();
TabbedPaneDemo obj = new TabbedPaneDemo();
obj.fn();
String line;
String result = "";
FileOutputStream out;
//FileOutputStream out; // declare a file output object
PrintStream p;
Process p1 = Runtime.getRuntime().exec("tasklist.exe");
out = new FileOutputStream("myfile.txt");//write to a file//
p = new PrintStream( out );
BufferedReader input = new BufferedReader(new InputStreamReader(p1.getInputStream()));//read form a file//
while ((line = input.readLine()) != null)
{
System.out.println(line);
//textarea.append(line + "\n");
result += line+"\n";
p.println (line);
//textarea.setVisible(true);
}
//msgBox(result);
p.close();
input.close();
}
catch(Exception e)
{
}
}
public static void msgBox(String msg) {
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
null, msg, "WindowsUtils",
javax.swing.JOptionPane.DEFAULT_OPTION);
}
}
**TabbedPaneDemo.java**
package components;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.JTabbedPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
public class TabbedPaneDemo extends JPanel {
Integer i;
public TabbedPaneDemo() {
super(new GridLayout(1, 1));
JTabbedPane tabbedPane = new JTabbedPane();
ImageIcon icon = createImageIcon("images");
JComponent panel1 = makeTextPanel("tasklist");
tabbedPane.addTab("tasks", icon, panel1,
"ta");
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
JComponent panel2 = makeTextPanel("windows");
tabbedPane.addTab("wins", icon, panel2,
"wi");
tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
add(tabbedPane);`enter code here`
tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
}
protected JComponent makeTextPanel(String text)
{
JPanel panel = new JPanel(false);
JLabel filler = new JLabel(text);
filler.setHorizontalAlignment(JLabel.CENTER);
panel.setLayout(new GridLayout(1, 1));
panel.add(filler);
return panel;
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = TabbedPaneDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("TabbedPaneDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TabbedPaneDemo(), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void fn() {
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
If you used swing to create a JTabbedPane, the simplest way to update it with content is probably adding a JTextArea to it like this:
tab.add(textarea);
Then update the textarea with whatever you'd like it to display with
textarea.setText(); // or append();
To add input from the console via stream do something like this:
BufferedReader input = new BufferedReader(
new InputStreamReader(consoleProcess.getInputStream()));
String text;
while ((text = input.readLine()) != null)
{
textarea.append(text + "\n");
}
input.close();