Problems with Changing JTextArea font size - java

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);

Related

Button click creates new JTable everytime instead of refreshing with new value

I'd like to create a JTable that displays the values from a created object by clicking a button.
The object is created here:
public class Getraenkeverwaltung extends Firma {
public static Getraenk getraenk1 = new Getraenk(1, "Pepsi Maxx Original", 0.99, 500);
...
}
Now with the following code I'm creating the window with all the panels.
public void buildUi() {
// Create the main window
Frame fr = new Frame();
fr.setLayout(new BorderLayout());
// Define colors
Color headerColor = new Color(38, 70, 83);
Color contentColor = new Color(42, 157, 143);
// create navigation pane at the top
JPanel navigation = new JPanel();
navigation.setBackground(headerColor);
navigation.setLayout(new GridLayout(1,4));
navigation.setPreferredSize(new Dimension(800,50));
// create content pane in the middle
JPanel content = new JPanel();
content.setBackground(contentColor);
content.setPreferredSize(new Dimension(800, 500));
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
// create footer pane at the bottom
JPanel footer = new JPanel();
footer.setBackground(headerColor);
footer.setLayout(new GridLayout(1,1));
footer.setPreferredSize(new Dimension(800, 50));
footer.setLayout(new BorderLayout());
// show impressum in the footer pane
JLabel impressum = new JLabel(Firma.impressum());
impressum.setHorizontalAlignment(SwingConstants.CENTER); // Platziert den Text mittig
impressum.setForeground(Color.white);
// create the buttons
Button btnBestand = new Button("Bestand anzeigen");
Button btnVerkauf = new Button("Verkaufen");
Button btnErhoehen = new Button("Bestand erhoehen");
Button btnExit = new Button("Exit");
// display beverages on button click
btnBestand.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String column [] = {"Artikelnummer", "Artikel", "Bestand"};
Object data [][] = {
{getraenk1.getId(), getraenk1.getName(), getraenk1.getBestand()},
{getraenk2.getId(), getraenk2.getName(), getraenk2.getBestand()},
{getraenk3.getId(), getraenk3.getName(), getraenk3.getBestand()}
};
JTable table = new JTable(data, column);
JScrollPane sp = new JScrollPane(table);
content.remove(sp);
content.revalidate();
content.repaint();
content.add(sp);
}
});
// open new sale window
btnVerkauf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Verkaufen();
}
});
// close the program
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// add the buttons to the navigation pane
navigation.add(btnBestand);
navigation.add(btnVerkauf);
navigation.add(btnErhoehen);
navigation.add(btnExit);
// add the impressum to the footer pane
footer.add(impressum, BorderLayout.CENTER);
// add the three main panels to the window
fr.add(navigation, BorderLayout.NORTH);
fr.add(content, BorderLayout.CENTER);
fr.add(footer, BorderLayout.SOUTH);
fr.pack();
}
One of the problems is the button functionality of btnBestand. Whenever I'm changing the value of some of my products, it should refresh the JTable.
Unfortunately, there's a new JTable displayed everytime I click on the button,
so it looks like this after hitting the button four times.
I'd like to just display the table with the new value after clicking on the button again.
Thanks in advance.
// edit:
Removed the content.remove(sp); pointed out by Gjermund Dahl, as it is unnecessary in this context. Thank you.
Problem still persists

How can I color this frame/border of my JTextArea?

I wanted to make a TextEditor and tried to change some colors. But I still have difficulties changing the color of the JFrame of the JTextArea (I mean this white border) and also don't know how I can make this text area so that it always changes the size to the selected JFrame size.
TextEditorPicture
TextEditorPicture2
public class TextEditor extends JFrame implements ActionListener {
JTextArea textArea;
JScrollPane scrollPane;
JLabel fontLabel;
JSpinner fontSizeSpinner;
JButton fontColorButton;
JComboBox fontBox;
JMenuBar menuBar;
JMenu fileMenu;
JMenuItem openItem;
JMenuItem saveItem;
JMenuItem exitItem;
TextEditor(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("TextEditor");
this.setSize(500,500);
this.setMinimumSize(new Dimension(500,0));
this.setMaximumSize(new Dimension(500, Integer.MAX_VALUE));
this.setVisible(true);
this.setLayout(new FlowLayout());
this.setLocationRelativeTo(null);
this.getContentPane().setBackground(Color.decode("#252025"));
//Text Area
textArea = new JTextArea();
textArea.setVisible(true);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setFont(new Font("SF Mono Regular 11", Font.PLAIN,20));
textArea.setBackground(Color.decode("#252025"));
textArea.setForeground(Color.decode("#eaeaea"));
//Scroll Panel Sidebar
scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new Dimension(500,500));
scrollPane.setMinimumSize(new Dimension(500,0));
scrollPane.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
scrollPane.setVisible(true);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
//Font Text
fontLabel = new JLabel("Font: ");
fontLabel.setForeground(Color.decode("#eaeaea"));
//Font Size Spinner
fontSizeSpinner = new JSpinner();
fontSizeSpinner.setPreferredSize(new Dimension(50,25));
fontSizeSpinner.setValue(20);
fontSizeSpinner.getEditor().getComponent(0).setBackground(Color.decode("#252025"));
fontSizeSpinner.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
textArea.setFont(new Font("SF Mono Regular 11",Font.PLAIN,(int) fontSizeSpinner.getValue()));
textArea.setSelectedTextColor(Color.white);
}
});
fontColorButton = new JButton("Color");
fontColorButton.setBackground(Color.decode("#252025"));
fontColorButton.setOpaque(true);
fontColorButton.setBorderPainted(false);
fontColorButton.addActionListener(this);
fontColorButton.setForeground(Color.decode("#eaeaea"));
String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
//Font Change Box
fontBox = new JComboBox(fonts);
fontBox.addActionListener(this);
fontBox.setBackground(Color.decode("#252025"));
fontBox.setForeground(Color.green);
fontBox.setOpaque(true);
fontBox.setEditable(true);
fontBox.getEditor().getEditorComponent().setBackground(Color.decode("#252025"));
((JTextField) fontBox.getEditor().getEditorComponent()).setBackground(Color.decode("#252025"));
fontBox.setSelectedItem("SF Mono Regular 11");
//Menubar
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
openItem = new JMenuItem("Open");
saveItem = new JMenuItem("Save");
exitItem = new JMenuItem("Exit");
openItem.addActionListener(this);
saveItem.addActionListener(this);
exitItem.addActionListener(this);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(exitItem);
menuBar.add(fileMenu);
this.setJMenuBar(menuBar);
this.add(fontLabel);
this.add(fontSizeSpinner);
this.add(fontColorButton);
this.add(fontBox);
this.add(scrollPane);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == fontColorButton) {
JColorChooser colorChooser = new JColorChooser();
Color color = colorChooser.showDialog(null, "Color", Color.white);
}
if(e.getSource()==fontBox) {
textArea.setFont(new Font((String)fontBox.getSelectedItem(),Font.PLAIN,textArea.getFont().getSize()));
}
//Open
if(e.getSource()==openItem) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File("."));
FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
fileChooser.setFileFilter(filter);
int response = fileChooser.showOpenDialog(null);
if(response==JFileChooser.APPROVE_OPTION) {
File file = new File(fileChooser.getSelectedFile().getAbsolutePath());
Scanner fileIn = null;
try {
fileIn = new Scanner(file);
if(file.isFile()) {
while(fileIn.hasNextLine()) {
String line = fileIn.nextLine()+"\n";
textArea.append(line);
}
}
} catch (FileNotFoundException e1){
e1.printStackTrace();
} finally {
fileIn.close();
}
}
}
//Save
if(e.getSource()==saveItem) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File("."));
int response = fileChooser.showSaveDialog(null);
if(response==JFileChooser.APPROVE_OPTION) {
File file;
PrintWriter fileOut = null;
file = new File(fileChooser.getSelectedFile().getAbsolutePath());
try {
fileOut = new PrintWriter(file);
fileOut.println(textArea.getText());
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
fileOut.close();
}
}
}
//Exit
if(e.getSource()==exitItem) {
System.exit(0);
}
}
}
You need to use multiple layouts. FlowLayout alone is not sufficient.
The center component of a BorderLayout will always stretch to fill the container’s space.
Remember that you can put panels inside panels. Put your font and color labels/fields in a JPanel that uses a FlowLayout, then put that JPanel in the NORTH area of a JPanel that uses a BorderLayout. Your JScrollPane belongs in the center of that same BorderLayout.
Remove all calls to setPreferredSize, setMinimumSize, and setMaximumSize. They are intefering with a layout manager’s ability to properly arrange things. All components have a useful preferred size when they are created.
To set the size of your JScrollPane, use the setRows and setColumns methods of JTextArea. The JScrollPane parent will consult its Scrollable view (that is, the JTextArea) to determine its preferred size.

JProgressBar in JTextPane

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.

Java Swing OSX Window Menu Icon Alignment

Java Swing seems to place the 'Menu Text' after the icon (if present) on MenuItems. See example below.
It does NOT look very nice.
Is there a way around this?
On OSX the icon fits in the left margin and the text aligns with all other MenuItems.
Do you mean something like this :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextPaneExample
{
private Icon info = UIManager.getIcon("OptionPane.informationIcon");
private Icon error = UIManager.getIcon("OptionPane.errorIcon");
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("JTextPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextPane tpane = new JTextPane();
tpane.setContentType("text/html");
JScrollPane scroller = new JScrollPane();
scroller.setViewportView(tpane);
try
{
java.net.URL url = new java.net.URL("http://maps.google.es/");
//tpane.setPage(url);
}
catch (Exception e)
{
e.printStackTrace();
}
frame.setJMenuBar(createMenuBar());
frame.getContentPane().add(scroller);
frame.setSize(300, 300);
frame.setVisible(true);
}
private JMenuBar createMenuBar()
{
JMenuBar menuBar = new JMenuBar();
JMenu windowMenu = new JMenu("Window");
JMenuItem minimizeItem = new JMenuItem("Minimize");
minimizeItem.setMargin(new java.awt.Insets(0, 10, 0, 0));
minimizeItem.setIcon(info);
minimizeItem.setIconTextGap(1);
minimizeItem.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
JMenuItem zoomItem = new JMenuItem("Zoom");
zoomItem.setMargin(new java.awt.Insets(0, 10, 0, 0));
zoomItem.setIconTextGap(1);
zoomItem.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem("Check Me", null, true);
cbmi.setMargin(new java.awt.Insets(5, 25, 5, 5));
cbmi.setIconTextGap(17);
cbmi.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
windowMenu.add(minimizeItem);
windowMenu.add(zoomItem);
windowMenu.add(cbmi);
menuBar.add(windowMenu);
return menuBar;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new JTextPaneExample().createAndDisplayGUI();
}
});
}
}
Here is the Output :
You could try either of these approaches:
Unicode characters are appealing, but they offer poor alignment in a variable pitch font:
JMenuBar menuBar = new JMenuBar();
JMenu windowMenu = new JMenu("Window");
windowMenu.add(new JMenuItem("♦ Item"));
windowMenu.add(new JMenuItem("✓ Item"));
windowMenu.add(new JMenuItem("• Item"));
menuBar.add(windowMenu);
frame.setJMenuBar(menuBar);
Better, implement the Icon interface, illustrated here and here, using a fixed-size implementation to control geometry. CellTest shows one approach to rendering an arbitrary unicode glyph.

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