How to Apply the background gradient of a JFrame - java

I want to apply gradient in JFrame.
I try my best but some problem I faced.
Please help me.
In following code.
I want to set pnlMain as BorderLayout but I used gradient paint so that BorderLayout is not set properly.
And also graphics2d.fillRect(0, 0, width, height) not fill whole pnlMain JPanel.
So please give some suggestion for it.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Point;
import javax.swing.Box;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class Frame extends javax.swing.JFrame {
// Getter & Setter
public Frame() {
setExtendedState(Frame.MAXIMIZED_BOTH);
setTitle("Gradient");
initComponents();
}
private void initComponents() {
menu_bar = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
pnlMain = new JPanel();
pnlSuper = new JPanel(new BorderLayout(15,15))
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Point point1 = new Point(10, 10);
Point point2 = new Point(
getWidth() - 10,
getHeight() - 10);
final GradientPaint gp = new GradientPaint(
point1, Color.YELLOW,
point2, new Color(255, 225, 100),
true);
final Graphics2D g2 = (Graphics2D) g;
g2.setPaint(gp);
g.fillRect(0, 0, getWidth(), getHeight());
}
};
pnlSuper.setBorder(new EmptyBorder(30,30,30,30));
pnlMain.setLayout(new BorderLayout());
pnlMain.setOpaque(false);
pnlImage = new JPanel(new BorderLayout());
pnlFooter = new JPanel(new GridLayout(1,2));
footerBox = Box.createVerticalBox();
lblBackground = new JLabel("Image");
lblBackground.setFont(new java.awt.Font("URW Bookman L", 0, 20));
lblAddress = new JLabel();
lblContactNumber = new JLabel();
lblBackground.setHorizontalAlignment(SwingConstants.CENTER);
lblAddress.setText("Address");
lblAddress.setAlignmentX(JLabel.CENTER_ALIGNMENT);
lblAddress.setFont(new java.awt.Font("URW Bookman L", 0, 20)); // NOI18N
footerBox.add(lblAddress);
lblContactNumber.setText("Contact Number ");
lblContactNumber.setFont(new java.awt.Font("URW Bookman L", 0, 20)); // NOI18N
lblContactNumber.setAlignmentX(JLabel.CENTER_ALIGNMENT);
footerBox.add(lblContactNumber);
pnlFooter.add(footerBox);
pnlImage.add(lblBackground);
pnlMain.add(pnlImage, BorderLayout.CENTER);
pnlMain.add(pnlFooter, BorderLayout.SOUTH);
pnlSuper.add(pnlMain);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
jMenu1.setFont(new java.awt.Font("URW Bookman L", 0, 18));
jMenu1.setPreferredSize(new java.awt.Dimension(45, 25));
menu_bar.add(jMenu1);
setJMenuBar(menu_bar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addGap(0, 1352, Short.MAX_VALUE).addComponent(pnlSuper));
layout.setVerticalGroup(layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGap(0, 757, Short.MAX_VALUE).addComponent(pnlSuper));
pack();
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Index.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Index.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Index.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Index.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Frame().setVisible(true);
}
});
}
private javax.swing.JMenu jMenu1;
private javax.swing.JToggleButton jToggleButton1;
private javax.swing.JMenuBar menu_bar;
private JLabel lblBackground;
private JPanel pnlMain;
private JPanel pnlFooter;
private JPanel pnlImage;
private JLabel lblAddress;
private JLabel lblContactNumber;
private Box footerBox;
private JPanel pnlSuper;
}
Thanq For Reading

In order to see the BG, all the components on top of it must be transparent. So this:
pnlImage = new JPanel(new BorderLayout());
pnlFooter = new JPanel(new GridLayout(1,2));
Should be:
pnlImage = new JPanel(new BorderLayout());
pnlImage.setOpaque(false);
pnlFooter = new JPanel(new GridLayout(1,2));
pnlFooter.setOpaque(false);

Related

Resize JLabel to fit resized main JPanel

I have two child panels and one parent panel (background). My goal is to resize JLabel icon in firstPanel, when main panel is resized. I tried to use StretchIcon, but it works only when adding JLabel icon to main.
My code now:
import darrylbu.icon.StretchIcon;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
public class Task {
JFrame frame;
JPanel main;
public static void main(String args[]) {
new Task();
}
public Task() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(600, 400));
main = mainPanel();
frame.add(main);
main.add(firstPanel());
main.add(secondPanel());
frame.pack();
frame.setVisible(true);
}
private JPanel mainPanel(){
JPanel main_panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage background = null;
try {
background = ImageIO.read(new URL("https://jpegshare.net/images/17/b0/17b0bad019ea5e37c84a5147a33b0ce7.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
g.drawImage(background, 0, 0, this.getWidth(), this.getHeight(), this);
}
};
main_panel.setLayout(new OverlayLayout(main_panel));
main_panel.setLayout(new GridLayout(1, 2));
return main_panel;
}
private JPanel firstPanel() {
JPanel first_panel = new JPanel();
first_panel.setOpaque(false);
BufferedImage image = null;
try {
image = ImageIO.read(new URL("https://jpegshare.net/images/7a/f3/7af3bfc51cb1170be9f5655d643147d7.png"));
} catch (IOException e) {
e.printStackTrace();
}
StretchIcon img = new StretchIcon(image);
JLabel icon = new JLabel(img);
first_panel.add(icon);
first_panel.setLayout(getLayout());
return first_panel;
}
private JPanel secondPanel(){
JPanel second_panel = new JPanel() {
#Override
public Dimension getMaximumSize() {
return new Dimension(300, 400);
}
#Override
public void paintComponent(Graphics g) {
BufferedImage image = null;
try {
image = ImageIO.read(new URL("https://jpegshare.net/images/17/bc/17bc21f519133ca31f857a65c897925a.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
g.drawImage(image, 0, 0,
getWidth() / 2, getHeight() / 2, this);
}
};
second_panel.setLayout(new BoxLayout(second_panel, BoxLayout.Y_AXIS));
String [] resources = {"flowers", "nyanko", "tutturu~"};
for(String s : resources){
JLabel label = new JLabel(0 + " " + s);
label.setFont(new Font("Serif", Font.BOLD, 18));
second_panel.add(label);
}
return second_panel;
}
private GridBagLayout getLayout() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 1.0, 1.0};
gridBagLayout.columnWidths = new int[]{0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, 1.0, 1.0};
return gridBagLayout;
}
}
You can solve this with one resize listener attached to main panel. I assume that you want to resize JLabel exactly how much you resized your main panel. Here is how you can achieve that:
private Dimension main_size = null; //Inital Dimension of main JPanel
main.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
//This method is called everytime main panel is resized
if((main_size==null) ||
(main_size.width==0 && main_size.height==0)) {
main_size=main.getSize();
}
updateJLabelSize(icon,e.getComponent().getSize());
}
});
//Method for updating JLabel size
private void updateJLabelSize(JLabel icon,Dimension newSize) {
int heightDifference = newSize.height - main_size.height;
int widthDifference = newSize.width - main_size.width;
icon.setSize(new Dimension(icon.getWidth() + widthDifference,
icon.getHeight()+heightDifference));
main_size = newSize;
}

Graphics artifacts appear here in JPanel [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
In my custom JPanel appears graphic artifacts. I dont know why, because I have used super.paintComponent() in all of my custom paintings.
Here is how it looks on create.
2. And here is how it looks when I click on upgrades button.
And here is the code.
Menu
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FontFormatException;
import java.awt.Graphics;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import java.awt.GridBagLayout;
import javax.swing.JPanel;
import java.awt.GridBagConstraints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Menu {
static JFrame frame;
public static double scale = 1.5;
private static int WIDTH = 300, HEIGHT = 400;
public static Font fontTerminal;
private JPanel menuPanel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #throws IOException
*/
public Menu() throws IOException {
initialize();
}
/**
* Initialize the contents of the frame.
* #throws IOException
*/
private void initialize() throws IOException {
fontTerminal = new Font("Consolas", 1, 1);
try {
fontTerminal = Font.createFont(Font.TRUETYPE_FONT, new File("res/terminal.ttf"));
} catch (FontFormatException e1) {
e1.printStackTrace();
}
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{1.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
menuPanel = new BackgroundPanel();
menuPanel.setLayout(null);
GridBagConstraints gbc_menuPanel = new GridBagConstraints();
gbc_menuPanel.fill = GridBagConstraints.BOTH;
gbc_menuPanel.gridx = 0;
gbc_menuPanel.gridy = 0;
frame.getContentPane().add(menuPanel, gbc_menuPanel);
GameButton newgameButton = new GameButton();
int ngButtWidth = 194, ngButtHeight = 71;
newgameButton.setBounds((frame.getWidth()/2) - (ngButtWidth/2), (frame.getHeight()/2) - (ngButtHeight/2), ngButtWidth, ngButtHeight);
newgameButton.setBackground( new Color(0,0,0,0));
menuPanel.add(newgameButton);
newgameButton.setLayout(new BorderLayout(0, 0));
JLabel newgameLbl = new GLabel("New Game", newgameButton, SwingConstants.CENTER);
newgameLbl.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
GameWindow gp = new GameWindow();
frame.setVisible(false);
}
});
newgameLbl.setFont(fontTerminal.deriveFont(19f));
newgameLbl.setForeground(new Color(0,0,0));
newgameButton.add(newgameLbl, BorderLayout.CENTER);
GameButton creditsButton = new GameButton();
creditsButton.setBackground(new Color(0, 0, 0, 0));
creditsButton.setBounds(56, 262, 194, 71);
menuPanel.add(creditsButton);
creditsButton.setLayout(new BorderLayout(0, 0));
JLabel creditsLabel = new GLabel("Credits", creditsButton, SwingConstants.CENTER);
creditsLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
Credits credits = new Credits();
credits.setVisible(true);
}
});
creditsLabel.setForeground(Color.BLACK);
creditsLabel.setFont(null);
creditsLabel.setBackground(new Color(0, 0, 0, 0));
creditsLabel.setFont(fontTerminal.deriveFont(19f));
creditsButton.add(creditsLabel);
}
}
GameWindow
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.UIManager.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.JPanel;
import java.awt.Insets;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.GridLayout;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTabbedPane;
import net.miginfocom.swing.MigLayout;
import java.awt.FlowLayout;
import javax.swing.JTable;
public class GameWindow {
private JFrame frame;
private Font fontTerminal;
private JPanel workerPanel1;
private GProgressbar Bar1;
private GameButton upgradeWorker1;
private JLabel upgradeWorker1_1;
private JPanel workerPanel2;
private GProgressbar Bar2;
private GameButton upgradeWorker2;
private JPanel workerPanel3;
private GProgressbar Bar3;
private GameButton upgradeWorker3;
private JPanel workerPanel4;
private GProgressbar Bar4;
private GameButton upgradeWorker4;
private JPanel upgradesPanel;
private JLabel upgradeWorker2_1;
private JLabel upgradeWorker3_1;
private JLabel upgradeWorker4_1;
private JPanel specialPanel;
private JPanel upgradesButton;
private JTable table, table2;
/**
* Create the application.
*/
public GameWindow() {
initialize();
this.frame.setVisible(true);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
fontTerminal = Menu.fontTerminal;
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, 306, 430);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{1.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
frame.addWindowListener( new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
frame.setVisible(false);
frame.dispose();
Menu.frame.setVisible(true);
}});
GamePanel gamePanel = new GamePanel();
gamePanel.setLayout(null);
GridBagConstraints gbc_menuPanel = new GridBagConstraints();
gbc_menuPanel.fill = GridBagConstraints.BOTH;
gbc_menuPanel.gridx = 0;
gbc_menuPanel.gridy = 0;
frame.getContentPane().add(gamePanel, gbc_menuPanel);
upgradesPanel = new JPanel();
upgradesPanel.setBounds(23, 221, 253, 174);
upgradesPanel.setBackground(new Color(0,0,0,0));
gamePanel.add(upgradesPanel);
workerPanel1 = new JPanel();
workerPanel1.setBackground(new Color(0,0,0,0));
GridBagLayout gbl_workerPanel1 = new GridBagLayout();
gbl_workerPanel1.columnWidths = new int[]{119, 118, 0};
gbl_workerPanel1.rowHeights = new int[]{36, 0};
gbl_workerPanel1.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gbl_workerPanel1.rowWeights = new double[]{0.0, Double.MIN_VALUE};
workerPanel1.setLayout(gbl_workerPanel1);
Bar1 = new GProgressbar();
Bar1.setStringPainted(true);
GridBagConstraints gbc_Bar1 = new GridBagConstraints();
gbc_Bar1.fill = GridBagConstraints.BOTH;
gbc_Bar1.insets = new Insets(0, 0, 0, 5);
gbc_Bar1.gridx = 0;
gbc_Bar1.gridy = 0;
workerPanel1.add(Bar1, gbc_Bar1);
upgradeWorker1 = new GameButton();
GridBagConstraints gbc_upgradeWorker1 = new GridBagConstraints();
gbc_upgradeWorker1.fill = GridBagConstraints.BOTH;
gbc_upgradeWorker1.gridx = 1;
gbc_upgradeWorker1.gridy = 0;
workerPanel1.add(upgradeWorker1, gbc_upgradeWorker1);
upgradeWorker1_1 = new GLabel("Upgrade", upgradeWorker1, SwingConstants.CENTER);
upgradeWorker1_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
//upgrade worker 1
}
});
upgradeWorker1.setLayout(new BorderLayout(0, 0));
upgradeWorker1_1.setForeground(new Color(0,0,0));
upgradeWorker1.add(upgradeWorker1_1);
workerPanel2 = new JPanel();
workerPanel2.setBackground(new Color(0, 0, 0, 0));
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{119, 118, 0};
gbl_panel.rowHeights = new int[]{36, 0};
gbl_panel.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
workerPanel2.setLayout(gbl_panel);
Bar2 = new GProgressbar();
Bar2.setStringPainted(true);
GridBagConstraints gbc_Bar2 = new GridBagConstraints();
gbc_Bar2.fill = GridBagConstraints.BOTH;
gbc_Bar2.insets = new Insets(0, 0, 0, 5);
gbc_Bar2.gridx = 0;
gbc_Bar2.gridy = 0;
workerPanel2.add(Bar2, gbc_Bar2);
upgradeWorker2 = new GameButton();
GridBagConstraints gbc_upgradeWorker2 = new GridBagConstraints();
gbc_upgradeWorker2.fill = GridBagConstraints.BOTH;
gbc_upgradeWorker2.gridx = 1;
gbc_upgradeWorker2.gridy = 0;
workerPanel2.add(upgradeWorker2, gbc_upgradeWorker2);
upgradeWorker2.setLayout(new BorderLayout(0, 0));
upgradeWorker2_1 = new GLabel("Upgrade", upgradeWorker2, SwingConstants.CENTER);
upgradeWorker2_1.setForeground(Color.BLACK);
upgradeWorker2_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
//upgrade worker 2
}
});
upgradeWorker2.setLayout(new BorderLayout(0, 0));
upgradeWorker2_1.setFont(fontTerminal.deriveFont(15f));
upgradeWorker2.add(upgradeWorker2_1);
workerPanel3 = new JPanel();
workerPanel3.setBackground(new Color(0, 0, 0, 0));
GridBagLayout gbl_workerPanel3 = new GridBagLayout();
gbl_workerPanel3.columnWidths = new int[]{119, 118, 0};
gbl_workerPanel3.rowHeights = new int[]{36, 0};
gbl_workerPanel3.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gbl_workerPanel3.rowWeights = new double[]{0.0, Double.MIN_VALUE};
workerPanel3.setLayout(gbl_workerPanel3);
Bar3 = new GProgressbar();
Bar3.setStringPainted(true);
GridBagConstraints gbc_Bar3 = new GridBagConstraints();
gbc_Bar3.fill = GridBagConstraints.BOTH;
gbc_Bar3.insets = new Insets(0, 0, 0, 5);
gbc_Bar3.gridx = 0;
gbc_Bar3.gridy = 0;
workerPanel3.add(Bar3, gbc_Bar3);
upgradeWorker3 = new GameButton();
GridBagConstraints gbc_upgradeWorker3 = new GridBagConstraints();
gbc_upgradeWorker3.fill = GridBagConstraints.BOTH;
gbc_upgradeWorker3.gridx = 1;
gbc_upgradeWorker3.gridy = 0;
workerPanel3.add(upgradeWorker3, gbc_upgradeWorker3);
upgradeWorker3.setLayout(new BorderLayout(0, 0));
upgradeWorker3_1 = new GLabel("Upgrade", upgradeWorker3, SwingConstants.CENTER);
upgradeWorker3.add(upgradeWorker3_1);
workerPanel4 = new JPanel();
workerPanel4.setBackground(new Color(0, 0, 0, 0));
GridBagLayout gbl_workerPanel4 = new GridBagLayout();
gbl_workerPanel4.columnWidths = new int[]{119, 118, 0};
gbl_workerPanel4.rowHeights = new int[]{36, 0};
gbl_workerPanel4.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gbl_workerPanel4.rowWeights = new double[]{0.0, Double.MIN_VALUE};
workerPanel4.setLayout(gbl_workerPanel4);
Bar4 = new GProgressbar();
Bar4.setStringPainted(true);
GridBagConstraints gbc_Bar4 = new GridBagConstraints();
gbc_Bar4.fill = GridBagConstraints.BOTH;
gbc_Bar4.insets = new Insets(0, 0, 0, 5);
gbc_Bar4.gridx = 0;
gbc_Bar4.gridy = 0;
workerPanel4.add(Bar4, gbc_Bar4);
upgradeWorker4 = new GameButton();
GridBagConstraints gbc_upgradeWorker4 = new GridBagConstraints();
gbc_upgradeWorker4.fill = GridBagConstraints.BOTH;
gbc_upgradeWorker4.gridx = 1;
gbc_upgradeWorker4.gridy = 0;
workerPanel4.add(upgradeWorker4, gbc_upgradeWorker4);
upgradeWorker4.setLayout(new BorderLayout(0, 0));
upgradeWorker4_1 = new GLabel("Upgrade", upgradeWorker4, SwingConstants.CENTER);
upgradeWorker4.add(upgradeWorker4_1);
GroupLayout gl_upgradesPanel = new GroupLayout(upgradesPanel);
gl_upgradesPanel.setHorizontalGroup(
gl_upgradesPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_upgradesPanel.createSequentialGroup()
.addContainerGap()
.addGroup(gl_upgradesPanel.createParallelGroup(Alignment.LEADING)
.addComponent(workerPanel1, GroupLayout.PREFERRED_SIZE, 238, GroupLayout.PREFERRED_SIZE)
.addComponent(workerPanel2, GroupLayout.PREFERRED_SIZE, 238, GroupLayout.PREFERRED_SIZE)
.addComponent(workerPanel3, GroupLayout.PREFERRED_SIZE, 238, GroupLayout.PREFERRED_SIZE)
.addComponent(workerPanel4, GroupLayout.PREFERRED_SIZE, 238, GroupLayout.PREFERRED_SIZE))
.addContainerGap(15, Short.MAX_VALUE))
);
gl_upgradesPanel.setVerticalGroup(
gl_upgradesPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_upgradesPanel.createSequentialGroup()
.addContainerGap()
.addComponent(workerPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(workerPanel2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(workerPanel3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(workerPanel4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE))
);
upgradesPanel.setLayout(gl_upgradesPanel);
specialPanel = new JPanel();
specialPanel.setBackground(new Color(0,0,0,0.2f));
specialPanel.setBounds(6, 6, 288, 203);
gamePanel.add(specialPanel);
specialPanel.setLayout(null);
String[] columnNames = {"Upgrades", ""};
Object[][] data =
{
{"Vozík +2", "2000$"},
{"Kalhoty +3", "15000$"},
{"Šperháky +4", "50000$"},
{"Auto *2", "200000$"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames){
#Override
public boolean isCellEditable(int row, int column) {
if(column != 1) return false;
else return true;
}
};
table = new JTable( model );
Action upgradeMultiplier = new AbstractAction()
{
int count = 0;
public void actionPerformed(ActionEvent e)
{
/*
*
JTable table = (JTable)e.getSource();
int modelRow = Integer.valueOf( e.getActionCommand() );
String sPrice = (String) table.getModel().getValueAt(modelRow, 1);
int price = Integer.parseInt(sPrice.substring(0,sPrice.length()-1));
String sMultip = (String) table.getModel().getValueAt(modelRow, 0);
if(sMultip.lastIndexOf("*") != -1) {
int multip = Integer.parseInt(sMultip.substring(sMultip.lastIndexOf("*")+1,sMultip.length()));
if(player.money.getMoney() >= price) {
player.money.deduct(price);
worker.multiplyMultiplier(multip);
((DefaultTableModel)table.getModel()).removeRow(modelRow);
}
} else if(sMultip.lastIndexOf("+") != -1) {
int multip = Integer.parseInt(sMultip.substring(sMultip.lastIndexOf("+")+1,sMultip.length()));
if(player.money.getMoney() >= price) {
player.money.deduct(price);
worker.plusMultiplier(multip);
((DefaultTableModel)table.getModel()).removeRow(modelRow);
}
}
progressBar1.setString(worker.getProfit()+"$");
lblMultiplier.setText(worker.multiplier+"x");
*
*/
}
};
ButtonColumn buttonColumn = new ButtonColumn(table, upgradeMultiplier , 1);
buttonColumn.setMnemonic(KeyEvent.VK_D);
table.setBounds(8, 55, 272, 142);
specialPanel.add(table);
String[] columnNames2 = {"Upgrades", ""};
Object[][] data2 =
{
{"Special +1", "2000$"},
{"Special +3", "15000$"},
{"Special +4", "50000$"},
{"SPecial *2", "200000$"},
};
DefaultTableModel model2 = new DefaultTableModel(data2, columnNames2){
#Override
public boolean isCellEditable(int row, int column) {
if(column != 1) return false;
else return true;
}
};
table2 = new JTable( model2 );
Action specialUpgrade = new AbstractAction()
{
int count = 0;
public void actionPerformed(ActionEvent e)
{
/*
*
JTable table = (JTable)e.getSource();
int modelRow = Integer.valueOf( e.getActionCommand() );
String sPrice = (String) table.getModel().getValueAt(modelRow, 1);
int price = Integer.parseInt(sPrice.substring(0,sPrice.length()-1));
String sMultip = (String) table.getModel().getValueAt(modelRow, 0);
if(sMultip.lastIndexOf("*") != -1) {
int multip = Integer.parseInt(sMultip.substring(sMultip.lastIndexOf("*")+1,sMultip.length()));
if(player.money.getMoney() >= price) {
player.money.deduct(price);
worker.multiplyMultiplier(multip);
((DefaultTableModel)table.getModel()).removeRow(modelRow);
}
} else if(sMultip.lastIndexOf("+") != -1) {
int multip = Integer.parseInt(sMultip.substring(sMultip.lastIndexOf("+")+1,sMultip.length()));
if(player.money.getMoney() >= price) {
player.money.deduct(price);
worker.plusMultiplier(multip);
((DefaultTableModel)table.getModel()).removeRow(modelRow);
}
}
progressBar1.setString(worker.getProfit()+"$");
lblMultiplier.setText(worker.multiplier+"x");
*
*/
}
};
ButtonColumn buttonColumn2 = new ButtonColumn(table, specialUpgrade , 1);
buttonColumn2.setMnemonic(KeyEvent.VK_D);
table2.setBounds(8, 55, 272, 142);
table2.setVisible(false);
specialPanel.add(table2);
upgradesButton = new GameButton();
upgradesButton.setBounds(8, 6, 121, 43);
specialPanel.add(upgradesButton);
upgradesButton.setBackground(new Color(0,0,0,0));
upgradesButton.setLayout(new BorderLayout(0, 0));
GLabel label4 = new GLabel("Upgrades", (GameButton) upgradesButton, SwingConstants.CENTER);
label4.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
table.setVisible(true);
table2.setVisible(false);
}
});
upgradesButton.add(label4);
JPanel specialsButton = new GameButton();
specialsButton.setBounds(159, 6, 121, 43);
specialPanel.add(specialsButton);
specialsButton.setBackground(new Color(0,0,0,0));
specialsButton.setLayout(new BorderLayout(0, 0));
GLabel lblSpecials = new GLabel("Specials", (GameButton) specialsButton, SwingConstants.CENTER);
lblSpecials.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
table.setVisible(false);
table2.setVisible(true);
}
});
specialsButton.add(lblSpecials);
}
}
GamePanel extends JPanel
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class GamePanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
try {
final BufferedImage image = ImageIO.read(new File("./res/gameBackground.jpg"));
g.drawImage(image, 0, 0, 300, 400, this);
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JProgressBar;
public class GProgressbar extends JProgressBar {
private static final long serialVersionUID = 1L;
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
GameButton extends JPanel
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class GameButton extends JPanel {
private static final long serialVersionUID = 1L;
boolean entered = false;
boolean pressed = false;
GameButton that = this;
public GameButton() {
this.setOpaque(true);
this.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
that.entered = true;
that.repaint();
}
#Override
public void mouseExited(MouseEvent e) {
that.entered = false;
that.repaint();
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
that.pressed = true;
that.repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
that.pressed = false;
that.repaint();
}
});
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(0,0,0,0));
g.fillRect(0, 0, WIDTH, HEIGHT);
if(!entered) {
try {
final BufferedImage image = ImageIO.read(new File("./res/button.gif"));
g.drawImage( image, 0, 0, this.getWidth(), this.getHeight(), this);
} catch(IOException e) {
e.printStackTrace();
}
} else if(pressed){
try {
final BufferedImage image = ImageIO.read(new File("./res/buttonpressed.gif"));
g.drawImage( image, 0, 0, this.getWidth(), this.getHeight(), this);
} catch(IOException e) {
e.printStackTrace();
}
} else {
try {
final BufferedImage image = ImageIO.read(new File("./res/buttonactive.gif"));
g.drawImage( image, 0, 0, this.getWidth(), this.getHeight(), this);
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
GLabel extends JLabel
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
public class GLabel extends JLabel{
GameButton that;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(0,0,0,0));
g.fillRect(0, 0, WIDTH, HEIGHT);
}
public GLabel(String s, GameButton that, int center) {
this.setText(s);
this.that = that;
this.setHorizontalAlignment(center);
setForeground(Color.BLACK);
setFont(Menu.fontTerminal.deriveFont(15f));
setBackground(new Color(0,0,0,0));
this.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
that.entered = true;
that.repaint();
}
#Override
public void mouseExited(MouseEvent e) {
that.entered = false;
that.repaint();
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
that.pressed = true;
that.repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
that.pressed = false;
that.repaint();
}
});
}
}
I want to make the background fully transparent.
Then all you need is:
component.setOpaque( false );
If you need partial transparency of the background then you will get artifacts as you will be breaking the painting contract with Swing components and the opaque property. Check out
Backgrounds With Transparency for more information and solutions to this problem.
Looks like you set a fully transparent JPanel for 'workerPanel1'.
As such, the background is showing behind the JPanel.
Instead of:
workerPanel1.setBackground(new Color(0,0,0,0))
use:
workerPanel1.setBackground(new Color(0,0,0))
(which is the same as: new Color(0,0,0,255))
Edit:
If you wish to keep a transparent panel, you can do so with JPanel#setOpaque(false).
When opaque is false, the panel does not draw its background at all and you will have to keep in mind whatever is displayed behind that panel.
Currently, you have two buttons showing behind it, so you might setVisible(false) them or remove them while this panel is active.

NullPointerException on calling getter method [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
I have three classes TestGUI , MainFrame and ReportsJPanel.
MainFrame object is passed as parameter in ReportsJPanel constructor. When I try to call getter method of MainFrame object that was passed and get the value of private variable, from ReportsJPanel object I get the NullPointerException error. Error happens on this line in ReportsJPanel instalationLocation=mainFrame.getInstalationLocation();
Code for TestGUI:
package testgui;
public class TestGUI {
public static void main(String[] args) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(RiskManagerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RiskManagerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RiskManagerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RiskManagerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
MainFrame mainFrame = new MainFrame();
mainFrame.initComponents();
mainFrame.setVisible(true);
}
});
}
}
Code for MainFrame:
package testgui;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import left_panel_package.ReportsJPanel;
public class MainFrame extends JFrame{
private String instalationLocation;
public MainFrame(){
setInstalationLocation("TEST_Location");
}
public void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("TEST");
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.setBackground(new Color(0, 0, 0));
JPanel leftPanel = new JPanel();
leftPanel.setBackground(new Color(255, 0, 0));
leftPanel.setPreferredSize(new Dimension(200,100));
leftPanel.setLayout(new GridLayout(3,0));
JPanel rightPanel = new JPanel();
rightPanel.setBackground(new Color(0, 255, 0));
rightPanel.setPreferredSize(new Dimension(200,100));
JPanel centerPanel = new JPanel();
centerPanel.setBackground(new Color(0, 0, 255));
JPanel toolBar = new JPanel();
toolBar.setBackground(new Color(0, 255, 255));
toolBar.setPreferredSize(new Dimension(100,100));
ReportsJPanel reportsPanel = new ReportsJPanel(this);
reportsPanel.initComponents();
leftPanel.add(reportsPanel);
mainPanel.add(leftPanel, BorderLayout.WEST);
mainPanel.add(rightPanel, BorderLayout.EAST);
mainPanel.add(centerPanel, BorderLayout.CENTER);
mainPanel.add(toolBar, BorderLayout.NORTH);
setContentPane(mainPanel);
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();
setSize(width, height);
setLocationRelativeTo(null);
}
public String getInstalationLocation() {
return instalationLocation;
}
private void setInstalationLocation(String instalationLocation) {
this.instalationLocation = instalationLocation;
}
}
Code for ReportsJPanel:
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import testgui.MainFrame;
public class ReportsJPanel extends JPanel{
private MainFrame mainFrame;
private String instalationLocation;
public ReportsJPanel (MainFrame mainframe){
this.mainFrame=mainFrame;
setBorder(new TitledBorder("Reports"));
}
public void initComponents(){
instalationLocation=mainFrame.getInstalationLocation();
}
}
Simple typo. In your constructor for your ReportsJPanel you have this.
public ReportsJPanel(MainFrame mainframe) {
this.mainFrame = mainFrame;
setBorder(new TitledBorder("Reports"));
}
You need to capitalize the f in the MainFrame object that you pass to the constructor.
public ReportsJPanel(MainFrame mainFrame) {
this.mainFrame = mainFrame;
setBorder(new TitledBorder("Reports"));
}
Otherwise, you will be setting this.mainFrame to itself, and the mainframe you pass in will not be used.
public ReportsJPanel (MainFrame mainframe){
this.mainFrame=mainFrame;
setBorder(new TitledBorder("Reports"));
}
names not matching in your code this.mainFrame = mainframe;
method parameter name is mainframe
I suggest you to use eclipse like IDE tool

repaint() method not calling paintComponent()

for my program I currently want to use the open button to open a JFileChooser and select an image and then draw it on the JPanel on the left side of the applet, I know that the file is being retrieved but when i go to repaint the graphics context nothing happens. Thanks in advance.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
public class FinalProject390 {
public static void main(String[] args) {
createAndShowGUI();
}
private static void createAndShowGUI() {
JFrame f = new JFrame("Final Project");
f.setSize(1025, 520);
f.add(new GraphicsPanel());
f.add(new MainPanel());
f.setVisible(true);
}
}
class MainPanel extends JPanel implements ActionListener {
JButton openButton = new JButton("Open");
JButton newButton = new JButton("New");
JButton saveButton = new JButton("Save");
JButton saveAsButton = new JButton("Save As");
JButton drawLineButton = new JButton("Draw Line");
JButton drawRectangleButton = new JButton("Draw Rectangle");
JButton drawOvalButton = new JButton("Draw Oval");
JButton drawArcButton = new JButton("Draw Arc");
JButton extractPixelDataButton = new JButton("Extract Pixel Data");
JButton convoluteButton = new JButton("Convolute");
JTextField xPosStartField = new JTextField("x-Position Start");
JTextField yPosStartField = new JTextField("y-Position Start");
JTextField xPosEndField = new JTextField("x-Position End");
JTextField yPosEndField = new JTextField("y-Position End");
JTextField angleStartField = new JTextField("Angle Start");
JTextField angleSizeField = new JTextField("Angle Size");
public MainPanel() {
openButton.setBounds(660, 50, 100, 30);
openButton.addActionListener(this);
newButton.setBounds(780, 50, 100, 30);
saveButton.setBounds(900, 50, 100, 30);
drawLineButton.setBounds(660, 110, 160, 30);
drawRectangleButton.setBounds(840, 110, 160, 30);
drawOvalButton.setBounds(660, 155, 160, 30);
drawArcButton.setBounds(840, 155, 160, 30);
extractPixelDataButton.setBounds(660, 220, 160, 30);
convoluteButton.setBounds(840, 220, 160, 30);
xPosStartField.setBounds(660, 280, 100, 30);
yPosStartField.setBounds(660, 320, 100, 30);
xPosEndField.setBounds(660, 380, 100, 30);
yPosEndField.setBounds(660, 420, 100, 30);
angleStartField.setBounds(900, 280, 100, 30);
angleSizeField.setBounds(900, 320, 100, 30);
setLayout(null);
setBackground(Color.green);
setBounds(641, 0, 370, 480);
add(openButton);
add(newButton);
add(saveButton);
add(drawLineButton);
add(drawRectangleButton);
add(drawOvalButton);
add(drawArcButton);
add(extractPixelDataButton);
add(convoluteButton);
add(xPosStartField);
add(yPosStartField);
add(xPosEndField);
add(yPosEndField);
add(angleStartField);
add(angleSizeField);
}
#Override
public void actionPerformed(ActionEvent e) {
javax.swing.JFileChooser fileChooser = new JFileChooser();
BufferedImage bin = null, bi = null;
GraphicsPanel gPanel = new GraphicsPanel();
fileChooser.setCurrentDirectory(new File(System
.getProperty("user.home")));
int result = fileChooser.showOpenDialog(null);
if (result == javax.swing.JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: "
+ selectedFile.getAbsolutePath());
try {
bin = ImageIO.read(new File(selectedFile.getAbsolutePath()));
} catch (IOException e1) {
e1.printStackTrace();
}
gPanel.setImg(bin);
}
}
}
class GraphicsPanel extends JPanel {
BufferedImage bi = null, bin = null;
public GraphicsPanel() {
setLayout(null);
setBackground(Color.blue);
setSize(640, 480);
setLocation(0, 0);
}
public void setImg(BufferedImage b) {
this.bi = b;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bi, 0, 0, null);
}
}
This looks like a homework assignment, so rather than an outright answer with code, instead please consider the following:
In your method createAndShowGUI() you instantiate a GraphicsPanel object and add it to a JFrame
In your actionPerformed() method, you instantiate another GraphicsPanel object (which is never added to the JFrame) and you call setImage().
Your image does not display because the GraphicsPanel control that has been added to your JFrame is not the same GraphicsPanel control that you set the image on.
I hope this will be enough to help you fix your code.

Swing - drawString shifting animation fails

I'm trying to make a little animation on Java swing, which should move the drawString's string a little to left(to center), however, whenever I try to do it, the program just slowly opens and just jumps to the place where It should land eventually, so seemingly, there no animation occurs.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.Border;
public class IntroPanel extends JPanel {
private int x = 300;
private JButton exitButton, startButton;
private JPanel buttonsPanel;
public IntroPanel()
{
setPreferredSize( new Dimension( 300, 150));
setLayout( new BorderLayout());
buttonsPanel = new JPanel();
exitButton = new JButton( "Exit" );
startButton = new JButton( "Start" );
exitButton.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
startButton.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/**
* TODO GOES TO MAIN PANEL
*/
}
});
setBackground( new Color( 250, 250, 250) );
startButton.setPreferredSize( new Dimension(70, 40) );
exitButton.setPreferredSize( new Dimension(70, 40) );
Border padding = BorderFactory.createEmptyBorder(0, 0, 25, 0);
setBorder(padding);
buttonsPanel.setBackground( new Color( 250, 250, 250));
buttonsPanel.add(startButton);
buttonsPanel.add(exitButton);
add(buttonsPanel, BorderLayout.SOUTH);
animate();
}
public void animate()
{
for( int i = 1; i < 211; i++ )
{
x--;
repaint();
try
{
Thread.sleep(10);
}
catch(InterruptedException ex) { }
}
}
public void paintComponent( Graphics page )
{
Graphics2D gra = (Graphics2D) page;
gra.setFont( new Font( "Philosopher-BoldItalic", Font.ITALIC | Font.BOLD, 50 ) );
Color start = new Color( 50, 50, 50 );
Color end = new Color( 250, 250, 250 );
GradientPaint gradient =
new GradientPaint( 120, 100, start, 270, 270, end);
gra.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
gra.setPaint( gradient );
gra.drawString("Geometrica", x, 100);
}
}
Main method:
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame( "Geometrica" );
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(420, 250);
frame.setBackground( new Color(250, 250, 250) );
frame.setLocationRelativeTo(null);
frame.getContentPane().add( new IntroPanel() );
frame.setVisible(true);
}
}
Thank you!
Call the animate method after the frame is made visible from outside the object.
Also you need to call super.paintComponent(page); inside your animate method like it says in the Javadoc then you'll get the desired result.
Main:
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame( "Geometrica" );
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(420, 250);
frame.setBackground( new Color(250, 250, 250) );
frame.setLocationRelativeTo(null);
IntroPanel p=new IntroPanel();
frame.getContentPane().add(p);
frame.setVisible(true);
p.animate();
}
}
IntroPanel:
public class IntroPanel extends JPanel {
private int x = 300;
private JButton exitButton, startButton;
private JPanel buttonsPanel;
public IntroPanel()
{
setPreferredSize( new Dimension( 300, 150));
setLayout( new BorderLayout());
buttonsPanel = new JPanel();
exitButton = new JButton( "Exit" );
startButton = new JButton( "Start" );
exitButton.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
startButton.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/**
* TODO GOES TO MAIN PANEL
*/
}
});
setBackground( new Color( 250, 250, 250) );
startButton.setPreferredSize( new Dimension(70, 40) );
exitButton.setPreferredSize( new Dimension(70, 40) );
Border padding = BorderFactory.createEmptyBorder(0, 0, 25, 0);
setBorder(padding);
buttonsPanel.setBackground( new Color( 250, 250, 250));
buttonsPanel.add(startButton);
buttonsPanel.add(exitButton);
add(buttonsPanel, BorderLayout.SOUTH);
}
public void animate()
{
super.paintComponent(page);
for( int i = 1; i < 211; i++ )
{
x--;
repaint();
try
{
Thread.sleep(10);
}
catch(InterruptedException ex) { }
}
}
public void paintComponent( Graphics page )
{
Graphics2D gra = (Graphics2D) page;
gra.setFont( new Font( "Philosopher-BoldItalic", Font.ITALIC | Font.BOLD, 50 ) );
Color start = new Color( 50, 50, 50 );
Color end = new Color( 250, 250, 250 );
GradientPaint gradient =
new GradientPaint( 120, 100, start, 270, 270, end);
gra.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
gra.setPaint( gradient );
gra.drawString("Geometrica", x, 100);
}
}

Categories