Java UIManager - Change ComponentsStyle - java

I want to change my componentstyle by using UIManager.
For example:
I click on a Button and the Button foreground changes from black to green. The same for a JCheckbox.....
In my example the changes just work for the Button.gradient.... I get no update for Button.foreground and no update for the JCheckbox!
Here my UIManagerClass:
package components;
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.SwingUtilities;
public class OwnUiManager {
ButtonDemo Bd;
OwnUiManager(ButtonDemo aThis) {
Bd = aThis;
}
public void setNormal() {
ArrayList<Object> gradients = new ArrayList();
gradients.add(0.3);
gradients.add(0.0);
gradients.add(new Color(221, 232, 243));
gradients.add(new Color(255, 255, 255));
gradients.add(new Color(184, 207, 229));
javax.swing.UIManager.put("RadioButton.background", Color.PINK);
javax.swing.UIManager.put("Button.gradient", gradients);
javax.swing.UIManager.put("Button.foreground", Color.PINK);
SwingUtilities.updateComponentTreeUI(Bd);
}
public void setNightVision() {
System.out.println("Tes");
ArrayList<Object> gradients = new ArrayList();
gradients.add(0.18f);
gradients.add(0.17f);
gradients.add(Color.BLACK);
gradients.add(Color.DARK_GRAY);
gradients.add(Color.DARK_GRAY);
javax.swing.UIManager.put("RadioButton.background", Color.GRAY);
javax.swing.UIManager.put("Button.gradient", gradients);
javax.swing.UIManager.put("Button.foreground", Color.red);
SwingUtilities.updateComponentTreeUI(Bd);
}
}
and here my Buttondemo/Main-Class:
package components;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class ButtonDemo extends JPanel
implements ActionListener {
protected JButton b1,b2;
private JRadioButton b3;
public ButtonDemo() {
b1 = new JButton("ON");
b1.addActionListener(this);
add(b1);
b2 = new JButton("OFF");
b2.addActionListener(this);
add(b2);
//For Testing the Style
b3=new JRadioButton("Test");
add(b3);
}
public void actionPerformed(ActionEvent e) {
OwnUiManager test = new OwnUiManager(this);
if (e.getSource().equals(b1)) {
test.setNormal();
} else {
test.setNightVision();
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("ButtonDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ButtonDemo newContentPane = new ButtonDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

JCheckBox / JRadioButton has Icon
have to change own Icon to concrete JCheckBox / JRadioButton or put then to the UIManager, then apply for whole JVM instance
for more infos have to check UIManager Defaults and Key Bindings by camickr
most of your potential issues is descibed in Creating a custom button in Java with JButton

Related

Java - how to zoom in/zoom out text in JTextArea

I am writing in a notepad. And I want to implement text scaling in my notepad. But I don't know how to do it. I'm trying to find it but everyone is suggesting to change the font size. But I need another solution.
I am create new project and add buttons and JTextArea.
package zoomtest;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class zoom {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
zoom window = new zoom();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public zoom() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
JButton ZoomIn = new JButton("Zoom in");
ZoomIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(ZoomIn);
JButton Zoomout = new JButton("Zoom out");
Zoomout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(Zoomout);
JTextArea jta = new JTextArea();
frame.getContentPane().add(jta, BorderLayout.CENTER);
}
}
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay close attention to the Laying Out Components Within a Container section.
I reworked your GUI. Here's how it looks when the application starts. I typed some text so you can see the font change.
Here's how it looks after we zoom out.
Here's how it looks after we zoom in.
Stack Overflow scales the images, so it's not as obvious that the text is zooming.
Explanation
Swing was designed to be used with layout managers. I created two JPanels, one for the JButtons and one for the JTextArea. I put the JTextArea in a JScrollPane so you could type more than 10 lines.
I keep track of the font size in an int field. This is a simple application model. Your Swing application should always have an application model made up of one or more plain Java getter/setter classes.
Code
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ZoomTextExample {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
new ZoomTextExample();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private int pointSize;
private Font textFont;
private JFrame frame;
private JTextArea jta;
private JTextField pointSizeField;
public ZoomTextExample() {
this.pointSize = 16;
this.textFont = new Font(Font.DIALOG, Font.PLAIN, pointSize);
initialize();
}
private void initialize() {
frame = new JFrame("Text Editor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createButtonPanel(), BorderLayout.NORTH);
frame.add(createTextAreaPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JButton zoomIn = new JButton("Zoom in");
zoomIn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(+2);
updatePanels();
}
});
panel.add(zoomIn);
panel.add(Box.createHorizontalStrut(20));
JLabel label = new JLabel("Current font size:");
panel.add(label);
pointSizeField = new JTextField(3);
pointSizeField.setEditable(false);
pointSizeField.setText(Integer.toString(pointSize));
panel.add(pointSizeField);
panel.add(Box.createHorizontalStrut(20));
JButton zoomOut = new JButton("Zoom out");
zoomOut.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(-2);
updatePanels();
}
});
panel.add(zoomOut);
return panel;
}
private JPanel createTextAreaPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
jta = new JTextArea(10, 40);
jta.setFont(textFont);
JScrollPane scrollPane = new JScrollPane(jta);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private void updatePanels() {
pointSizeField.setText(Integer.toString(pointSize));
textFont = textFont.deriveFont((float) pointSize);
jta.setFont(textFont);
frame.pack();
}
private void incrementPointSize(int increment) {
pointSize += increment;
}
}

Why can't I change the JButton (disabled) text color?

I started programming Java. This is my first window application. I did a simple tic-tac-toe game and I want the "o" button font color to be a different color. But it doesn't work. I can change the background color, but not the fonts, why?
package moje;
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.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.print.PrinterJob;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JTextField;
public class Kolko_i_krzyzyk extends JFrame implements ActionListener {
static JTextField tekst;
static JLayeredPane ekran = new JLayeredPane();
static JButton button = new JButton();
static int licznik=0;
public Kolko_i_krzyzyk () {
super("Kółko i krzyżyk");
ekran = new JLayeredPane();
setVisible(true);
setSize(800, 800);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
//Siatka podzielona 3 na 3
setLayout(new GridLayout(3,3));
//Tworzenie 9 przycisków
for(int i = 1; i<=9; i++) {
JButton button = new JButton();
add(button);
button.addActionListener(this);
}
}
public static void main(String[] args) {
JFrame okno = new Kolko_i_krzyzyk();
}
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if(licznik%2==0 ) {
button.setText("x");
button.setFont(new Font ("Arial", Font.BOLD, 90));
}
else {
button.setText("O");
button.setForeground(Color.RED);
button.setFont(new Font ("Arial", Font.BOLD, 90));
}
button.setEnabled(false);
licznik++;
}
}
The issue here is the default behavior when disabling the JButton via setEnabled(false).
This will grey out the button and ignore any color formatting you did to the text (foreground).
There are several workarounds to modify this behavior (as seen in this similar question).
Here is a short demonstration (without the final game logic of course) , which changes the UI of the JButton via setUI().
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.plaf.metal.MetalButtonUI;
public class Test {
private int counter = 0;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Test().buildGui());
}
private void buildGui() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
panel.setLayout(new GridLayout(3, 3));
for (int i = 1; i <= 9; i++) {
JButton button = new JButton() {
#Override
public Dimension getPreferredSize() {
return new Dimension(150, 150);
}
};
button.setFont(new Font("Arial", Font.BOLD, 90));
panel.add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (counter % 2 == 0) {
button.setText("X");
button.setUI(new MetalButtonUI() {
// override the disabled text color for the button UI
protected Color getDisabledTextColor() {
return Color.BLUE;
}
});
} else {
button.setText("O");
button.setUI(new MetalButtonUI() {
protected Color getDisabledTextColor() {
return Color.RED;
}
});
}
button.setEnabled(false);
counter++;
}
});
}
frame.pack();
frame.setVisible(true);
}
}
Result:
Another (simpler) way to do it would be to build some ImageIcons for "X" and "O", then set these on the buttons via setIcon()/setDisabledIcon(). This would save you the trouble from modifying the button UI.

Swing: GlassPane and the custom painted semitransparent Buttons

I have a short toolbar at the left side of my application. When user points this toolbar, I open a semitransparent full toolbar (I use GlassPane to do it). All except semitransparency works fine.
Here is the screenshot of my example program:
As you see the first button is painted correctly, but all another have completly transparent background.
Here is my code (SSCCE):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.plaf.basic.BasicButtonUI;
import javax.swing.plaf.metal.MetalLookAndFeel;
/**
* <code>FlyOutExample</code>.
*/
public class FlyOutExample implements Runnable {
private static final String[] BUTTONS = {"First button", "Second", "Another button", "Last Button", "End"};
private static final Color HT_BLUE = new Color(0, 0, 255, 160); // half transparent blue
private JPanel shortPanel = new JPanel(new GridLayout(5, 1));
private JPanel fullPanel = new JPanel(new GridLayout(5, 1));
private JPanel fullPanelWrapper = new JPanel(new BorderLayout());
private JPanel shortPanelWrapper = new JPanel(new BorderLayout());
private JFrame frm;
public static void main(String[] args) {
SwingUtilities.invokeLater(new FlyOutExample());
}
#Override
public void run() {
try {
UIManager.setLookAndFeel(MetalLookAndFeel.class.getName());
} catch (Exception e) {
e.printStackTrace();
}
for (String s : BUTTONS) {
JButton b = new JButton(s.substring(0, 1));
b.setBackground(Color.BLUE);
b.setForeground(Color.RED);
b.setUI(new BasicButtonUI());
shortPanel.add(b);
b = new JButton(s);
b.setForeground(Color.RED);
b.setOpaque(false);
b.setHorizontalAlignment(SwingConstants.LEADING);
b.setBackground(HT_BLUE);
b.setUI(new BasicButtonUI() {
#Override
public void update(Graphics g, JComponent c) {
Color old = g.getColor();
g.setColor(HT_BLUE);
g.fillRect(0, 0, c.getWidth(), c.getHeight());
g.setColor(old);
paint(g, c);
}
});
fullPanel.add(b);
}
frm = new JFrame("Flyout example");
shortPanelWrapper.setOpaque(false);
shortPanelWrapper.add(shortPanel, BorderLayout.NORTH);
JPanel bluePanel1 = new JPanel();
bluePanel1.setOpaque(true);
bluePanel1.setBackground(Color.BLUE);
shortPanelWrapper.add(bluePanel1);
fullPanel.setOpaque(false);
fullPanelWrapper.setOpaque(false);
fullPanelWrapper.add(fullPanel, BorderLayout.NORTH);
JPanel bluePanel2 = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
Color old = g.getColor();
g.setColor(HT_BLUE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(old);
}
};
bluePanel2.setOpaque(false);
fullPanelWrapper.add(bluePanel2);
MouseListener openListener = new OpenSideBarListener();
for (Component c : shortPanel.getComponents()) {
c.addMouseListener(openListener);
}
bluePanel1.addMouseListener(openListener);
MouseListener closeListener = new CloseSideBarListener();
for (Component c : fullPanel.getComponents()) {
c.addMouseListener(closeListener);
}
bluePanel2.addMouseListener(closeListener);
JPanel topPanel = new JPanel();
topPanel.setBackground(Color.GREEN);
topPanel.setPreferredSize(new Dimension(0, 30));
JPanel bottomPanel = new JPanel();
bottomPanel.setBackground(Color.GREEN);
bottomPanel.setPreferredSize(new Dimension(0, 30));
frm.add(topPanel, BorderLayout.NORTH);
frm.add(bottomPanel, BorderLayout.SOUTH);
frm.add(shortPanelWrapper, BorderLayout.WEST);
frm.add(new JScrollPane(new JTable(40, 7)));
frm.pack();
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
private void openPopup() {
if (shortPanelWrapper.getMousePosition() != null) {
Container glassPane = (Container) frm.getGlassPane();
glassPane.setLayout(null);
fullPanelWrapper.setLocation(shortPanelWrapper.getLocation());
fullPanelWrapper.setSize(140, shortPanelWrapper.getHeight());
glassPane.add(fullPanelWrapper);
glassPane.setVisible(true);
}
}
private void closePopup() {
if (fullPanelWrapper.getMousePosition() == null) {
Container glassPane = (Container) frm.getGlassPane();
glassPane.removeAll();
glassPane.setVisible(false);
}
}
private class OpenSideBarListener extends MouseAdapter {
#Override
public void mouseEntered(MouseEvent e) {
openPopup();
}
}
private class CloseSideBarListener extends MouseAdapter {
#Override
public void mouseExited(MouseEvent e) {
closePopup();
}
}
}
My JDK is: 1.8_91, OS: Windows 7
My question is: what should I do to paint all my buttons correct?
P.S. In real application I have a custom UI for all buttons present in the left toolbar, so please don't remove the UI for my buttons.
UPDATE
I've started the app again (without any changes) and got another bug
Here ist the new picture:
Probably it's a bug of my graphic card?

Change JLabel colour repeatedly each time when JButton pressed

I'm trying to make a traffic light program, changing the foreground colour of JLabel from red to yellow to green, everytime I press JButton (i.e once i press JButton, JLabel turns red, then when i again press JButton it turns yellow and so on). But somehow the colour changes only once to red & nothing happens on further pressing JButton. Any kind of help would be appreciated. Thanks.
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class traffic {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
traffic window = new traffic();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public traffic() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 798, 512);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblTrafficLight = new JLabel("Traffic Light");
lblTrafficLight.setFont(new Font("Tahoma", Font.BOLD, 40));
lblTrafficLight.setHorizontalAlignment(SwingConstants.CENTER);
lblTrafficLight.setBounds(190, 11, 403, 61);
frame.getContentPane().add(lblTrafficLight);
JLabel lblRed = new JLabel("RED");
lblRed.setHorizontalAlignment(SwingConstants.CENTER);
lblRed.setFont(new Font("Tahoma", Font.PLAIN, 40));
lblRed.setBounds(273, 125, 249, 61);
frame.getContentPane().add(lblRed);
JButton btnButton = new JButton("Button");
btnButton.setActionCommand("B");
btnButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.RED);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.YELLOW);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.GREEN);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.YELLOW);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.RED);
}
}
});
btnButton.setBounds(353, 346, 89, 23);
frame.getContentPane().add(btnButton);
}
}
You're using the same actionCommand, B for each if block, and so all of the blocks will always run, and the last block will be the one seen.
e.g.,
int x = 1;
if (x == 1) {
// do something
}
if (x == 1) {
// do something else
}
all blocks will be done!
Either change the actionCommands used, or don't use actionCommand String but rather an incrementing int index. Also, don't use MouseListeners for JButtons but rather ActionListeners.
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
public class Traffic2 extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = 300;
private static final String[] STRINGS = {"Red", "Blue", "Orange", "Yellow", "Green", "Cyan"};
private Map<String, Color> stringColorMap = new HashMap<>();
private JLabel label = new JLabel("", SwingConstants.CENTER);
private int index = 0;
public Traffic2() {
stringColorMap.put("Red", Color.red);
stringColorMap.put("Blue", Color.blue);
stringColorMap.put("Orange", Color.orange);
stringColorMap.put("Yellow", Color.YELLOW);
stringColorMap.put("Green", Color.GREEN);
stringColorMap.put("Cyan", Color.CYAN);
label.setFont(label.getFont().deriveFont(Font.BOLD, 40f));
String key = STRINGS[index];
label.setText(key);
label.setForeground(stringColorMap.get(key));
JPanel centerPanel = new JPanel(new GridBagLayout());
centerPanel.add(label);
JPanel topPanel = new JPanel();
topPanel.add(new JButton(new AbstractAction("Change Color") {
#Override
public void actionPerformed(ActionEvent e) {
index++;
index %= STRINGS.length;
String key = STRINGS[index];
label.setText(key);
label.setForeground(stringColorMap.get(key));
}
}));
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(centerPanel, BorderLayout.CENTER);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
Traffic2 mainPanel = new Traffic2();
JFrame frame = new JFrame("Traffic2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Adding a jTextArea to JPanel from within the Panel

So, I am creating a new Canvas (JPanel) class: Canvas canvas = new Canvas(); and then I am calling a method on that class: canvas.addTextBox();
Now, from within this Canvas class, I want to add a new jTextArea to the Canvas. I tried using the code below but it isn't showing up. Not sure what I am doing wrong. Thanks!
class Canvas extends JPanel {
public Canvas() {
this.setOpaque(true);
//this.setBackground(Color.WHITE);
}
public void addTextBox() {
final JTextArea commentTextArea = new JTextArea(10, 10);
commentTextArea.setLineWrap(true);
commentTextArea.setLineWrap(true);
commentTextArea.setWrapStyleWord(true);
commentTextArea.setVisible(true);
}
}
Full Code
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class UMLEditor {
public static void main(String[] args) {
JFrame frame = new UMLWindow();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(30, 30, 1000, 700);
frame.getContentPane().setBackground(Color.white);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class UMLWindow extends JFrame {
Canvas canvas = new Canvas();
private static final long serialVersionUID = 1L;
public UMLWindow() {
addMenus();
}
public void addMenus() {
getContentPane().add(canvas);
JMenuBar menubar = new JMenuBar();
JMenuItem newTextBox = new JMenuItem("New Text Box");
newTextBox.setMnemonic(KeyEvent.VK_E);
newTextBox.setToolTipText("Exit application");
newTextBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
canvas.addTextBox();
}
});
menubar.add(newTextBox);
setJMenuBar(menubar);
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
class Canvas extends JPanel {
public Canvas() {
this.setOpaque(true);
//this.setBackground(Color.WHITE);
}
public void addTextBox() {
final JTextArea commentTextArea = new JTextArea(10, 10);
commentTextArea.setLineWrap(true);
commentTextArea.setLineWrap(true);
commentTextArea.setWrapStyleWord(true);
commentTextArea.setVisible(true);
}
}
The addTextBox method only creates a JTextArea. It never adds it to the JPanel
You will need to add the following line to addTextBox method:
add( commentTextArea );
In case the JFrame which contains your components is already visible on screen when the addTextBox method is called, you need to invalidate the container as well. Simply add
revalidate();
repaint();

Categories

Resources