In my program, I'm using javahelp with helpbroker: all the swing components of the window are automatically generated and positioned.
I would like custom the helpbroker to add a button bar at the bottom of the window like in the image.
What is the easiest way to do it ?
Thanks
The only way to add a help button is to Embed the javahelp in a JFrame:
public class vmHelp {
public static void main(String args[]) {
JHelp helpViewer = null;
String title = "";
try {
// Get the classloader of this class.
ClassLoader cl = vmHelp.class.getClassLoader();
// Use the findHelpSet method of HelpSet to create a URL referencing the helpset file.
// Note that in this example the location of the helpset is implied as being in the same
// directory as the program by specifying "jhelpset.hs" without any directory prefix,
// this should be adjusted to suit the implementation.
String lHelpSetFile = "APP.hs";
URL url = HelpSet.findHelpSet(cl, lHelpSetFile);
if (url == null) {
System.err.println("URL is null, maybe the help set file is wrong: " + lHelpSetFile + ". Look at vmHelp.java");
return;
}
// Create a new JHelp object with a new HelpSet.
HelpSet h = new HelpSet(cl, url);
title = h.getTitle();
helpViewer = new JHelp(h);
// Set the initial entry point in the table of contents.
helpViewer.setCurrentID("top");
} catch (Exception e) {
System.err.println(e.getMessage());
}
// Create a new frame.
JFrame frame = new JFrame();
// Set it's size.
frame.setSize(1000, 800);
// Add the created helpViewer to it.
frame.getContentPane().add(helpViewer);
// Set a default close operation.
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setTitle(title);
// Make the frame visible.
frame.setVisible(true);
}
}
After we can customize the JFrame as we want, it is easy to add a south panel with a close button.
To make all the help buttons listen our javahelp:
pButton.addActionListener(helpAction(pHelpId));
with helpAction that displays our JFrame
Think also to handle keyboard shortcuts, like the helpbroker:
pComponent.registerKeyboardAction(helpAction(pHelpId), KeyStroke.getKeyStroke(KeyEvent.VK_HELP, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
pComponent.registerKeyboardAction(helpAction(pHelpId), KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
To open the help at the wanted section:
helpViewer.setCurrentID("top");
"top" corresponds to tag in the .jhm file
Related
I am trying to return an ArrayList with two values, text and a text area. However when I press the button that is meant to do this, nothing happens. Can you please explain why this is the case?
The method that returns the ArrayList:
public ArrayList<Object> newFile(){
ArrayList<Object> objectArrayList = new ArrayList<>();
TextArea textField = new TextArea("Type File Information.., ");
AtomicReference<String> fileText = new AtomicReference<>();
textField.addTextListener((textListener) -> {
fileText.set(textField.getText());
});
objectArrayList.add(String.valueOf(fileText));
objectArrayList.add(textField);
return objectArrayList;
}
}
The code snippet that executes the method and gets the text area:
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
switch (action) {
case "New":
fileText = (String) newFile().get(0);
MainMenu mainMenu = new MainMenu();
mainMenu.add((TextArea)newFile().get(1));
break;
The code snippet where I add the handler:
newFile.addActionListener(mainMenuHandler);
Why are you using AWT. You should at least be using Swing.
MainMenu mainMenu = new MainMenu();
mainMenu.add((TextArea)newFile().get(1));
In your case you add the text area to the MainMenu, but you never add the MainMenu to the frame.
So you would need to add the "mainMenu" to the frame.
Also, when using Swing if you add a component to a visible frame then you need to invoke revalidate() and repaint() on the container you add the component to.
I'm trying to write the contents of an array to a JTextArea. I've tried everything I can think of, and I can't understand what isn't working here. I've stripped the unnecessary stuff out of my code, here's the two relevant classfiles:
Main class:
package irclogtest;
public class BriBotMain {
public static void main(String args[]) throws Exception {
boolean startup = true;
//frame test launch
BriDisplayGUI data = new BriDisplayGUI(startup);
data.irclog.append("BriBot Startup Successful!" + "\n");
//example access through function when startup is false (only in main class for sample code to demonstrate issue)
try {
BriDisplayGUI data2 = new BriDisplayGUI(false); //tells us which class we're accessing
String[] textForGUI = new String[2]; //tells us the array has 2 lines
textForGUI[0] = "this is the first line"; //set the first line of the array to this text
textForGUI[1] = "this is the second";
data2.arrayToDisplay(textForGUI); //appends contents of array to text window
}
catch(Exception e) {
System.out.println(e);
}
}
}
GUI display class:
package irclogtest;
import java.awt.event.*;
import java.io.IOException;
import javax.swing.*;
public class BriDisplayGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = -7811223081379421773L;
String file_name = "C:/Bribot/logfile.txt";
//these lines create the objects we use
JFrame frame = new JFrame();
JPanel pane = new JPanel();
JButton pressme = new JButton("Click here");
JButton pressme2 = new JButton("Also here");
JTextArea irclog = new JTextArea( 20, 70);
JScrollPane scrollirc = new JScrollPane(irclog);
public BriDisplayGUI(boolean startup) { //startup function, opens and sets up the window
if(startup == true){
frame.setTitle("Bribot Test Frame"); frame.setBounds(100,100,840,420); //sets title of window, sets position and size of window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //tells program to end on window close
frame.add(pane); //adds the main display pane to the window
//panel customization goes here
pressme.addActionListener(this);
pane.add(pressme);
pressme2.addActionListener(this);
pane.add(pressme2);
pressme.requestFocusInWindow();
irclog.setEditable(false);
scrollirc.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
pane.add(scrollirc);
irclog.setLineWrap(true);
irclog.setWrapStyleWord(true);
//pane.add(inputthing);
frame.setVisible(true);
} else {
System.out.println("Display Class Called");
}
}
public void arrayToDisplay(String[] text) throws IOException {
int i;
for ( i=0; i < text.length; i++) {
irclog.append( text[i] + "\n");
System.out.println( i + ": " + text[i]);
}
}
public void singleToDisplay(String text) throws IOException {
irclog.append(text + "\n");
System.out.println(text);
}
//basic event handler
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == pressme) {
} else if(source == pressme2) {
}
}
}
The first append works fine, but the second doesn't, and I can't figure out why (although the for loop does, as the contents of the array get written to console). I've searched quite a bit and nothing I've tried works. Can anyone point out the inevitable obvious oversight here? I'm the definition of a novice, so any advice is appreciated.
Thanks!
The default constructor doesn't do anything, meaning it doesn't construct any kind of UI or display, what would be, an empty frame.
You seem to be thinking the text will appear in data when you are appending it to data1
Try calling this(false) within the default constructor
A better solution would be to construct the core UI from the default constructor and from the "startup" constructor call this() and then modify the UI in what ever way this constructor needs
It seems like you write a new program. Why do you use Swing? Did you take a look at JavaFX?
I am not sure if that is going to fix your problem but you could try a foreach
for(String s : text){
irclog.append(s+"\n");
}
I have a JPanel inside a Anchor Pane inside a JavaFX project. The problem I'm having is the content that's loaded inside the panel is not confined to the panel and cuts off text once it reaches the edge of the panel instead of moving on to the next line.
This is fine however if I test the panel inside a Jframe.
The Anchor panel was created and placed in the user interface using Scene Builder for JavaFX.
Below is the code where I make labels of ranging font sizes(this is to created a Word Cloud) and place them in a JPanel and then return this panel.
public JPanel nnsePairWordCloud() throws SQLException, InstantiationException, IllegalAccessException {
Database databaseConnection = new Database();
databaseConnection.getConnection();
ResultSet nnsePairs = databaseConnection.getNNSEPairInfoFromDatabase();
ResultSet nnseScores = databaseConnection.getNNSESimilarityResultsFromDatabase();
//adding words from the database to the array that will make up the word cloud
while(nnsePairs.next()) {
String wordPair = nnsePairs.getString(1);
WORDS.add(wordPair);
}
//adding each pairs weighting from the database - this will determine the size of the word
while(nnseScores.next()) {
Double wordResult = nnseScores.getDouble(1);
WEIGHTINGS.add(wordResult);
}
System.out.println("cloud data got");
JPanel panel = new JPanel();
panel.setSize(380, 275);
Cloud cloud = new Cloud();
// cloud.setMinWeight(-1);
//cloud.setMaxWeight(1);
cloud.setMaxTagsToDisplay(300);
//Random random = new Random();
for (int i =0; i<WORDS.size(); i++) {
cloud.addTag(new Tag(WORDS.get(i), WEIGHTINGS.get(i)));
}
for (Tag tag : cloud.tags()) {
final JLabel label = new JLabel(tag.getName());
label.setOpaque(false);
label.setFont(label.getFont().deriveFont((float) tag.getWeight() * 10));
panel.add(label);
}
//frame.add(panel);
//frame.setSize(800, 600);
//frame.setVisible(true);
return panel;
}
And here's the code where the panel is returned to and set - creates a SwingNode first and then loads the content. I had to do it this way so I could load the content in the JavaFX UI.
final SwingNode nodeForWordCloud = new SwingNode();
createAndSetSwingContentForWordCloud(nodeForWordCloud);
wordCloudBox.getChildren().add(nodeForWordCloud);
private void createAndSetSwingContentForWordCloud(final SwingNode swingNode) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
swingNode.setContent(new WordCloud().initUI());
} catch (SQLException ex) {
Logger.getLogger(WordNetPairPageController.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(WordNetPairPageController.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(WordNetPairPageController.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
Figured it out.
If I use a JavaFX FlowPane instead then it solves both the problems I was having. The content now flows within the pane and doesn't cut off and the content loads straight away as its no longer a swing component so it doesn't have to run on a separate thread.
Anyone having similar problems look up how the different layouts in Java FX work as this will help you figure out which one to use. These panels work very differently than they do in Swing.
is there any way to save an image from a java applet
Been asked before:
Java applet - saving an image in a png format
or
Save an Image to a File in a Applet?
Please first search your question or at least check out the related questions as you type your question in. It's very helpful for finding other users with common issues.
Just try this notepad example which helps u to load images and save it also,
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
import java.io.*;
public class Notepad extends JFrame implements ActionListener {
private TextArea textArea = new TextArea("", 0,0, TextArea.SCROLLBARS_VERTICAL_ONLY);
private MenuBar menuBar = new MenuBar(); // first, create a MenuBar item
private Menu file = new Menu(); // our File menu
// what's going in File? let's see...
private MenuItem openFile = new MenuItem(); // an open option
private MenuItem saveFile = new MenuItem(); // a save option
private MenuItem close = new MenuItem(); // and a close option!
public Notepad() {
this.setSize(500, 300); // set the initial size of the window
this.setTitle("Java Notepad Tutorial"); // set the title of the window
setDefaultCloseOperation(EXIT_ON_CLOSE); // set the default close operation (exit when it gets closed)
this.textArea.setFont(new Font("Century Gothic", Font.BOLD, 12)); // set a default font for the TextArea
// this is why we didn't have to worry about the size of the TextArea!
this.getContentPane().setLayout(new BorderLayout()); // the BorderLayout bit makes it fill it automatically
this.getContentPane().add(textArea);
// add our menu bar into the GUI
this.setMenuBar(this.menuBar);
this.menuBar.add(this.file); // we'll configure this later
// first off, the design of the menuBar itself. Pretty simple, all we need to do
// is add a couple of menus, which will be populated later on
this.file.setLabel("File");
// now it's time to work with the menu. I'm only going to add a basic File menu
// but you could add more!
// now we can start working on the content of the menu~ this
gets a little repetitive,
// so please bare with me!
// time for the repetitive stuff. let's add the "Open" option
this.openFile.setLabel("Open"); // set the label of the menu item
this.openFile.addActionListener(this);
// add an action listener (so we know when it's been clicked
this.openFile.setShortcut(new MenuShortcut(KeyEvent.VK_O, false));
// set a keyboard shortcut
this.file.add(this.openFile); // add it to the "File" menu
// and the save...
this.saveFile.setLabel("Save");
this.saveFile.addActionListener(this);
this.saveFile.setShortcut(new MenuShortcut(KeyEvent.VK_S, false));
this.file.add(this.saveFile);
// and finally, the close option
this.close.setLabel("Close");
// along with our "CTRL+F4" shortcut to close the window, we also have
// the default closer, as stated at the beginning of this tutorial.
// this means that we actually have TWO shortcuts to close:
// 1) the default close operation (example, Alt+F4 on Windows)
// 2) CTRL+F4, which we are about to define now:
(this one will appear in the label)
this.close.setShortcut(new MenuShortcut(KeyEvent.VK_F4, false));
this.close.addActionListener(this);
this.file.add(this.close);
}
public void actionPerformed (ActionEvent e) {
// if the source of the event was our "close" option
if (e.getSource() == this.close)
this.dispose(); // dispose all resources and close the application
// if the source was the "open" option
else if (e.getSource() == this.openFile) {
JFileChooser open = new JFileChooser();
// open up a file chooser (a dialog for the user to browse files to open)
int option = open.showOpenDialog(this);
// get the option that the user selected (approve or cancel)
// NOTE: because we are OPENing a file, we call showOpenDialog~
// if the user clicked OK, we have "APPROVE_OPTION"
// so we want to open the file
if (option == JFileChooser.APPROVE_OPTION) {
this.textArea.setText("");
// clear the TextArea before applying the file contents
try {
// create a scanner to read the file (getSelectedFile().getPath() will get the path to the file)
Scanner scan = new Scanner(new FileReader(open.getSelectedFile().getPath()));
while (scan.hasNext()) // while there's still something to read
this.textArea.append(scan.nextLine() + "\n"); // append the line to the TextArea
} catch (Exception ex) { // catch any exceptions, and...
// ...write to the debug console
System.out.println(ex.getMessage());
}
}
}
// and lastly, if the source of the event was the "save" option
else if (e.getSource() == this.saveFile) {
JFileChooser save = new JFileChooser(); // again, open a file chooser
int option = save.showSaveDialog(this); // similar to the open file, only this time we call
// showSaveDialog instead of showOpenDialog
// if the user clicked OK (and not cancel)
if (option == JFileChooser.APPROVE_OPTION) {
try {
// create a buffered writer to write to a file
BufferedWriter out = new BufferedWriter(new FileWriter(save.getSelectedFile().getPath()));
out.write(this.textArea.getText()); // write the contents of the TextArea to the file
out.close(); // close the file stream
} catch (Exception ex) { // again, catch any exceptions and...
// ...write to the debug console
System.out.println(ex.getMessage());
}
}
}
}
// the main method, for actually creating our notepad and setting it to visible.
public static void main(String args[]) {
Notepad app = new Notepad();
app.setVisible(true);
}
}
I am working on a JFrame/panel that will contain a button. When the user clicks the button, I want an image (which will be stored in the computer hard disk beforehand) to open on the front screen.
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//here i want a code that will somehow open the image from a given directory
}});
Any suggestions on how to go about this ? I have to tell where the image is stored and trigger a virtual 'double click' for the image to pop up on the front screen. Is that even possible using java to synchronize such computer functions?
I don't know a very short way, but I would use something like this (as qick hack to get an impression):
try {
// this is a new frame, where the picture should be shown
final JFrame showPictureFrame = new JFrame("Title");
// we will put the picture into this label
JLabel pictureLabel = new JLabel();
/* The following will read the image */
// you should get your picture-path in another way. e.g. with a JFileChooser
String path = "C:\\Users\\Public\\Pictures\\Sample Pictures\\Koala.jpg";
URL url = new File(path).toURI().toURL();
BufferedImage img = ImageIO.read(url);
/* until here */
// add the image as ImageIcon to the label
pictureLabel.setIcon(new ImageIcon(img));
// add the label to the frame
showPictureFrame.add(pictureLabel);
// pack everything (does many stuff. e.g. resizes the frame to fit the image)
showPictureFrame.pack();
//this is how you should open a new Frame or Dialog, but only using showPictureFrame.setVisible(true); would also work.
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
showPictureFrame.setVisible(true);
}
});
} catch (IOException ex) {
System.err.println("Some IOException accured (did you set the right path?): ");
System.err.println(ex.getMessage());
}
I think this will work ...
Code:
process = new ProcessBuilder("mspaint","yourFileName.jpeg").start();
This will open your image file with mspaint.....
and also use *Java Advanced Imaging (JAI)*
Try this code
try
{
// the line that reads the image file
BufferedImage image;
// work with the image here ...
image = ImageIO.read(new File("C://Users//Neo//Desktop//arduino.jpg"));
jLabel1.setIcon(new ImageIcon(image));
}
catch (IOException e)
{
// log the exception
// re-throw if desired
}
I'm not sure but try this...
try
{
JLabel picture=new JLabel();
ImageIcon ic=new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("C:\\Users\\Desktop\\xyz.jpg")));
picture.setIcon(ic);
}
catch(Exception)
{
}