JProgressBar in JTextPane - java

I added a progress bar to my text pane but I cannot re-size the width of the progress bar added (can re-size height). could you please help me with this issue and also tell me how can I remove the progress bar once I am done with it.
JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
progressBar.setPreferredSize(new Dimension(50, 15));
progressBar.setMinimum(0);
progressBar.setMaximum((int) file.length());
textPane.setSelectionStart(textPane.getText().length());
textPane.setSelectionEnd(textPane.getText().length());
textPane.insertComponent(progressBar);

I think you are questioning about how to set your preferred width for the JProgressBar, right?
If this is your question, you should use setMaximumSize instead of setPreferredSize:
JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
//progressBar.setPreferredSize(new Dimension(50, 15));
progressBar.setMaximumSize(new Dimension(50, 15)); // This line instead of above line
progressBar.setMinimum(0);
progressBar.setMaximum((int) file.length());
[EDIT]
For removing components you should assume the components in your JTextPane as some characters, and then remove them from JTextPane's Document object. I also assumed a temp JButton to raise the remove event:
JButton b = new JButton("Remove!");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
textPane.getDocument().remove(0, 1);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
});
Good Luck.

Related

Why does some of my components such as JLabel and JComboBox sometimes not appear after using a JButton?

I'm trying to transition from the home screen to the option menu through a JButton by adding a JPanel (menu) to the frame and hiding the currently visible panel (background). I'm using an Action Listener to activate the transition. Sometimes when running the code (more like most of the time), some parts of the menu won't appear such as the JComboBox and two of the JLabels. I'm not having an issue with the JSlider though, but I haven't been able to identify the problem for the other components. I tried implementing menu.revalidate() and menu.setVisible(true) at the end of my code, but to no prevail. I also tried doing frame.revalidate() and frame.setVisible(true). Another attempt at fixing this was by moving around the menu.add([insert JLabel/JComboBox]).
The code that I used is as provided
Window.java
JFrame frame;
JPanel background;
JPanel menu;
JSlider difficulty;
JLabel difficultyLabel;
JComboBox exerciseChoice;
JPanel dropDownPanel;
JLabel exerciseChoiceLabel;
JPanel difficultyPanel;
public ActionListener startButtonPressed() throws IOException {
ActionListener temp =
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
background.setVisible(false);
menu = new JPanel();
menu.setLayout(new BoxLayout (menu, BoxLayout.Y_AXIS));
menu.setBounds(menu.getLocation().x+50, 50, 700, 100);
menu.setBackground(Color.WHITE);
startButton.setEnabled(false);
createDifficultySlider();
createWorkoutDropDown();
frame.add(menu);
frame.setVisible(true);
} catch (IOException r) {}
}
};
return temp;
}
public void createWorkoutDropDown() throws IOException {
dropDownPanel = new JPanel();
dropDownPanel.setLayout(new FlowLayout(FlowLayout.LEADING));
dropDownPanel.setBackground(Color.WHITE);
String[] choices = {"Abs", "Cardio", "Full Body", "Upper Body", "Stretches", "Lower Body"};
exerciseChoice = new JComboBox(choices);
exerciseChoice.setFont(new Font("Verdana", Font.PLAIN, 20));
exerciseChoiceLabel = new JLabel("Workout Options");
exerciseChoiceLabel.setFont(new Font("Verdana", Font.PLAIN, 20));
dropDownPanel.add(exerciseChoiceLabel);
dropDownPanel.add(exerciseChoice);
menu.add(dropDownPanel);
}
public void createDifficultySlider() throws IOException {
difficultyPanel = new JPanel();
difficultyPanel.setLayout(new FlowLayout(FlowLayout.LEADING));
difficultyPanel.setBackground(Color.WHITE);
difficulty = new JSlider(JSlider.HORIZONTAL, 1, 10, 5);
difficulty.setPreferredSize(new Dimension(difficulty.getPreferredSize().width + 60, difficulty.getPreferredSize().height + 5));
difficultyLabel = new JLabel("Difficulty Level (Easy 1- Hard 10)");
difficultyLabel.setFont(new Font("Verdana", Font.PLAIN, 20));
difficulty.setFont(new Font("Verdana", Font.PLAIN, 10));
difficulty.setMajorTickSpacing(1);
difficulty.setPaintLabels(true);
difficulty.setPaintTicks(true);
difficulty.setSnapToTicks(true);
difficultyPanel.add(difficultyLabel, BorderLayout.PAGE_START);
difficultyPanel.add(difficulty, BorderLayout.LINE_START);
menu.add(difficultyPanel);
}
EDIT: I had to throw IOExceptions because I was importing fonts from my drive.

JProgressBar doesn't look correct

Even using the following code the JProgressBar I'm using to display the progress of a download is far from the Windows 10 native look: in other programs the green part of the progress bar fills the entire height of the progress bar but in Java it doesn't seem to be the case. Also when updated the progress bar feels very chunky compared to other programs.
Here's how it looks normally
https://i.imgur.com/xmhWrxf.png
In java
https://i.imgur.com/81T0hbF.png
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame.setDefaultLookAndFeelDecorated(true);
the main JFrame of my app
private JButton button = new JButton("Test");
private JProgressBar progressBar = new JProgressBar();
private JPanel panel = new JPanel();
public MainFrame()
{
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
progressBar.setMinimum(0);
progressBar.setMaximum(100);
progressBar.setValue(60);
progressBar.setEnabled(true);
progressBar.setPreferredSize(new Dimension(300, 25));
this.panel.add(progressBar);
this.panel.add(button);
this.setSize(400, 600);
this.setContentPane(panel);
this.setVisible(true);
}
This made my progressbar look much better in my opinion.
public static Font defaultFont = new Font(Font.decode(null).getName(), Font.PLAIN, 12);
progressbar.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
progressbar.setBackground(new Color(230, 230, 230));
progressbar.setForeground(new Color(120, 230, 90));
progressbar.setUI(new BasicProgressBarUI() {
#Override
protected Color getSelectionBackground() {
return new Color(50, 50, 50);
}
#Override
protected Color getSelectionForeground() {
return new Color(50, 50, 50);
}
}
Edit: you can optionally use progressbar.setStringPainted(true) to show the percentage

Problems with Changing JTextArea font size

I am trying to prompt the user for input from a JOptionPane to change the font size of the JTextArea, shown below as, "console".
Issue:
However, the JOptionPane is not showing when I click on the size JMenu item.
Code:
Font font = new Font("Arial", Font.PLAIN, 12);
panel = new JPanel();
panel.setLayout(new BorderLayout());
add(panel, BorderLayout.CENTER);
JTextArea console = new JTextArea();
console.setLineWrap(true);
console.setWrapStyleWord(true);
console.setEditable(false);
console.setFont(font);
JScrollPane scroll = new JScrollPane(console);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(scroll, BorderLayout.CENTER);
JMenuBar bar = new JMenuBar();
panel.add(bar, BorderLayout.NORTH);
JMenu size = new JMenu("Size");
size.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
String fontSize = JOptionPane.showInputDialog(panel, "New font size, 6 or larger:", "Set Font Size", JOptionPane.OK_CANCEL_OPTION);
Font newFont = font.deriveFont(Integer.parseInt(fontSize));
console.setFont(newFont);
}
});
bar.add(size);
This seems to be a bug but you could use a ´MenuListener´ as described in this answer by #TPete
Here is the code he provided in his answer to work around the issue:
JMenu menu = new JMenu("MyMenu");
menu.addMenuListener(new MenuListener() {
#Override
public void menuSelected(MenuEvent e) {
System.out.println("menuSelected");
}
#Override
public void menuDeselected(MenuEvent e) {
System.out.println("menuDeselected");
}
#Override
public void menuCanceled(MenuEvent e) {
System.out.println("menuCanceled");
}
});
Basically he's using a MenuListener instead of an ActionListener to catch the event successfully.
Hope this helps!
Issue with the JOptionPane is not showing when I click on the size JMenu item, is because the container where we need to display the pane is incorrect
try the following
JOptionPane.showInputDialog(**this**, "New font size, 6 or larger:",
"Set Font Size", JOptionPane.OK_CANCEL_OPTION);

My whole code is complete but I am not able to add a second button

Please take a look at my code it is working fine the way I want but the only issue is that I want to add another button opposite my current button and I am not able to do so can any body please help me.
import java.awt.event.*;
import javax.swing.*;
public class Example2 extends JFrame {
public Example2() {
initUI();
}
public final void initUI() {
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
panel.setToolTipText("A Panel container");
JButton button = new JButton("Even");
button.setBounds(100, 60, 100, 30);
button.setToolTipText("A button component");
JButton button2 = new JButton("Odd");
button2.setBounds(100, 60, 100, 30);
button2.setToolTipText("A button component");
//Add action listener to button
button.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System .out.println("You clicked the button");
int sum=0;
for(int i=1;i<=100;i++){
if(i%2==0){
System.out.println(i);
sum+=i;
}
}
System.out.println("Sum of even numbers: "+sum);
}
});
panel.add(button);
panel.add(button2);
setTitle("Tooltip");
setSize(500, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Example2 ex = new Example2();
ex.setVisible(true);
}
}
panel.setLayout(null);
That is where it starts to go wrong.
Use layouts. See Laying Out Components Within a Container & Effective Layout Management: Short Course for more details.
Use:
The appropriate layouts.
Possibly nested inside one another.
With appropriate layout padding and component border/insets for white space.
As an aside.
...
button.setBounds(100, 60, 100, 30);
button.setToolTipText("A button component");
JButton button2 = new JButton("Odd");
button2.setBounds(100, 60, 100, 30);
...
Did you notice how the bounds of the two buttons were identical? What do you think happens when you put two components of the same size in the same place?
You have to change panel.setLayout(null) to layout you need. For example:
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
or
panel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER));
Andrew Thompson +1 ,
Here are some usefull links :
A Visual Guide to Layout Managers
Using Layout Managers
Adding space between components

Reduce Spaces in a GridLayout Java Swing

Good day, please would like to know how to reduce the spaces between the labels and the Textboxes in this picture below and also how to create some spaces between the labels and the frame.Thank you.
My code for this:
private void initUI(JFrame parent) {
// private void initUI() {
myPanel = new JPanel(new GridLayout(3,2,1,1));
buttons_panel = new JPanel(new FlowLayout());
username_label = new JLabel("Username: ");
password_label = new JLabel("Password: ");
username = new JTextField(20);
password = new JPasswordField(20);
ok = new JButton("Ok");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
myPanel.add(username_label);
myPanel.add(username);
myPanel.add(password_label);
myPanel.add(password);
buttons_panel.add(ok);
buttons_panel.add(cancel);
getContentPane().add(myPanel, BorderLayout.CENTER);
getContentPane().add(buttons_panel, BorderLayout.PAGE_END);
pack();
setResizable(false);
setLocationRelativeTo(parent);
}
Should i be using GridBagLayout for this instead?..
All cells in GridLayout have equal size. You have to use GridBagLayout or SpringLayout or BoxLayout.
or use proper
1) Borders
2) set for Alignment (left - right, top - bottom) for
used LayoutManager, simple example for Boxlayout
text alignment (left - center - right)
You can also use the GridLayout hgap and hgap parameters and add a matching, empty Border, as shown here.

Categories

Resources