Swing GUI moving when user enters text - java

I am trying to do a fairly basic swing GUI where a user can enter a url, choose a local file location etc. I am using multiple layout managers including boxlayout, borderlayout and flowlayout. The code is below.
My problem is that some of the components are moving around when the user puts text into the optionsTxt jtextarea. Anyone know where I should start to stop this happening?
Setup menu bar
JButton menu_File = new JButton("File");
JButton menu_Edit = new JButton("Edit");
JToolBar toolBar = new JToolBar();
toolBar.add(menu_File);
toolBar.add(menu_Edit);
//Setup options area
JPanel options = new JPanel();
options.setBorder(BorderFactory.createTitledBorder("Options"));
BoxLayout layout_Options = new BoxLayout(options, BoxLayout.Y_AXIS);
options.setLayout(layout_Options);
JLabel optionsLblURL = new JLabel("Enter URL:");
optionsTxtUrl = new JTextArea(1,15);
JLabel chooseDestLbl = new JLabel("Choose save location:");
chooseDest = new JButton("Browse");
chooseDest.addActionListener(this);
options.add(optionsLblURL);
options.add(optionsTxtUrl);
options.add(chooseDestLbl);
options.add(chooseDest);
//Setup launch area
JPanel launch = new JPanel();
launch.setBorder(BorderFactory.createTitledBorder("Launch"));
launchBtnStart = new JButton("Start Download");
launchBtnStart.setVerticalAlignment(SwingConstants.CENTER);
launchBtnStart.setHorizontalAlignment(SwingConstants.CENTER);
launchBtnStart.addActionListener(this);
launch.add(launchBtnStart);
//Setup reporting area
JPanel logging = new JPanel();
logging.setBorder(BorderFactory.createTitledBorder("Log"));
BoxLayout layout_Logging = new BoxLayout(logging, BoxLayout.Y_AXIS);
logging.setLayout(layout_Logging);
JTextArea loggingTxt = new JTextArea(3,10);
loggingTxt.setEditable(false);
logging.add(pb);
logging.add(loggingTxt);
//Add components to window
BorderLayout borderLayout = new BorderLayout();
setLayout(borderLayout);
add("North", toolBar);
add("West", options);
add("East", launch);
add("South", logging);
setVisible(true);

"My problem is that some of the components are moving around when the user puts text into the optionsTxt jtextarea. Anyone know where I should start to stop this happening?"
Start by putting your JTextArea in a ScrollPane and setLineWrap(true) and setWrapStyleWord(true). You may want to consider doing this with both JTextAreas you have
JTextArea optionsTxtUrl = new JTextArea(1,15);
optionsTxtUrl.setLineWrap(true);
optionsTxtUrl.setWrapStyleWord(true);
JScrollPane scroll = new JScrollPane(optionsTxtUrl);
options.add(scroll); // take out options.add(optionsTxtUrl);
This will make your lines wrap when they reach the right edge of the text area
public void setWrapStyleWord(boolean word) - Sets the style of wrapping used if the text area is wrapping lines. If set to true the lines will be wrapped at word boundaries (whitespace) if they are too long to fit within the allocated width. If set to false, the lines will be wrapped at character boundaries. By default this property is false.
public void setLineWrap(boolean wrap) - Sets the line-wrapping policy of the text area. If set to true the lines will be wrapped if they are too long to fit within the allocated width. If set to false, the lines will always be unwrapped. A PropertyChange event ("lineWrap") is fired when the policy is changed. By default this property is false.
If this doesn't solve your problem, you should edit your post with a Minimal, Complete, Tested and Readable example so we can test out your problem.

Related

JScrollPane Not Scrolling In JTextArea

There's something that I don't understand. My code does not like JScrollBar apparently. I add it and I cannot scroll horizontally nor vertically.
Here's what it looks like:
Keep in mind that I'm new and I'm still working on it, so I'm sorry if it was something really obvious and easily avoidable.
public ChangeLog() {
//Init.
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JTextArea textarea = new JTextArea();
JScrollPane scrollpane = new JScrollPane(textarea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//Text Stuff
textarea.setFont(textarea.getFont().deriveFont(16f));
textarea.setText("Change Log: \n V1.0(A): Original encoder \n V1.0(B): Original decoder \n V1.1: Combination of both encoder and decoder \n V1.2: Added a heavier encoding & decoding system \n V1.3: Added an icon \n V1.4: Created an 'Info' page \n V1.5: Added a 'Change Log' page to the 'Info' page \n "
+ "V1.6: Removed the 'Change Log' \n V1.7: Added a 'Change Log' but was not implemented \n V1.8: Added a the 'Change Log' button \n V1.9: Added horizontal and vertical scroll bars to the 'Change Log'");
textarea.setForeground(Color.BLACK);
Dimension d = new Dimension(250, 275);
textarea.setPreferredSize(d);
//Other Stuff
scrollpane.setViewportView(textarea);
scrollpane.getPreferredSize();
//Layout
panel.setLayout(null);
scrollpane.setBounds(new Rectangle(new Point(20, 20), scrollpane.getPreferredSize()));
textarea.setBounds(new Rectangle(new Point(20, 23), textarea.getPreferredSize()));
//Frame Stuff
frame.setAlwaysOnTop(true);
frame.setSize(300, 350);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
//Panel Stuff
frame.add(panel);
panel.setSize(frame.getSize());
panel.setBackground(Color.BLUE);
panel.add(textarea);
panel.add(scrollpane);
} }
I have created a working solution. Made some changes also.
public TestClass() {
//Init.
JFrame frame = new JFrame();
JPanel panel = new JPanel(new BorderLayout());
JTextArea textarea = new JTextArea();
JScrollPane scrollpane = new JScrollPane(textarea);
panel.add(scrollpane, BorderLayout.CENTER);
//Text Stuff
textarea.setFont(textarea.getFont().deriveFont(16f));
textarea.setText("Change Log: \n V1.0(A): Original encoder \n V1.0(B): Original decoder \n V1.1: Combination of both encoder and decoder \n V1.2: Added a heavier encoding & decoding system \n V1.3: Added an icon \n V1.4: Created an 'Info' page \n V1.5: Added a 'Change Log' page to the 'Info' page \n "
+ "V1.6: Removed the 'Change Log' \n V1.7: Added a 'Change Log' but was not implemented \n V1.8: Added a the 'Change Log' button \n V1.9: Added horizontal and vertical scroll bars to the 'Change Log'");
textarea.setForeground(Color.BLACK);
//Dimension d = new Dimension(250, 275);
//textarea.setPreferredSize(d);
//Other Stuff
scrollpane.setViewportView(textarea);
scrollpane.getPreferredSize();
//Layout
//scrollpane.setBounds(new Rectangle(new Point(20, 20), scrollpane.getPreferredSize()));
//textarea.setBounds(new Rectangle(new Point(20, 23), textarea.getPreferredSize()));
//Listeners
//Frame Stuff
frame.setAlwaysOnTop(true);
frame.setSize(300, 350);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
//Panel Stuff
frame.add(panel);
panel.setSize(frame.getSize());
panel.setBackground(Color.BLUE);
panel.add(scrollpane);
}
Also when swing better works with the layout managers and null layout will leads to inconsistent look on different screen types.
Let me know if anything more required. And yes everybody starts from scratch. I am still learning. You will too get many things. Just keep the hunger of learning. :-)
Dimension d = new Dimension(250, 275);
textarea.setPreferredSize(d);
Don't hardcode a size for the text area. The size of the text area will change dynamically as text is added/removed and scrollbars will appear/disappear as required.
JTextArea textarea = new JTextArea();
Don't create the text area with no parameters. Instead, when you create the text area use something like:
JTextArea textarea = new JTextArea(5, 20);
to suggest a default size of the text area. Then when you have more than 5 lines of text the scrollbar will appear.
So I'm a relatively new Java developer
Start by reading the Swing Tutorial for Swing basics. There is a section on How to Use Text Areas to get you started.
panel.setLayout(null);
scrollpane.setBounds(...)
Don't a null layout. Don't use setBounds(). Swing was designed to be used with layout managers. See the above tutorial for working examples.

how to create 2 content panels in north widget

can we create 2 content panels in north widget.
BorderLayoutContainer con = new BorderLayoutContainer();
ContentPanel cp = new ContentPanel();
VerticalLayoutContainer logoLayout = new VerticalLayoutContainer();
BorderLayoutData d = new BorderLayoutData(.20);
d.setMargins(new Margins());
Image logo = new Image("/IMAGES/Logo.png");
logoLayout.add(logo);
cp.add(logoLayout);
cp.setHeaderVisible(false);
con.setNorthWidget(cp, d);
please suggest me how to create two content panels.
Basically what I need to do is - please look into the image and let me know what I can do for that
You create your two panels within a single panel, and then assign that single panel to NORTH. Remember that your overall layout can be created from nested layouts.
ContentPanel cp = new ContentPanel();
JPanel panelA = new JPanel();
JPanel panelB = new JPanel();
JPanel panelBig = new JPanel();
panelBig.add(panelA);
panelBig.add(panelB);
cp.add(panelBig, BorderLayout.NORTH);
I think you can probably work out the rest of the details on your own.

Add HTML in JEditorPane in Java Swing

I would like to add HTML in my JEditorPane but the text is not displayed correctly.
Also, when the text's height is greater that the editor's height,
the the cursor goes to the last line of the scroll Pane.
My code is as follows:
JPanel JPInfo = new JPanel(new BorderLayout());
JPInfo.setBorder(BorderFactory.createTitledBorder("Information"));
editorPaneInfo = new JEditorPane();
editorPaneInfo.setEditable(false);
editorPaneInfo.setText("<html><p style=\"color:green\"> Test Test </p></html>");
JScrollPane editorScrollPaneInfo = new JScrollPane(editorPaneInfo);
editorScrollPaneInfo.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPInfo.add(editorScrollPaneInfo,BorderLayout.CENTER);
SOLVED:
I added the following line before setText
editorPaneInfo.setContentType("text/html");
My problem was solved:
I added the following line before .setText()
editorPaneInfo.setContentType("text/html");

updating JLabel image, dynamic via selection

So basically im creating a GUI that allows the user to select a file, this file is check to be a .wav file. Then this file's data is graphed through JFreechart.
This graph or image created by Jfreechart i want to put into the JFrame.
The problem is that the code:
ImageIcon myIcon1 = new ImageIcon("blah.jpg");
JLabel graphLabel1 = new JLabel(myIcon1);
southContent.add(graphLabel1);
must be created & declared in the method where i create the JFrame ( must be added to the frame )
thus i cannot dynamically update the image to new created graphs, depending on what file the user selects. ( on selection of a new file, via button a new graph image is created )
is there a way to force
ImageIcon myIcon1 = new ImageIcon("blah.jpg");
JLabel graphLabel1 = new JLabel(myIcon1);
southContent.add(graphLabel1);
to update to the new image ( in the same direcotry, with the same name )
or is there a way using Mapping to set the image name ("blah.jpg") dynamically with a counter?
here is my SSCCE
public class gui extends JFrame {
ImageIcon myIcon1 = new ImageIcon("C:/location/chart1.jpg");
JLabel graphLabel1 = new JLabel(myIcon1);
gui() {
// create Pane + contents & listeners...
JPanel content = new JPanel();
JPanel southContent = new JPanel();
content.setLayout(new FlowLayout());
content.add(open_File);
// Jfreechart graph image -- not visible until selected
graphLabel1.setVisible(false);
// this is the graph image being added to the panel
southContent.add(graphLabel1);
southContent.setLayout(new FlowLayout());
// add action listeners to buttons
open_File.addActionListener(new OpenAction());
// set Pane allignments & size...
this.setContentPane(content);
this.add(southContent, BorderLayout.SOUTH);
this.setTitle("Count Words");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1100, 720);
this.setLocationRelativeTo(null);
}
// opening selected file directory.
class OpenAction implements ActionListener {
public void actionPerformed(ActionEvent ae) {
/// gets user selection ( file ) and procesess .wav data into array
/// loops through array creating X series for JfreeChart
// Add the series "series" to data set "dataset"
dataset.addSeries(series);
// create the graph
JFreeChart chart = ChartFactory.createXYLineChart(
".Wav files", // Graph Title
"Bytes", // X axis name
"Frequency", // Y axis name
dataset, // Dataset
PlotOrientation.VERTICAL, // Plot orientation
true, // Show Legend
true, // tooltips
false // generate URLs?
);
try {
ChartUtilities.saveChartAsJPEG(
new File("C:/location/chart1.jpg"), chart, 1000, 600);
} catch (IOException e) {
System.err.println("Error occured: " + e + "");
}
// !!!!! this is where i need to set the ImageIcon added to the
// panel in "gui" to this new created Graph image ("chart1.jpg")
// as above
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// sets the image label itself to visible as a new image has been
// added ot it
graphLabel1.setVisible(true);
}
}
}
Just add the JLabel to its container as you usually do. Then, once you created the image and you have an instance of an ImageIcon, just call the setIcon() method for the JLabel.
Using something like this should allow displaying both images of the waveform, as well as new images of the waveform.
try {
//ChartUtilities.saveChartAsJPEG(
// new File("C:/location/chart1.jpg"), chart, 1000, 600);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ChartUtilities.saveChartAsPNG(baos, chart, 1000, 600);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
BufferedImage image = ImageIO.read(bais);
// !!!!! this is where we need to set the ImageIcon..
graphLabel1.setIcon(new ImageIcon(image));
} catch (IOException e) {
e.printStackTrace();
System.err.println("Error occured: " + e + "");
}
OTOH you might look to increasing the memory size and generate the entire waveform in one pass, then display the label in a scroll pane.
Thanks to Dan and Andrew Thompson, i have a working product.
I used a counting variable to count teach time the "OpenAction" button was selected.
i then used this variable to make dynamic names for each image i created through JFreechart.
Thus i used .setIcon to reset the icon image to each new created image with a new name.
.setIcon does not seem to work if you are trying to reset the label to a Image icon that has the same name as the previously selected Image icon.
the finished code segment looks like:
ImageIcon myIcon1 = new ImageIcon("C:/location/chart"+CounterVariable+".png");
graphLabel1.setIcon(myIcon1);
for example this will create charts;
chart1
chart2
chart3
and so forth.

using a box layout in java

the following codes created a box layout conviniently but the problem i have is the textfields occupy the entire rows. which is supposed to asume the parameter length in which it was specified.
public void makeControlpanel(){
JPanel controlpanel = new JPanel();
//SET PANEL LAYOUT MANAGERS
controlpanel.setLayout(new BoxLayout(controlpanel,BoxLayout.PAGE_AXIS));
controlpanel.setBorder(BorderFactory.createTitledBorder("Create Control file"));
filenameC = new JLabel("Filename");
filenameBad = new JLabel("Bad Filename");
filenameDis = new JLabel("Discard Filename");
// fields
fileField = new JTextField(1);
badfileField = new JTextField(7);
discardfileField = new JTextField(7);
The layout manager decides the size of the components. You have options to define the bounds of a component to the layout manager using
comp.setMinimumSize(new Dimension(w, h));
comp.setPreferredSize(new Dimension(w, h));
comp.setMaximumSize(new Dimension(w, h));
When you give setPreferredSize layout manager will try to give that size. GridBagLayout is the msot flexible layout and you can prettymuch achieve any layout you need.
The parameter length by defenition only defines the character you can put in the textfield.

Categories