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();
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'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
}
}
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);
}
}
So I hit the following problem: I want to initializate the Swing constructor with a controller instance from my App class. That is the place I init the repo and controller. When i want to pass to the swing Gui class, the controller parameter I realized it has its own main method.
Could you please check the code and tell me if this is the correct approach? 'Cause I'm uncertain, and i can't find a basic example from a TUI app to a GUI app. Thank you!
App.java
package app;
import repository.*;
import view.View_gui;
import controller.*;
public class App{
RepoInterface ri;
ControllerInterface c;
View_gui gui;
public App() {
ri = new Repo();
c = new Controller(ri);
gui = new View_gui(c);
}
public static void main(String[] args) {
App app = new App();
}
}
View_gui.java
package view;
import controller.*;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import com.jgoodies.forms.factories.DefaultComponentFactory;
import java.awt.BorderLayout;
import java.awt.Label;
import java.awt.Panel;
import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JSeparator;
import javax.swing.JPanel;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.GridLayout;
public class View_gui {
private JFrame frame;
private static ControllerInterface ci; //added the variable
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
View_gui window = new View_gui(ci); // parametrizied
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public View_gui(ControllerInterface c) {
ci = c; // add + param by me
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame("Countries");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblNewLabel = new JLabel("Country");
JLabel lblCapital = new JLabel("Capital");
JLabel lblArea = new JLabel("Area");
}
}